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/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/node-gyp-build b/node_modules/.bin/node-gyp-build new file mode 100644 index 0000000..78d3889 --- /dev/null +++ b/node_modules/.bin/node-gyp-build @@ -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/../node-gyp-build/bin.js" "$@" +else + exec node "$basedir/../node-gyp-build/bin.js" "$@" +fi diff --git a/node_modules/.bin/node-gyp-build-optional b/node_modules/.bin/node-gyp-build-optional new file mode 100644 index 0000000..03297c5 --- /dev/null +++ b/node_modules/.bin/node-gyp-build-optional @@ -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/../node-gyp-build/optional.js" "$@" +else + exec node "$basedir/../node-gyp-build/optional.js" "$@" +fi diff --git a/node_modules/.bin/node-gyp-build-optional.cmd b/node_modules/.bin/node-gyp-build-optional.cmd new file mode 100644 index 0000000..74d85f2 --- /dev/null +++ b/node_modules/.bin/node-gyp-build-optional.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%\..\node-gyp-build\optional.js" %* diff --git a/node_modules/.bin/node-gyp-build-optional.ps1 b/node_modules/.bin/node-gyp-build-optional.ps1 new file mode 100644 index 0000000..45995c3 --- /dev/null +++ b/node_modules/.bin/node-gyp-build-optional.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/../node-gyp-build/optional.js" $args + } else { + & "$basedir/node$exe" "$basedir/../node-gyp-build/optional.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../node-gyp-build/optional.js" $args + } else { + & "node$exe" "$basedir/../node-gyp-build/optional.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/node-gyp-build-test b/node_modules/.bin/node-gyp-build-test new file mode 100644 index 0000000..049fa6a --- /dev/null +++ b/node_modules/.bin/node-gyp-build-test @@ -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/../node-gyp-build/build-test.js" "$@" +else + exec node "$basedir/../node-gyp-build/build-test.js" "$@" +fi diff --git a/node_modules/.bin/node-gyp-build-test.cmd b/node_modules/.bin/node-gyp-build-test.cmd new file mode 100644 index 0000000..182a757 --- /dev/null +++ b/node_modules/.bin/node-gyp-build-test.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%\..\node-gyp-build\build-test.js" %* diff --git a/node_modules/.bin/node-gyp-build-test.ps1 b/node_modules/.bin/node-gyp-build-test.ps1 new file mode 100644 index 0000000..6cb0b9b --- /dev/null +++ b/node_modules/.bin/node-gyp-build-test.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/../node-gyp-build/build-test.js" $args + } else { + & "$basedir/node$exe" "$basedir/../node-gyp-build/build-test.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../node-gyp-build/build-test.js" $args + } else { + & "node$exe" "$basedir/../node-gyp-build/build-test.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/node-gyp-build.cmd b/node_modules/.bin/node-gyp-build.cmd new file mode 100644 index 0000000..ac854a6 --- /dev/null +++ b/node_modules/.bin/node-gyp-build.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%\..\node-gyp-build\bin.js" %* diff --git a/node_modules/.bin/node-gyp-build.ps1 b/node_modules/.bin/node-gyp-build.ps1 new file mode 100644 index 0000000..c1f9a9a --- /dev/null +++ b/node_modules/.bin/node-gyp-build.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/../node-gyp-build/bin.js" $args + } else { + & "$basedir/node$exe" "$basedir/../node-gyp-build/bin.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../node-gyp-build/bin.js" $args + } else { + & "node$exe" "$basedir/../node-gyp-build/bin.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/rollup b/node_modules/.bin/rollup new file mode 100644 index 0000000..11bd86d --- /dev/null +++ b/node_modules/.bin/rollup @@ -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/../rollup/dist/bin/rollup" "$@" +else + exec node "$basedir/../rollup/dist/bin/rollup" "$@" +fi diff --git a/node_modules/.bin/rollup.cmd b/node_modules/.bin/rollup.cmd new file mode 100644 index 0000000..b3f110b --- /dev/null +++ b/node_modules/.bin/rollup.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%\..\rollup\dist\bin\rollup" %* diff --git a/node_modules/.bin/rollup.ps1 b/node_modules/.bin/rollup.ps1 new file mode 100644 index 0000000..10f657d --- /dev/null +++ b/node_modules/.bin/rollup.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/../rollup/dist/bin/rollup" $args + } else { + & "$basedir/node$exe" "$basedir/../rollup/dist/bin/rollup" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../rollup/dist/bin/rollup" $args + } else { + & "node$exe" "$basedir/../rollup/dist/bin/rollup" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/svelte-kit b/node_modules/.bin/svelte-kit new file mode 100644 index 0000000..610e55b --- /dev/null +++ b/node_modules/.bin/svelte-kit @@ -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/../@sveltejs/kit/svelte-kit.js" "$@" +else + exec node "$basedir/../@sveltejs/kit/svelte-kit.js" "$@" +fi diff --git a/node_modules/.bin/svelte-kit.cmd b/node_modules/.bin/svelte-kit.cmd new file mode 100644 index 0000000..38d52f9 --- /dev/null +++ b/node_modules/.bin/svelte-kit.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%\..\@sveltejs\kit\svelte-kit.js" %* diff --git a/node_modules/.bin/svelte-kit.ps1 b/node_modules/.bin/svelte-kit.ps1 new file mode 100644 index 0000000..1ac1f3f --- /dev/null +++ b/node_modules/.bin/svelte-kit.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/../@sveltejs/kit/svelte-kit.js" $args + } else { + & "$basedir/node$exe" "$basedir/../@sveltejs/kit/svelte-kit.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../@sveltejs/kit/svelte-kit.js" $args + } else { + & "node$exe" "$basedir/../@sveltejs/kit/svelte-kit.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/vite b/node_modules/.bin/vite new file mode 100644 index 0000000..a85d325 --- /dev/null +++ b/node_modules/.bin/vite @@ -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/../vite/bin/vite.js" "$@" +else + exec node "$basedir/../vite/bin/vite.js" "$@" +fi diff --git a/node_modules/.bin/vite.cmd b/node_modules/.bin/vite.cmd new file mode 100644 index 0000000..f62e966 --- /dev/null +++ b/node_modules/.bin/vite.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%\..\vite\bin\vite.js" %* diff --git a/node_modules/.bin/vite.ps1 b/node_modules/.bin/vite.ps1 new file mode 100644 index 0000000..a7759bc --- /dev/null +++ b/node_modules/.bin/vite.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/../vite/bin/vite.js" $args + } else { + & "$basedir/node$exe" "$basedir/../vite/bin/vite.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../vite/bin/vite.js" $args + } else { + & "node$exe" "$basedir/../vite/bin/vite.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.cache/@babel/register/.babel.7.5.5.development.json b/node_modules/.cache/@babel/register/.babel.7.5.5.development.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/node_modules/.cache/@babel/register/.babel.7.5.5.development.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..b7afcb2 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,980 @@ +{ + "name": "crimson-eagle-notes-app", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@ampproject/remapping": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.1.tgz", + "integrity": "sha512-lFMjJTrFL3j7L9yBxwYfCq2k6qqwHyzuUl/XBnif78PWTJYyL/dfowQHWE3sp6U6ZzqWiiIZnpTMO96zhkjwtg==", + "peer": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.0", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.18.17", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.18.17.tgz", + "integrity": "sha512-fGEb8f2BSA3CW7riJVurug65ACLuQAzKq0SSqkY2b2yHHH0MzDfbLyKIGzHwOI/gkHcxM/leuSW6D5w/LMNitA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz", + "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==", + "peer": true, + "dependencies": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz", + "integrity": "sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==", + "peer": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", + "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", + "peer": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", + "peer": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.18", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.18.tgz", + "integrity": "sha512-w+niJYzMHdd7USdiH2U6869nqhD2nbfZXND5Yp93qIbEmnDNk7PD48o+YchRVpzMU7M6jVCbenTR7PA1FLQ9pA==", + "peer": true, + "dependencies": { + "@jridgewell/resolve-uri": "3.1.0", + "@jridgewell/sourcemap-codec": "1.4.14" + } + }, + "node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.14", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz", + "integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==", + "peer": true + }, + "node_modules/@polka/url": { + "version": "1.0.0-next.21", + "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.21.tgz", + "integrity": "sha512-a5Sab1C4/icpTZVzZc5Ghpz88yQtGOyNqYXcZgOssB2uuAr+wF/MvN6bgtW32q7HHrvBki+BsZ0OuNv6EV3K9g==", + "peer": true + }, + "node_modules/@supabase/auth-helpers-shared": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@supabase/auth-helpers-shared/-/auth-helpers-shared-0.4.1.tgz", + "integrity": "sha512-IEDX9JzWkIjQiLUaP4Qy5YDiG0jFQatWfS+jw8cCQs6QfbNdEPd2Y3qonwGHnM90CZom9SvjuylBv2pFVAL7Lw==", + "dependencies": { + "jose": "^4.14.3" + }, + "peerDependencies": { + "@supabase/supabase-js": "^2.19.0" + } + }, + "node_modules/@supabase/auth-helpers-sveltekit": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/@supabase/auth-helpers-sveltekit/-/auth-helpers-sveltekit-0.10.1.tgz", + "integrity": "sha512-28pXA76s7lhw5YSbfB8d8goh7UKHZk2GCU2lIsf3KQLfBhIeYtwO3SL7SNKa50x9enFGgIQjlHj6ukSYeeR+1A==", + "dependencies": { + "@supabase/auth-helpers-shared": "0.4.1" + }, + "peerDependencies": { + "@supabase/supabase-js": "^2.19.0", + "@sveltejs/kit": "^1.15.4" + } + }, + "node_modules/@supabase/functions-js": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.1.2.tgz", + "integrity": "sha512-QCR6pwJs9exCl37bmpMisUd6mf+0SUBJ6mUpiAjEkSJ/+xW8TCuO14bvkWHADd5hElJK9MxNlMQXxSA4DRz9nQ==", + "dependencies": { + "cross-fetch": "^3.1.5" + } + }, + "node_modules/@supabase/gotrue-js": { + "version": "2.46.1", + "resolved": "https://registry.npmjs.org/@supabase/gotrue-js/-/gotrue-js-2.46.1.tgz", + "integrity": "sha512-tebFX3XvPqEJKHOVgkXTN20g9iUhLx6tebIYQvTggYTrqOT2af8oTpSBdgYzbwJ291G6P6CSpR6KY0cT9ade5A==", + "dependencies": { + "cross-fetch": "^3.1.5" + } + }, + "node_modules/@supabase/postgrest-js": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-1.7.2.tgz", + "integrity": "sha512-GK80JpRq8l6Qll85erICypAfQCied8tdlXfsDN14W844HqXCSOisk8AaE01DAwGJanieaoN5fuqhzA2yKxDvEQ==", + "dependencies": { + "cross-fetch": "^3.1.5" + } + }, + "node_modules/@supabase/realtime-js": { + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.7.3.tgz", + "integrity": "sha512-c7TzL81sx2kqyxsxcDduJcHL9KJdCOoKimGP6lQSqiZKX42ATlBZpWbyy9KFGFBjAP4nyopMf5JhPi2ZH9jyNw==", + "dependencies": { + "@types/phoenix": "^1.5.4", + "@types/websocket": "^1.0.3", + "websocket": "^1.0.34" + } + }, + "node_modules/@supabase/storage-js": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.5.1.tgz", + "integrity": "sha512-nkR0fQA9ScAtIKA3vNoPEqbZv1k5B5HVRYEvRWdlP6mUpFphM9TwPL2jZ/ztNGMTG5xT6SrHr+H7Ykz8qzbhjw==", + "dependencies": { + "cross-fetch": "^3.1.5" + } + }, + "node_modules/@supabase/supabase-js": { + "version": "2.31.0", + "resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.31.0.tgz", + "integrity": "sha512-W9/4s+KnSUX67wJKBn/3yLq+ieycnMzVjK3nNTLX5Wko3ypNT/081l2iFYrf+nsLQ1CiT4mA92I3dxCy6CmxTg==", + "dependencies": { + "@supabase/functions-js": "^2.1.0", + "@supabase/gotrue-js": "^2.46.1", + "@supabase/postgrest-js": "^1.7.0", + "@supabase/realtime-js": "^2.7.3", + "@supabase/storage-js": "^2.5.1", + "cross-fetch": "^3.1.5" + } + }, + "node_modules/@sveltejs/kit": { + "version": "1.22.4", + "resolved": "https://registry.npmjs.org/@sveltejs/kit/-/kit-1.22.4.tgz", + "integrity": "sha512-Opkqw1QXk4Cc25b/heJP2D7mX+OUBFAq4MXKfET58svTTxdeiHFKzmnuRsSF3nmxESqrLjqPAgHpib+knNGzRw==", + "hasInstallScript": true, + "peer": true, + "dependencies": { + "@sveltejs/vite-plugin-svelte": "^2.4.1", + "@types/cookie": "^0.5.1", + "cookie": "^0.5.0", + "devalue": "^4.3.1", + "esm-env": "^1.0.0", + "kleur": "^4.1.5", + "magic-string": "^0.30.0", + "mime": "^3.0.0", + "sade": "^1.8.1", + "set-cookie-parser": "^2.6.0", + "sirv": "^2.0.2", + "undici": "~5.22.0" + }, + "bin": { + "svelte-kit": "svelte-kit.js" + }, + "engines": { + "node": "^16.14 || >=18" + }, + "peerDependencies": { + "svelte": "^3.54.0 || ^4.0.0-next.0", + "vite": "^4.0.0" + } + }, + "node_modules/@sveltejs/vite-plugin-svelte": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte/-/vite-plugin-svelte-2.4.3.tgz", + "integrity": "sha512-NY2h+B54KHZO3kDURTdARqthn6D4YSIebtfW75NvZ/fwyk4G+AJw3V/i0OBjyN4406Ht9yZcnNWMuRUFnDNNiA==", + "peer": true, + "dependencies": { + "@sveltejs/vite-plugin-svelte-inspector": "^1.0.3", + "debug": "^4.3.4", + "deepmerge": "^4.3.1", + "kleur": "^4.1.5", + "magic-string": "^0.30.1", + "svelte-hmr": "^0.15.2", + "vitefu": "^0.2.4" + }, + "engines": { + "node": "^14.18.0 || >= 16" + }, + "peerDependencies": { + "svelte": "^3.54.0 || ^4.0.0", + "vite": "^4.0.0" + } + }, + "node_modules/@sveltejs/vite-plugin-svelte-inspector": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte-inspector/-/vite-plugin-svelte-inspector-1.0.3.tgz", + "integrity": "sha512-Khdl5jmmPN6SUsVuqSXatKpQTMIifoQPDanaxC84m9JxIibWvSABJyHpyys0Z+1yYrxY5TTEQm+6elh0XCMaOA==", + "peer": true, + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": "^14.18.0 || >= 16" + }, + "peerDependencies": { + "@sveltejs/vite-plugin-svelte": "^2.2.0", + "svelte": "^3.54.0 || ^4.0.0", + "vite": "^4.0.0" + } + }, + "node_modules/@types/cookie": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.5.1.tgz", + "integrity": "sha512-COUnqfB2+ckwXXSFInsFdOAWQzCCx+a5hq2ruyj+Vjund94RJQd4LG2u9hnvJrTgunKAaax7ancBYlDrNYxA0g==", + "peer": true + }, + "node_modules/@types/estree": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.1.tgz", + "integrity": "sha512-LG4opVs2ANWZ1TJoKc937iMmNstM/d0ae1vNbnBvBhqCSezgVUOzcLCqbI5elV8Vy6WKwKjaqR+zO9VKirBBCA==", + "peer": true + }, + "node_modules/@types/node": { + "version": "20.4.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.5.tgz", + "integrity": "sha512-rt40Nk13II9JwQBdeYqmbn2Q6IVTA5uPhvSO+JVqdXw/6/4glI6oR9ezty/A9Hg5u7JH4OmYmuQ+XvjKm0Datg==" + }, + "node_modules/@types/phoenix": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@types/phoenix/-/phoenix-1.6.0.tgz", + "integrity": "sha512-qwfpsHmFuhAS/dVd4uBIraMxRd56vwBUYQGZ6GpXnFuM2XMRFJbIyruFKKlW2daQliuYZwe0qfn/UjFCDKic5g==" + }, + "node_modules/@types/websocket": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@types/websocket/-/websocket-1.0.5.tgz", + "integrity": "sha512-NbsqiNX9CnEfC1Z0Vf4mE1SgAJ07JnRYcNex7AJ9zAVzmiGHmjKFEk7O4TJIsgv2B1sLEb6owKFZrACwdYngsQ==", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/acorn": { + "version": "8.10.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.10.0.tgz", + "integrity": "sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw==", + "peer": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/aria-query": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", + "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", + "peer": true, + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/axobject-query": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-3.2.1.tgz", + "integrity": "sha512-jsyHu61e6N4Vbz/v18DHwWYKK0bSWLqn47eeDSKPB7m8tqMHF9YJ+mhIk2lVteyZrY8tnSj/jHOv4YiTCuCJgg==", + "peer": true, + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/bufferutil": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.7.tgz", + "integrity": "sha512-kukuqc39WOHtdxtw4UScxF/WVnMFVSQVKhtx3AjZJzhd0RGZZldcrfSEbVsWWe6KNH253574cq5F+wpv0G9pJw==", + "hasInstallScript": true, + "dependencies": { + "node-gyp-build": "^4.3.0" + }, + "engines": { + "node": ">=6.14.2" + } + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "peer": true, + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/code-red": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/code-red/-/code-red-1.0.3.tgz", + "integrity": "sha512-kVwJELqiILQyG5aeuyKFbdsI1fmQy1Cmf7dQ8eGmVuJoaRVdwey7WaMknr2ZFeVSYSKT0rExsa8EGw0aoI/1QQ==", + "peer": true, + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.14", + "@types/estree": "^1.0.0", + "acorn": "^8.8.2", + "estree-walker": "^3.0.3", + "periscopic": "^3.1.0" + } + }, + "node_modules/cookie": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", + "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", + "peer": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cross-fetch": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.1.8.tgz", + "integrity": "sha512-cvA+JwZoU0Xq+h6WkMvAUqPEYy92Obet6UdKLfW60qn99ftItKjB5T+BkyWOFWe2pUyfQ+IJHmpOTznqk1M6Kg==", + "dependencies": { + "node-fetch": "^2.6.12" + } + }, + "node_modules/css-tree": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-2.3.1.tgz", + "integrity": "sha512-6Fv1DV/TYw//QF5IzQdqsNDjx/wc8TrMBZsqjL9eW01tWb7R7k/mq+/VXfJCl7SoD5emsJop9cOByJZfs8hYIw==", + "peer": true, + "dependencies": { + "mdn-data": "2.0.30", + "source-map-js": "^1.0.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, + "node_modules/d": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/d/-/d-1.0.1.tgz", + "integrity": "sha512-m62ShEObQ39CfralilEQRjH6oAMtNCV1xJyEx5LpRYUVN+EviphDgUc/F3hnYbADmkiNs67Y+3ylmlG7Lnu+FA==", + "dependencies": { + "es5-ext": "^0.10.50", + "type": "^1.0.1" + } + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "peer": true, + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/devalue": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/devalue/-/devalue-4.3.2.tgz", + "integrity": "sha512-KqFl6pOgOW+Y6wJgu80rHpo2/3H07vr8ntR9rkkFIRETewbf5GaYYcakYfiKz89K+sLsuPkQIZaXDMjUObZwWg==", + "peer": true + }, + "node_modules/es5-ext": { + "version": "0.10.62", + "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.62.tgz", + "integrity": "sha512-BHLqn0klhEpnOKSrzn/Xsz2UIW8j+cGmo9JLzr8BiUapV8hPL9+FliFqjwr9ngW7jWdnxv6eO+/LqyhJVqgrjA==", + "hasInstallScript": true, + "dependencies": { + "es6-iterator": "^2.0.3", + "es6-symbol": "^3.1.3", + "next-tick": "^1.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/es6-iterator": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", + "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==", + "dependencies": { + "d": "1", + "es5-ext": "^0.10.35", + "es6-symbol": "^3.1.1" + } + }, + "node_modules/es6-symbol": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.3.tgz", + "integrity": "sha512-NJ6Yn3FuDinBaBRWl/q5X/s4koRHBrgKAu+yGI6JCBeiu3qrcbJhwT2GeR/EXVfylRk8dpQVJoLEFhK+Mu31NA==", + "dependencies": { + "d": "^1.0.1", + "ext": "^1.1.2" + } + }, + "node_modules/esbuild": { + "version": "0.18.17", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.18.17.tgz", + "integrity": "sha512-1GJtYnUxsJreHYA0Y+iQz2UEykonY66HNWOb0yXYZi9/kNrORUEHVg87eQsCtqh59PEJ5YVZJO98JHznMJSWjg==", + "hasInstallScript": true, + "peer": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/android-arm": "0.18.17", + "@esbuild/android-arm64": "0.18.17", + "@esbuild/android-x64": "0.18.17", + "@esbuild/darwin-arm64": "0.18.17", + "@esbuild/darwin-x64": "0.18.17", + "@esbuild/freebsd-arm64": "0.18.17", + "@esbuild/freebsd-x64": "0.18.17", + "@esbuild/linux-arm": "0.18.17", + "@esbuild/linux-arm64": "0.18.17", + "@esbuild/linux-ia32": "0.18.17", + "@esbuild/linux-loong64": "0.18.17", + "@esbuild/linux-mips64el": "0.18.17", + "@esbuild/linux-ppc64": "0.18.17", + "@esbuild/linux-riscv64": "0.18.17", + "@esbuild/linux-s390x": "0.18.17", + "@esbuild/linux-x64": "0.18.17", + "@esbuild/netbsd-x64": "0.18.17", + "@esbuild/openbsd-x64": "0.18.17", + "@esbuild/sunos-x64": "0.18.17", + "@esbuild/win32-arm64": "0.18.17", + "@esbuild/win32-ia32": "0.18.17", + "@esbuild/win32-x64": "0.18.17" + } + }, + "node_modules/esm-env": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.0.0.tgz", + "integrity": "sha512-Cf6VksWPsTuW01vU9Mk/3vRue91Zevka5SjyNf3nEpokFRuqt/KjUQoGAwq9qMmhpLTHmXzSIrFRw8zxWzmFBA==", + "peer": true + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "peer": true, + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/ext": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/ext/-/ext-1.7.0.tgz", + "integrity": "sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==", + "dependencies": { + "type": "^2.7.2" + } + }, + "node_modules/ext/node_modules/type": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/type/-/type-2.7.2.tgz", + "integrity": "sha512-dzlvlNlt6AXU7EBSfpAscydQ7gXB+pPGsPnfJnZpiNJBDj7IaJzQlBZYGdEi4R9HmPdBv2XmWJ6YUtoTa7lmCw==" + }, + "node_modules/is-reference": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.1.tgz", + "integrity": "sha512-baJJdQLiYaJdvFbJqXrcGv3WU3QCzBlUcI5QhbesIm6/xPsvmO+2CDoi/GMOFBQEQm+PXkwOPrp9KK5ozZsp2w==", + "peer": true, + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==" + }, + "node_modules/jose": { + "version": "4.14.4", + "resolved": "https://registry.npmjs.org/jose/-/jose-4.14.4.tgz", + "integrity": "sha512-j8GhLiKmUAh+dsFXlX1aJCbt5KMibuKb+d7j1JaOJG6s2UjX1PQlW+OKB/sD4a/5ZYF4RcmYmLSndOoU3Lt/3g==", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/locate-character": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz", + "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==", + "peer": true + }, + "node_modules/magic-string": { + "version": "0.30.2", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.2.tgz", + "integrity": "sha512-lNZdu7pewtq/ZvWUp9Wpf/x7WzMTsR26TWV03BRZrXFsv+BI6dy8RAiKgm1uM/kyR0rCfUcqvOlXKG66KhIGug==", + "peer": true, + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/mdn-data": { + "version": "2.0.30", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.30.tgz", + "integrity": "sha512-GaqWWShW4kv/G9IEucWScBx9G1/vsFZZJUO+tD26M8J8z3Kw5RDQjaoZe03YAClgeS/SWPOcb4nkFBTEi5DUEA==", + "peer": true + }, + "node_modules/mime": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", + "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==", + "peer": true, + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/mrmime": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-1.0.1.tgz", + "integrity": "sha512-hzzEagAgDyoU1Q6yg5uI+AorQgdvMCur3FcKf7NhMKWsaYg+RnbTyHRa/9IlLF9rf455MOCtcqqrQQ83pPP7Uw==", + "peer": true, + "engines": { + "node": ">=10" + } + }, + "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==", + "peer": true + }, + "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==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "peer": true, + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/next-tick": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.1.0.tgz", + "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==" + }, + "node_modules/node-fetch": { + "version": "2.6.12", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.12.tgz", + "integrity": "sha512-C/fGU2E8ToujUivIO0H+tpQ6HWo4eEmchoPIoXtxCrVghxdKq+QOHqEZW7tuP3KlV3bC8FRMO5nMCC7Zm1VP6g==", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/node-gyp-build": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.6.0.tgz", + "integrity": "sha512-NTZVKn9IylLwUzaKjkas1e4u2DLNcV4rdYagA4PWdPwW87Bi7z+BznyKSRwS/761tV/lzCGXplWsiaMjLqP2zQ==", + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/periscopic": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/periscopic/-/periscopic-3.1.0.tgz", + "integrity": "sha512-vKiQ8RRtkl9P+r/+oefh25C3fhybptkHKCZSPlcXiJux2tJF55GnEj3BVn4A5gKfq9NWWXXrxkHBwVPUfH0opw==", + "peer": true, + "dependencies": { + "@types/estree": "^1.0.0", + "estree-walker": "^3.0.0", + "is-reference": "^3.0.0" + } + }, + "node_modules/picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", + "peer": true + }, + "node_modules/postcss": { + "version": "8.4.27", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.27.tgz", + "integrity": "sha512-gY/ACJtJPSmUFPDCHtX78+01fHa64FaU4zaaWfuh1MhGJISufJAH4cun6k/8fwsHYeK4UQmENQK+tRLCFJE8JQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "peer": true, + "dependencies": { + "nanoid": "^3.3.6", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rollup": { + "version": "3.27.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-3.27.0.tgz", + "integrity": "sha512-aOltLCrYZ0FhJDm7fCqwTjIUEVjWjcydKBV/Zeid6Mn8BWgDCUBBWT5beM5ieForYNo/1ZHuGJdka26kvQ3Gzg==", + "peer": true, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=14.18.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/sade": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", + "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==", + "peer": true, + "dependencies": { + "mri": "^1.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/set-cookie-parser": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.6.0.tgz", + "integrity": "sha512-RVnVQxTXuerk653XfuliOxBP81Sf0+qfQE73LIYKcyMYHG94AuH0kgrQpRDuTZnSmjpysHmzxJXKNfa6PjFhyQ==", + "peer": true + }, + "node_modules/sirv": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/sirv/-/sirv-2.0.3.tgz", + "integrity": "sha512-O9jm9BsID1P+0HOi81VpXPoDxYP374pkOLzACAoyUQ/3OUVndNpsz6wMnY2z+yOxzbllCKZrM+9QrWsv4THnyA==", + "peer": true, + "dependencies": { + "@polka/url": "^1.0.0-next.20", + "mrmime": "^1.0.0", + "totalist": "^3.0.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/source-map-js": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", + "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "peer": true, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/svelte": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/svelte/-/svelte-4.1.2.tgz", + "integrity": "sha512-/evA8U6CgOHe5ZD1C1W3va9iJG7mWflcCdghBORJaAhD2JzrVERJty/2gl0pIPrJYBGZwZycH6onYf+64XXF9g==", + "peer": true, + "dependencies": { + "@ampproject/remapping": "^2.2.1", + "@jridgewell/sourcemap-codec": "^1.4.15", + "@jridgewell/trace-mapping": "^0.3.18", + "acorn": "^8.9.0", + "aria-query": "^5.3.0", + "axobject-query": "^3.2.1", + "code-red": "^1.0.3", + "css-tree": "^2.3.1", + "estree-walker": "^3.0.3", + "is-reference": "^3.0.1", + "locate-character": "^3.0.0", + "magic-string": "^0.30.0", + "periscopic": "^3.1.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/svelte-hmr": { + "version": "0.15.2", + "resolved": "https://registry.npmjs.org/svelte-hmr/-/svelte-hmr-0.15.2.tgz", + "integrity": "sha512-q/bAruCvFLwvNbeE1x3n37TYFb3mTBJ6TrCq6p2CoFbSTNhDE9oAtEfpy+wmc9So8AG0Tja+X0/mJzX9tSfvIg==", + "peer": true, + "engines": { + "node": "^12.20 || ^14.13.1 || >= 16" + }, + "peerDependencies": { + "svelte": "^3.19.0 || ^4.0.0-next.0" + } + }, + "node_modules/totalist": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/totalist/-/totalist-3.0.1.tgz", + "integrity": "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==", + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "node_modules/type": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/type/-/type-1.2.0.tgz", + "integrity": "sha512-+5nt5AAniqsCnu2cEQQdpzCAh33kVx8n0VoFidKpB1dVVLAN/F+bgVOqOJqOnEnrhp222clB5p3vUlD+1QAnfg==" + }, + "node_modules/typedarray-to-buffer": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", + "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "dependencies": { + "is-typedarray": "^1.0.0" + } + }, + "node_modules/undici": { + "version": "5.22.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.22.1.tgz", + "integrity": "sha512-Ji2IJhFXZY0x/0tVBXeQwgPlLWw13GVzpsWPQ3rV50IFMMof2I55PZZxtm4P6iNq+L5znYN9nSTAq0ZyE6lSJw==", + "peer": true, + "dependencies": { + "busboy": "^1.6.0" + }, + "engines": { + "node": ">=14.0" + } + }, + "node_modules/utf-8-validate": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", + "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", + "hasInstallScript": true, + "dependencies": { + "node-gyp-build": "^4.3.0" + }, + "engines": { + "node": ">=6.14.2" + } + }, + "node_modules/vite": { + "version": "4.4.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-4.4.8.tgz", + "integrity": "sha512-LONawOUUjxQridNWGQlNizfKH89qPigK36XhMI7COMGztz8KNY0JHim7/xDd71CZwGT4HtSRgI7Hy+RlhG0Gvg==", + "peer": true, + "dependencies": { + "esbuild": "^0.18.10", + "postcss": "^8.4.26", + "rollup": "^3.25.2" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + }, + "peerDependencies": { + "@types/node": ">= 14", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/vitefu": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/vitefu/-/vitefu-0.2.4.tgz", + "integrity": "sha512-fanAXjSaf9xXtOOeno8wZXIhgia+CZury481LsDaV++lSvcU2R9Ch2bPh3PYFyoHW+w9LqAeYRISVQjUIew14g==", + "peer": true, + "peerDependencies": { + "vite": "^3.0.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "vite": { + "optional": true + } + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" + }, + "node_modules/websocket": { + "version": "1.0.34", + "resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.34.tgz", + "integrity": "sha512-PRDso2sGwF6kM75QykIesBijKSVceR6jL2G8NGYyq2XrItNC2P5/qL5XeR056GhA+Ly7JMFvJb9I312mJfmqnQ==", + "dependencies": { + "bufferutil": "^4.0.1", + "debug": "^2.2.0", + "es5-ext": "^0.10.50", + "typedarray-to-buffer": "^3.1.5", + "utf-8-validate": "^5.0.2", + "yaeti": "^0.0.6" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/websocket/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/websocket/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/yaeti": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/yaeti/-/yaeti-0.0.6.tgz", + "integrity": "sha512-MvQa//+KcZCUkBTIC9blM+CU9J2GzuTytsOUwf2lidtvkx/6gnEp1QvJv34t9vdjhFmha/mUiNDbN0D0mJWdug==", + "engines": { + "node": ">=0.10.32" + } + } + } +} diff --git a/node_modules/@ampproject/remapping/LICENSE b/node_modules/@ampproject/remapping/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/@ampproject/remapping/LICENSE @@ -0,0 +1,202 @@ + + 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@ampproject/remapping/README.md b/node_modules/@ampproject/remapping/README.md new file mode 100644 index 0000000..1463c9f --- /dev/null +++ b/node_modules/@ampproject/remapping/README.md @@ -0,0 +1,218 @@ +# @ampproject/remapping + +> Remap sequential sourcemaps through transformations to point at the original source code + +Remapping allows you to take the sourcemaps generated through transforming your code and "remap" +them to the original source locations. Think "my minified code, transformed with babel and bundled +with webpack", all pointing to the correct location in your original source code. + +With remapping, none of your source code transformations need to be aware of the input's sourcemap, +they only need to generate an output sourcemap. This greatly simplifies building custom +transformations (think a find-and-replace). + +## Installation + +```sh +npm install @ampproject/remapping +``` + +## Usage + +```typescript +function remapping( + map: SourceMap | SourceMap[], + loader: (file: string, ctx: LoaderContext) => (SourceMap | null | undefined), + options?: { excludeContent: boolean, decodedMappings: boolean } +): SourceMap; + +// LoaderContext gives the loader the importing sourcemap, tree depth, the ability to override the +// "source" location (where child sources are resolved relative to, or the location of original +// source), and the ability to override the "content" of an original source for inclusion in the +// output sourcemap. +type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; +} +``` + +`remapping` takes the final output sourcemap, and a `loader` function. For every source file pointer +in the sourcemap, the `loader` will be called with the resolved path. If the path itself represents +a transformed file (it has a sourcmap associated with it), then the `loader` should return that +sourcemap. If not, the path will be treated as an original, untransformed source code. + +```js +// Babel transformed "helloworld.js" into "transformed.js" +const transformedMap = JSON.stringify({ + file: 'transformed.js', + // 1st column of 2nd line of output file translates into the 1st source + // file, line 3, column 2 + mappings: ';CAEE', + sources: ['helloworld.js'], + version: 3, +}); + +// Uglify minified "transformed.js" into "transformed.min.js" +const minifiedTransformedMap = JSON.stringify({ + file: 'transformed.min.js', + // 0th column of 1st line of output file translates into the 1st source + // file, line 2, column 1. + mappings: 'AACC', + names: [], + sources: ['transformed.js'], + version: 3, +}); + +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + // The "transformed.js" file is an transformed file. + if (file === 'transformed.js') { + // The root importer is empty. + console.assert(ctx.importer === ''); + // The depth in the sourcemap tree we're currently loading. + // The root `minifiedTransformedMap` is depth 0, and its source children are depth 1, etc. + console.assert(ctx.depth === 1); + + return transformedMap; + } + + // Loader will be called to load transformedMap's source file pointers as well. + console.assert(file === 'helloworld.js'); + // `transformed.js`'s sourcemap points into `helloworld.js`. + console.assert(ctx.importer === 'transformed.js'); + // This is a source child of `transformed`, which is a source child of `minifiedTransformedMap`. + console.assert(ctx.depth === 2); + return null; + } +); + +console.log(remapped); +// { +// file: 'transpiled.min.js', +// mappings: 'AAEE', +// sources: ['helloworld.js'], +// version: 3, +// }; +``` + +In this example, `loader` will be called twice: + +1. `"transformed.js"`, the first source file pointer in the `minifiedTransformedMap`. We return the + associated sourcemap for it (its a transformed file, after all) so that sourcemap locations can + be traced through it into the source files it represents. +2. `"helloworld.js"`, our original, unmodified source code. This file does not have a sourcemap, so + we return `null`. + +The `remapped` sourcemap now points from `transformed.min.js` into locations in `helloworld.js`. If +you were to read the `mappings`, it says "0th column of the first line output line points to the 1st +column of the 2nd line of the file `helloworld.js`". + +### Multiple transformations of a file + +As a convenience, if you have multiple single-source transformations of a file, you may pass an +array of sourcemap files in the order of most-recent transformation sourcemap first. Note that this +changes the `importer` and `depth` of each call to our loader. So our above example could have been +written as: + +```js +const remapped = remapping( + [minifiedTransformedMap, transformedMap], + () => null +); + +console.log(remapped); +// { +// file: 'transpiled.min.js', +// mappings: 'AAEE', +// sources: ['helloworld.js'], +// version: 3, +// }; +``` + +### Advanced control of the loading graph + +#### `source` + +The `source` property can overridden to any value to change the location of the current load. Eg, +for an original source file, it allows us to change the location to the original source regardless +of what the sourcemap source entry says. And for transformed files, it allows us to change the +relative resolving location for child sources of the loaded sourcemap. + +```js +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + if (file === 'transformed.js') { + // We pretend the transformed.js file actually exists in the 'src/' directory. When the nested + // source files are loaded, they will now be relative to `src/`. + ctx.source = 'src/transformed.js'; + return transformedMap; + } + + console.assert(file === 'src/helloworld.js'); + // We could futher change the source of this original file, eg, to be inside a nested directory + // itself. This will be reflected in the remapped sourcemap. + ctx.source = 'src/nested/transformed.js'; + return null; + } +); + +console.log(remapped); +// { +// …, +// sources: ['src/nested/helloworld.js'], +// }; +``` + + +#### `content` + +The `content` property can be overridden when we encounter an original source file. Eg, this allows +you to manually provide the source content of the original file regardless of whether the +`sourcesContent` field is present in the parent sourcemap. It can also be set to `null` to remove +the source content. + +```js +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + if (file === 'transformed.js') { + // transformedMap does not include a `sourcesContent` field, so usually the remapped sourcemap + // would not include any `sourcesContent` values. + return transformedMap; + } + + console.assert(file === 'helloworld.js'); + // We can read the file to provide the source content. + ctx.content = fs.readFileSync(file, 'utf8'); + return null; + } +); + +console.log(remapped); +// { +// …, +// sourcesContent: [ +// 'console.log("Hello world!")', +// ], +// }; +``` + +### Options + +#### excludeContent + +By default, `excludeContent` is `false`. Passing `{ excludeContent: true }` will exclude the +`sourcesContent` field from the returned sourcemap. This is mainly useful when you want to reduce +the size out the sourcemap. + +#### decodedMappings + +By default, `decodedMappings` is `false`. Passing `{ decodedMappings: true }` will leave the +`mappings` field in a [decoded state](https://github.com/rich-harris/sourcemap-codec) instead of +encoding into a VLQ string. diff --git a/node_modules/@ampproject/remapping/dist/remapping.mjs b/node_modules/@ampproject/remapping/dist/remapping.mjs new file mode 100644 index 0000000..b5edded --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.mjs @@ -0,0 +1,191 @@ +import { decodedMappings, traceSegment, TraceMap } from '@jridgewell/trace-mapping'; +import { GenMapping, maybeAddSegment, setSourceContent, toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping'; + +const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null); +const EMPTY_SOURCES = []; +function SegmentObject(source, line, column, name, content) { + return { source, line, column, name, content }; +} +function Source(map, sources, source, content) { + return { + map, + sources, + source, + content, + }; +} +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +function MapSource(map, sources) { + return Source(map, sources, '', null); +} +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +function OriginalSource(source, content) { + return Source(null, EMPTY_SOURCES, source, content); +} +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +function traceMappings(tree) { + // TODO: Eventually support sourceRoot, which has to be removed because the sources are already + // fully resolved. We'll need to make sources relative to the sourceRoot before adding them. + const gen = new GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) + continue; + } + const { column, line, name, content, source } = traced; + maybeAddSegment(gen, i, genCol, source, line, column, name); + if (source && content != null) + setSourceContent(gen, source, content); + } + } + return gen; +} +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +function originalPositionFor(source, line, column, name) { + if (!source.map) { + return SegmentObject(source.source, line, column, name, source.content); + } + const segment = traceSegment(source.map, line, column); + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) + return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) + return SOURCELESS_MAPPING; + return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); +} + +function asArray(value) { + if (Array.isArray(value)) + return value; + return [value]; +} +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +function buildSourceMapTree(input, loader) { + const maps = asArray(input).map((m) => new TraceMap(m, '')); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error(`Transformation map ${i} must have exactly one source file.\n` + + 'Did you specify these with the most recent transformation maps first?'); + } + } + let tree = build(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; +} +function build(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx = { + importer, + depth, + source: sourceFile || '', + content: undefined, + }; + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + const { source, content } = ctx; + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) + return build(new TraceMap(sourceMap, source), loader, source, depth); + // Else, it's an an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + return OriginalSource(source, sourceContent); + }); + return MapSource(map, children); +} + +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +class SourceMap { + constructor(map, options) { + const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } +} + +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +function remapping(input, loader, options) { + const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); +} + +export { remapping as default }; +//# sourceMappingURL=remapping.mjs.map diff --git a/node_modules/@ampproject/remapping/dist/remapping.mjs.map b/node_modules/@ampproject/remapping/dist/remapping.mjs.map new file mode 100644 index 0000000..078a2b7 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"remapping.mjs","sources":["../src/source-map-tree.ts","../src/build-source-map-tree.ts","../src/source-map.ts","../src/remapping.ts"],"sourcesContent":["import { GenMapping, maybeAddSegment, setSourceContent } from '@jridgewell/gen-mapping';\nimport { traceSegment, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport type { TraceMap } from '@jridgewell/trace-mapping';\n\nexport type SourceMapSegmentObject = {\n column: number;\n line: number;\n name: string;\n source: string;\n content: string | null;\n};\n\nexport type OriginalSource = {\n map: null;\n sources: Sources[];\n source: string;\n content: string | null;\n};\n\nexport type MapSource = {\n map: TraceMap;\n sources: Sources[];\n source: string;\n content: null;\n};\n\nexport type Sources = OriginalSource | MapSource;\n\nconst SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null);\nconst EMPTY_SOURCES: Sources[] = [];\n\nfunction SegmentObject(\n source: string,\n line: number,\n column: number,\n name: string,\n content: string | null\n): SourceMapSegmentObject {\n return { source, line, column, name, content };\n}\n\nfunction Source(map: TraceMap, sources: Sources[], source: '', content: null): MapSource;\nfunction Source(\n map: null,\n sources: Sources[],\n source: string,\n content: string | null\n): OriginalSource;\nfunction Source(\n map: TraceMap | null,\n sources: Sources[],\n source: string | '',\n content: string | null\n): Sources {\n return {\n map,\n sources,\n source,\n content,\n } as any;\n}\n\n/**\n * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes\n * (which may themselves be SourceMapTrees).\n */\nexport function MapSource(map: TraceMap, sources: Sources[]): MapSource {\n return Source(map, sources, '', null);\n}\n\n/**\n * A \"leaf\" node in the sourcemap tree, representing an original, unmodified source file. Recursive\n * segment tracing ends at the `OriginalSource`.\n */\nexport function OriginalSource(source: string, content: string | null): OriginalSource {\n return Source(null, EMPTY_SOURCES, source, content);\n}\n\n/**\n * traceMappings is only called on the root level SourceMapTree, and begins the process of\n * resolving each mapping in terms of the original source files.\n */\nexport function traceMappings(tree: MapSource): GenMapping {\n // TODO: Eventually support sourceRoot, which has to be removed because the sources are already\n // fully resolved. We'll need to make sources relative to the sourceRoot before adding them.\n const gen = new GenMapping({ file: tree.map.file });\n const { sources: rootSources, map } = tree;\n const rootNames = map.names;\n const rootMappings = decodedMappings(map);\n\n for (let i = 0; i < rootMappings.length; i++) {\n const segments = rootMappings[i];\n\n for (let j = 0; j < segments.length; j++) {\n const segment = segments[j];\n const genCol = segment[0];\n let traced: SourceMapSegmentObject | null = SOURCELESS_MAPPING;\n\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length !== 1) {\n const source = rootSources[segment[1]];\n traced = originalPositionFor(\n source,\n segment[2],\n segment[3],\n segment.length === 5 ? rootNames[segment[4]] : ''\n );\n\n // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a\n // respective segment into an original source.\n if (traced == null) continue;\n }\n\n const { column, line, name, content, source } = traced;\n\n maybeAddSegment(gen, i, genCol, source, line, column, name);\n if (source && content != null) setSourceContent(gen, source, content);\n }\n }\n\n return gen;\n}\n\n/**\n * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own\n * child SourceMapTrees, until we find the original source map.\n */\nexport function originalPositionFor(\n source: Sources,\n line: number,\n column: number,\n name: string\n): SourceMapSegmentObject | null {\n if (!source.map) {\n return SegmentObject(source.source, line, column, name, source.content);\n }\n\n const segment = traceSegment(source.map, line, column);\n\n // If we couldn't find a segment, then this doesn't exist in the sourcemap.\n if (segment == null) return null;\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length === 1) return SOURCELESS_MAPPING;\n\n return originalPositionFor(\n source.sources[segment[1]],\n segment[2],\n segment[3],\n segment.length === 5 ? source.map.names[segment[4]] : name\n );\n}\n","import { TraceMap } from '@jridgewell/trace-mapping';\n\nimport { OriginalSource, MapSource } from './source-map-tree';\n\nimport type { Sources, MapSource as MapSourceType } from './source-map-tree';\nimport type { SourceMapInput, SourceMapLoader, LoaderContext } from './types';\n\nfunction asArray(value: T | T[]): T[] {\n if (Array.isArray(value)) return value;\n return [value];\n}\n\n/**\n * Recursively builds a tree structure out of sourcemap files, with each node\n * being either an `OriginalSource` \"leaf\" or a `SourceMapTree` composed of\n * `OriginalSource`s and `SourceMapTree`s.\n *\n * Every sourcemap is composed of a collection of source files and mappings\n * into locations of those source files. When we generate a `SourceMapTree` for\n * the sourcemap, we attempt to load each source file's own sourcemap. If it\n * does not have an associated sourcemap, it is considered an original,\n * unmodified source file.\n */\nexport default function buildSourceMapTree(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader\n): MapSourceType {\n const maps = asArray(input).map((m) => new TraceMap(m, ''));\n const map = maps.pop()!;\n\n for (let i = 0; i < maps.length; i++) {\n if (maps[i].sources.length > 1) {\n throw new Error(\n `Transformation map ${i} must have exactly one source file.\\n` +\n 'Did you specify these with the most recent transformation maps first?'\n );\n }\n }\n\n let tree = build(map, loader, '', 0);\n for (let i = maps.length - 1; i >= 0; i--) {\n tree = MapSource(maps[i], [tree]);\n }\n return tree;\n}\n\nfunction build(\n map: TraceMap,\n loader: SourceMapLoader,\n importer: string,\n importerDepth: number\n): MapSourceType {\n const { resolvedSources, sourcesContent } = map;\n\n const depth = importerDepth + 1;\n const children = resolvedSources.map((sourceFile: string | null, i: number): Sources => {\n // The loading context gives the loader more information about why this file is being loaded\n // (eg, from which importer). It also allows the loader to override the location of the loaded\n // sourcemap/original source, or to override the content in the sourcesContent field if it's\n // an unmodified source file.\n const ctx: LoaderContext = {\n importer,\n depth,\n source: sourceFile || '',\n content: undefined,\n };\n\n // Use the provided loader callback to retrieve the file's sourcemap.\n // TODO: We should eventually support async loading of sourcemap files.\n const sourceMap = loader(ctx.source, ctx);\n\n const { source, content } = ctx;\n\n // If there is a sourcemap, then we need to recurse into it to load its source files.\n if (sourceMap) return build(new TraceMap(sourceMap, source), loader, source, depth);\n\n // Else, it's an an unmodified source file.\n // The contents of this unmodified source file can be overridden via the loader context,\n // allowing it to be explicitly null or a string. If it remains undefined, we fall back to\n // the importing sourcemap's `sourcesContent` field.\n const sourceContent =\n content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;\n return OriginalSource(source, sourceContent);\n });\n\n return MapSource(map, children);\n}\n","import { toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping';\n\nimport type { GenMapping } from '@jridgewell/gen-mapping';\nimport type { DecodedSourceMap, EncodedSourceMap, Options } from './types';\n\n/**\n * A SourceMap v3 compatible sourcemap, which only includes fields that were\n * provided to it.\n */\nexport default class SourceMap {\n declare file?: string | null;\n declare mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings'];\n declare sourceRoot?: string;\n declare names: string[];\n declare sources: (string | null)[];\n declare sourcesContent?: (string | null)[];\n declare version: 3;\n\n constructor(map: GenMapping, options: Options) {\n const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);\n this.version = out.version; // SourceMap spec says this should be first.\n this.file = out.file;\n this.mappings = out.mappings as SourceMap['mappings'];\n this.names = out.names as SourceMap['names'];\n\n this.sourceRoot = out.sourceRoot;\n\n this.sources = out.sources as SourceMap['sources'];\n if (!options.excludeContent) {\n this.sourcesContent = out.sourcesContent as SourceMap['sourcesContent'];\n }\n }\n\n toString(): string {\n return JSON.stringify(this);\n }\n}\n","import buildSourceMapTree from './build-source-map-tree';\nimport { traceMappings } from './source-map-tree';\nimport SourceMap from './source-map';\n\nimport type { SourceMapInput, SourceMapLoader, Options } from './types';\nexport type {\n SourceMapSegment,\n EncodedSourceMap,\n EncodedSourceMap as RawSourceMap,\n DecodedSourceMap,\n SourceMapInput,\n SourceMapLoader,\n LoaderContext,\n Options,\n} from './types';\n\n/**\n * Traces through all the mappings in the root sourcemap, through the sources\n * (and their sourcemaps), all the way back to the original source location.\n *\n * `loader` will be called every time we encounter a source file. If it returns\n * a sourcemap, we will recurse into that sourcemap to continue the trace. If\n * it returns a falsey value, that source file is treated as an original,\n * unmodified source file.\n *\n * Pass `excludeContent` to exclude any self-containing source file content\n * from the output sourcemap.\n *\n * Pass `decodedMappings` to receive a SourceMap with decoded (instead of\n * VLQ encoded) mappings.\n */\nexport default function remapping(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader,\n options?: boolean | Options\n): SourceMap {\n const opts =\n typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };\n const tree = buildSourceMapTree(input, loader);\n return new SourceMap(traceMappings(tree), opts);\n}\n"],"names":[],"mappings":";;;AA6BA,MAAM,kBAAkB,mBAAmB,aAAa,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;AAC/E,MAAM,aAAa,GAAc,EAAE,CAA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AAG,kBAAkB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC/C,OAAO,IAAI,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;AAClD;;;;"} \ No newline at end of file diff --git a/node_modules/@ampproject/remapping/dist/remapping.umd.js b/node_modules/@ampproject/remapping/dist/remapping.umd.js new file mode 100644 index 0000000..e292d4c --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.umd.js @@ -0,0 +1,196 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@jridgewell/trace-mapping'), require('@jridgewell/gen-mapping')) : + typeof define === 'function' && define.amd ? define(['@jridgewell/trace-mapping', '@jridgewell/gen-mapping'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.remapping = factory(global.traceMapping, global.genMapping)); +})(this, (function (traceMapping, genMapping) { 'use strict'; + + const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null); + const EMPTY_SOURCES = []; + function SegmentObject(source, line, column, name, content) { + return { source, line, column, name, content }; + } + function Source(map, sources, source, content) { + return { + map, + sources, + source, + content, + }; + } + /** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ + function MapSource(map, sources) { + return Source(map, sources, '', null); + } + /** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ + function OriginalSource(source, content) { + return Source(null, EMPTY_SOURCES, source, content); + } + /** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ + function traceMappings(tree) { + // TODO: Eventually support sourceRoot, which has to be removed because the sources are already + // fully resolved. We'll need to make sources relative to the sourceRoot before adding them. + const gen = new genMapping.GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = traceMapping.decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) + continue; + } + const { column, line, name, content, source } = traced; + genMapping.maybeAddSegment(gen, i, genCol, source, line, column, name); + if (source && content != null) + genMapping.setSourceContent(gen, source, content); + } + } + return gen; + } + /** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ + function originalPositionFor(source, line, column, name) { + if (!source.map) { + return SegmentObject(source.source, line, column, name, source.content); + } + const segment = traceMapping.traceSegment(source.map, line, column); + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) + return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) + return SOURCELESS_MAPPING; + return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); + } + + function asArray(value) { + if (Array.isArray(value)) + return value; + return [value]; + } + /** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ + function buildSourceMapTree(input, loader) { + const maps = asArray(input).map((m) => new traceMapping.TraceMap(m, '')); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error(`Transformation map ${i} must have exactly one source file.\n` + + 'Did you specify these with the most recent transformation maps first?'); + } + } + let tree = build(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; + } + function build(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx = { + importer, + depth, + source: sourceFile || '', + content: undefined, + }; + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + const { source, content } = ctx; + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) + return build(new traceMapping.TraceMap(sourceMap, source), loader, source, depth); + // Else, it's an an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + return OriginalSource(source, sourceContent); + }); + return MapSource(map, children); + } + + /** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ + class SourceMap { + constructor(map, options) { + const out = options.decodedMappings ? genMapping.toDecodedMap(map) : genMapping.toEncodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } + } + + /** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ + function remapping(input, loader, options) { + const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); + } + + return remapping; + +})); +//# sourceMappingURL=remapping.umd.js.map diff --git a/node_modules/@ampproject/remapping/dist/remapping.umd.js.map b/node_modules/@ampproject/remapping/dist/remapping.umd.js.map new file mode 100644 index 0000000..9c89888 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"remapping.umd.js","sources":["../src/source-map-tree.ts","../src/build-source-map-tree.ts","../src/source-map.ts","../src/remapping.ts"],"sourcesContent":["import { GenMapping, maybeAddSegment, setSourceContent } from '@jridgewell/gen-mapping';\nimport { traceSegment, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport type { TraceMap } from '@jridgewell/trace-mapping';\n\nexport type SourceMapSegmentObject = {\n column: number;\n line: number;\n name: string;\n source: string;\n content: string | null;\n};\n\nexport type OriginalSource = {\n map: null;\n sources: Sources[];\n source: string;\n content: string | null;\n};\n\nexport type MapSource = {\n map: TraceMap;\n sources: Sources[];\n source: string;\n content: null;\n};\n\nexport type Sources = OriginalSource | MapSource;\n\nconst SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null);\nconst EMPTY_SOURCES: Sources[] = [];\n\nfunction SegmentObject(\n source: string,\n line: number,\n column: number,\n name: string,\n content: string | null\n): SourceMapSegmentObject {\n return { source, line, column, name, content };\n}\n\nfunction Source(map: TraceMap, sources: Sources[], source: '', content: null): MapSource;\nfunction Source(\n map: null,\n sources: Sources[],\n source: string,\n content: string | null\n): OriginalSource;\nfunction Source(\n map: TraceMap | null,\n sources: Sources[],\n source: string | '',\n content: string | null\n): Sources {\n return {\n map,\n sources,\n source,\n content,\n } as any;\n}\n\n/**\n * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes\n * (which may themselves be SourceMapTrees).\n */\nexport function MapSource(map: TraceMap, sources: Sources[]): MapSource {\n return Source(map, sources, '', null);\n}\n\n/**\n * A \"leaf\" node in the sourcemap tree, representing an original, unmodified source file. Recursive\n * segment tracing ends at the `OriginalSource`.\n */\nexport function OriginalSource(source: string, content: string | null): OriginalSource {\n return Source(null, EMPTY_SOURCES, source, content);\n}\n\n/**\n * traceMappings is only called on the root level SourceMapTree, and begins the process of\n * resolving each mapping in terms of the original source files.\n */\nexport function traceMappings(tree: MapSource): GenMapping {\n // TODO: Eventually support sourceRoot, which has to be removed because the sources are already\n // fully resolved. We'll need to make sources relative to the sourceRoot before adding them.\n const gen = new GenMapping({ file: tree.map.file });\n const { sources: rootSources, map } = tree;\n const rootNames = map.names;\n const rootMappings = decodedMappings(map);\n\n for (let i = 0; i < rootMappings.length; i++) {\n const segments = rootMappings[i];\n\n for (let j = 0; j < segments.length; j++) {\n const segment = segments[j];\n const genCol = segment[0];\n let traced: SourceMapSegmentObject | null = SOURCELESS_MAPPING;\n\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length !== 1) {\n const source = rootSources[segment[1]];\n traced = originalPositionFor(\n source,\n segment[2],\n segment[3],\n segment.length === 5 ? rootNames[segment[4]] : ''\n );\n\n // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a\n // respective segment into an original source.\n if (traced == null) continue;\n }\n\n const { column, line, name, content, source } = traced;\n\n maybeAddSegment(gen, i, genCol, source, line, column, name);\n if (source && content != null) setSourceContent(gen, source, content);\n }\n }\n\n return gen;\n}\n\n/**\n * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own\n * child SourceMapTrees, until we find the original source map.\n */\nexport function originalPositionFor(\n source: Sources,\n line: number,\n column: number,\n name: string\n): SourceMapSegmentObject | null {\n if (!source.map) {\n return SegmentObject(source.source, line, column, name, source.content);\n }\n\n const segment = traceSegment(source.map, line, column);\n\n // If we couldn't find a segment, then this doesn't exist in the sourcemap.\n if (segment == null) return null;\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length === 1) return SOURCELESS_MAPPING;\n\n return originalPositionFor(\n source.sources[segment[1]],\n segment[2],\n segment[3],\n segment.length === 5 ? source.map.names[segment[4]] : name\n );\n}\n","import { TraceMap } from '@jridgewell/trace-mapping';\n\nimport { OriginalSource, MapSource } from './source-map-tree';\n\nimport type { Sources, MapSource as MapSourceType } from './source-map-tree';\nimport type { SourceMapInput, SourceMapLoader, LoaderContext } from './types';\n\nfunction asArray(value: T | T[]): T[] {\n if (Array.isArray(value)) return value;\n return [value];\n}\n\n/**\n * Recursively builds a tree structure out of sourcemap files, with each node\n * being either an `OriginalSource` \"leaf\" or a `SourceMapTree` composed of\n * `OriginalSource`s and `SourceMapTree`s.\n *\n * Every sourcemap is composed of a collection of source files and mappings\n * into locations of those source files. When we generate a `SourceMapTree` for\n * the sourcemap, we attempt to load each source file's own sourcemap. If it\n * does not have an associated sourcemap, it is considered an original,\n * unmodified source file.\n */\nexport default function buildSourceMapTree(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader\n): MapSourceType {\n const maps = asArray(input).map((m) => new TraceMap(m, ''));\n const map = maps.pop()!;\n\n for (let i = 0; i < maps.length; i++) {\n if (maps[i].sources.length > 1) {\n throw new Error(\n `Transformation map ${i} must have exactly one source file.\\n` +\n 'Did you specify these with the most recent transformation maps first?'\n );\n }\n }\n\n let tree = build(map, loader, '', 0);\n for (let i = maps.length - 1; i >= 0; i--) {\n tree = MapSource(maps[i], [tree]);\n }\n return tree;\n}\n\nfunction build(\n map: TraceMap,\n loader: SourceMapLoader,\n importer: string,\n importerDepth: number\n): MapSourceType {\n const { resolvedSources, sourcesContent } = map;\n\n const depth = importerDepth + 1;\n const children = resolvedSources.map((sourceFile: string | null, i: number): Sources => {\n // The loading context gives the loader more information about why this file is being loaded\n // (eg, from which importer). It also allows the loader to override the location of the loaded\n // sourcemap/original source, or to override the content in the sourcesContent field if it's\n // an unmodified source file.\n const ctx: LoaderContext = {\n importer,\n depth,\n source: sourceFile || '',\n content: undefined,\n };\n\n // Use the provided loader callback to retrieve the file's sourcemap.\n // TODO: We should eventually support async loading of sourcemap files.\n const sourceMap = loader(ctx.source, ctx);\n\n const { source, content } = ctx;\n\n // If there is a sourcemap, then we need to recurse into it to load its source files.\n if (sourceMap) return build(new TraceMap(sourceMap, source), loader, source, depth);\n\n // Else, it's an an unmodified source file.\n // The contents of this unmodified source file can be overridden via the loader context,\n // allowing it to be explicitly null or a string. If it remains undefined, we fall back to\n // the importing sourcemap's `sourcesContent` field.\n const sourceContent =\n content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;\n return OriginalSource(source, sourceContent);\n });\n\n return MapSource(map, children);\n}\n","import { toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping';\n\nimport type { GenMapping } from '@jridgewell/gen-mapping';\nimport type { DecodedSourceMap, EncodedSourceMap, Options } from './types';\n\n/**\n * A SourceMap v3 compatible sourcemap, which only includes fields that were\n * provided to it.\n */\nexport default class SourceMap {\n declare file?: string | null;\n declare mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings'];\n declare sourceRoot?: string;\n declare names: string[];\n declare sources: (string | null)[];\n declare sourcesContent?: (string | null)[];\n declare version: 3;\n\n constructor(map: GenMapping, options: Options) {\n const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);\n this.version = out.version; // SourceMap spec says this should be first.\n this.file = out.file;\n this.mappings = out.mappings as SourceMap['mappings'];\n this.names = out.names as SourceMap['names'];\n\n this.sourceRoot = out.sourceRoot;\n\n this.sources = out.sources as SourceMap['sources'];\n if (!options.excludeContent) {\n this.sourcesContent = out.sourcesContent as SourceMap['sourcesContent'];\n }\n }\n\n toString(): string {\n return JSON.stringify(this);\n }\n}\n","import buildSourceMapTree from './build-source-map-tree';\nimport { traceMappings } from './source-map-tree';\nimport SourceMap from './source-map';\n\nimport type { SourceMapInput, SourceMapLoader, Options } from './types';\nexport type {\n SourceMapSegment,\n EncodedSourceMap,\n EncodedSourceMap as RawSourceMap,\n DecodedSourceMap,\n SourceMapInput,\n SourceMapLoader,\n LoaderContext,\n Options,\n} from './types';\n\n/**\n * Traces through all the mappings in the root sourcemap, through the sources\n * (and their sourcemaps), all the way back to the original source location.\n *\n * `loader` will be called every time we encounter a source file. If it returns\n * a sourcemap, we will recurse into that sourcemap to continue the trace. If\n * it returns a falsey value, that source file is treated as an original,\n * unmodified source file.\n *\n * Pass `excludeContent` to exclude any self-containing source file content\n * from the output sourcemap.\n *\n * Pass `decodedMappings` to receive a SourceMap with decoded (instead of\n * VLQ encoded) mappings.\n */\nexport default function remapping(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader,\n options?: boolean | Options\n): SourceMap {\n const opts =\n typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };\n const tree = buildSourceMapTree(input, loader);\n return new SourceMap(traceMappings(tree), opts);\n}\n"],"names":["GenMapping","decodedMappings","maybeAddSegment","setSourceContent","traceSegment","TraceMap","toDecodedMap","toEncodedMap"],"mappings":";;;;;;IA6BA,MAAM,kBAAkB,mBAAmB,aAAa,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;IAC/E,MAAM,aAAa,GAAc,EAAE,CAAC;IAEpC,SAAS,aAAa,CACpB,MAAc,EACd,IAAY,EACZ,MAAc,EACd,IAAY,EACZ,OAAsB,EAAA;QAEtB,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IACjD,CAAC;IASD,SAAS,MAAM,CACb,GAAoB,EACpB,OAAkB,EAClB,MAAmB,EACnB,OAAsB,EAAA;QAEtB,OAAO;YACL,GAAG;YACH,OAAO;YACP,MAAM;YACN,OAAO;SACD,CAAC;IACX,CAAC;IAED;;;IAGG;IACa,SAAA,SAAS,CAAC,GAAa,EAAE,OAAkB,EAAA;QACzD,OAAO,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC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O,CAAC;IAC3B,QAAA,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC;IACrB,QAAA,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAiC,CAAC;IACtD,QAAA,IAAI,CAAC,KAAK,GAAG,GAAG,CAAC,KAA2B,CAAC;IAE7C,QAAA,IAAI,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAEjC,QAAA,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,OAA+B,CAAC;IACnD,QAAA,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE;IAC3B,YAAA,IAAI,CAAC,cAAc,GAAG,GAAG,CAAC,cAA6C,CAAC;IACzE,SAAA;SACF;QAED,QAAQ,GAAA;IACN,QAAA,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;SAC7B;IACF;;ICpBD;;;;;;;;;;;;;;IAcG;IACqB,SAAA,SAAS,CAC/B,KAAwC,EACxC,MAAuB,EACvB,OAA2B,EAAA;QAE3B,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAO,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC;QAChG,MAAM,IAAI,GAAG,kBAAkB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/C,OAAO,IAAI,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;IAClD;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts b/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts new file mode 100644 index 0000000..f87fcea --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts @@ -0,0 +1,14 @@ +import type { MapSource as MapSourceType } from './source-map-tree'; +import type { SourceMapInput, SourceMapLoader } from './types'; +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +export default function buildSourceMapTree(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader): MapSourceType; diff --git a/node_modules/@ampproject/remapping/dist/types/remapping.d.ts b/node_modules/@ampproject/remapping/dist/types/remapping.d.ts new file mode 100644 index 0000000..0b58ea9 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/remapping.d.ts @@ -0,0 +1,19 @@ +import SourceMap from './source-map'; +import type { SourceMapInput, SourceMapLoader, Options } from './types'; +export type { SourceMapSegment, EncodedSourceMap, EncodedSourceMap as RawSourceMap, DecodedSourceMap, SourceMapInput, SourceMapLoader, LoaderContext, Options, } from './types'; +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +export default function remapping(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader, options?: boolean | Options): SourceMap; diff --git a/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts b/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts new file mode 100644 index 0000000..3a9f7af --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts @@ -0,0 +1,42 @@ +import { GenMapping } from '@jridgewell/gen-mapping'; +import type { TraceMap } from '@jridgewell/trace-mapping'; +export declare type SourceMapSegmentObject = { + column: number; + line: number; + name: string; + source: string; + content: string | null; +}; +export declare type OriginalSource = { + map: null; + sources: Sources[]; + source: string; + content: string | null; +}; +export declare type MapSource = { + map: TraceMap; + sources: Sources[]; + source: string; + content: null; +}; +export declare type Sources = OriginalSource | MapSource; +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +export declare function MapSource(map: TraceMap, sources: Sources[]): MapSource; +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +export declare function OriginalSource(source: string, content: string | null): OriginalSource; +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +export declare function traceMappings(tree: MapSource): GenMapping; +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +export declare function originalPositionFor(source: Sources, line: number, column: number, name: string): SourceMapSegmentObject | null; diff --git a/node_modules/@ampproject/remapping/dist/types/source-map.d.ts b/node_modules/@ampproject/remapping/dist/types/source-map.d.ts new file mode 100644 index 0000000..ef999b7 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/source-map.d.ts @@ -0,0 +1,17 @@ +import type { GenMapping } from '@jridgewell/gen-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Options } from './types'; +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +export default class SourceMap { + file?: string | null; + mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings']; + sourceRoot?: string; + names: string[]; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + constructor(map: GenMapping, options: Options); + toString(): string; +} diff --git a/node_modules/@ampproject/remapping/dist/types/types.d.ts b/node_modules/@ampproject/remapping/dist/types/types.d.ts new file mode 100644 index 0000000..730a963 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/types.d.ts @@ -0,0 +1,14 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +export type { SourceMapSegment, DecodedSourceMap, EncodedSourceMap, } from '@jridgewell/trace-mapping'; +export type { SourceMapInput }; +export declare type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; +}; +export declare type SourceMapLoader = (file: string, ctx: LoaderContext) => SourceMapInput | null | undefined | void; +export declare type Options = { + excludeContent?: boolean; + decodedMappings?: boolean; +}; diff --git a/node_modules/@ampproject/remapping/package.json b/node_modules/@ampproject/remapping/package.json new file mode 100644 index 0000000..bf3dad2 --- /dev/null +++ b/node_modules/@ampproject/remapping/package.json @@ -0,0 +1,75 @@ +{ + "name": "@ampproject/remapping", + "version": "2.2.1", + "description": "Remap sequential sourcemaps through transformations to point at the original source code", + "keywords": [ + "source", + "map", + "remap" + ], + "main": "dist/remapping.umd.js", + "module": "dist/remapping.mjs", + "types": "dist/types/remapping.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/remapping.d.ts", + "browser": "./dist/remapping.umd.js", + "require": "./dist/remapping.umd.js", + "import": "./dist/remapping.mjs" + }, + "./dist/remapping.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "author": "Justin Ridgewell ", + "repository": { + "type": "git", + "url": "git+https://github.com/ampproject/remapping.git" + }, + "license": "Apache-2.0", + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "test": "run-s -n test:lint test:only", + "test:debug": "node --inspect-brk node_modules/.bin/jest --runInBand", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "jest --coverage", + "test:watch": "jest --coverage --watch" + }, + "devDependencies": { + "@rollup/plugin-typescript": "8.3.2", + "@types/jest": "27.4.1", + "@typescript-eslint/eslint-plugin": "5.20.0", + "@typescript-eslint/parser": "5.20.0", + "eslint": "8.14.0", + "eslint-config-prettier": "8.5.0", + "jest": "27.5.1", + "jest-config": "27.5.1", + "npm-run-all": "4.1.5", + "prettier": "2.6.2", + "rollup": "2.70.2", + "ts-jest": "27.1.4", + "tslib": "2.4.0", + "typescript": "4.6.3" + }, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.0", + "@jridgewell/trace-mapping": "^0.3.9" + } +} 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..2116e7d 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..94f5cd1 --- /dev/null +++ b/node_modules/@esbuild/win32-x64/package.json @@ -0,0 +1,17 @@ +{ + "name": "@esbuild/win32-x64", + "version": "0.18.17", + "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/@jridgewell/gen-mapping/LICENSE b/node_modules/@jridgewell/gen-mapping/LICENSE new file mode 100644 index 0000000..352f071 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2022 Justin Ridgewell + +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/@jridgewell/gen-mapping/README.md b/node_modules/@jridgewell/gen-mapping/README.md new file mode 100644 index 0000000..4066cdb --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/README.md @@ -0,0 +1,227 @@ +# @jridgewell/gen-mapping + +> Generate source maps + +`gen-mapping` allows you to generate a source map during transpilation or minification. +With a source map, you're able to trace the original location in the source file, either in Chrome's +DevTools or using a library like [`@jridgewell/trace-mapping`][trace-mapping]. + +You may already be familiar with the [`source-map`][source-map] package's `SourceMapGenerator`. This +provides the same `addMapping` and `setSourceContent` API. + +## Installation + +```sh +npm install @jridgewell/gen-mapping +``` + +## Usage + +```typescript +import { GenMapping, addMapping, setSourceContent, toEncodedMap, toDecodedMap } from '@jridgewell/gen-mapping'; + +const map = new GenMapping({ + file: 'output.js', + sourceRoot: 'https://example.com/', +}); + +setSourceContent(map, 'input.js', `function foo() {}`); + +addMapping(map, { + // Lines start at line 1, columns at column 0. + generated: { line: 1, column: 0 }, + source: 'input.js', + original: { line: 1, column: 0 }, +}); + +addMapping(map, { + generated: { line: 1, column: 9 }, + source: 'input.js', + original: { line: 1, column: 9 }, + name: 'foo', +}); + +assert.deepEqual(toDecodedMap(map), { + version: 3, + file: 'output.js', + names: ['foo'], + sourceRoot: 'https://example.com/', + sources: ['input.js'], + sourcesContent: ['function foo() {}'], + mappings: [ + [ [0, 0, 0, 0], [9, 0, 0, 9, 0] ] + ], +}); + +assert.deepEqual(toEncodedMap(map), { + version: 3, + file: 'output.js', + names: ['foo'], + sourceRoot: 'https://example.com/', + sources: ['input.js'], + sourcesContent: ['function foo() {}'], + mappings: 'AAAA,SAASA', +}); +``` + +### Smaller Sourcemaps + +Not everything needs to be added to a sourcemap, and needless markings can cause signficantly +larger file sizes. `gen-mapping` exposes `maybeAddSegment`/`maybeAddMapping` APIs that will +intelligently determine if this marking adds useful information. If not, the marking will be +skipped. + +```typescript +import { maybeAddMapping } from '@jridgewell/gen-mapping'; + +const map = new GenMapping(); + +// Adding a sourceless marking at the beginning of a line isn't useful. +maybeAddMapping(map, { + generated: { line: 1, column: 0 }, +}); + +// Adding a new source marking is useful. +maybeAddMapping(map, { + generated: { line: 1, column: 0 }, + source: 'input.js', + original: { line: 1, column: 0 }, +}); + +// But adding another marking pointing to the exact same original location isn't, even if the +// generated column changed. +maybeAddMapping(map, { + generated: { line: 1, column: 9 }, + source: 'input.js', + original: { line: 1, column: 0 }, +}); + +assert.deepEqual(toEncodedMap(map), { + version: 3, + names: [], + sources: ['input.js'], + sourcesContent: [null], + mappings: 'AAAA', +}); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map +Memory Usage: +gen-mapping: addSegment 5852872 bytes +gen-mapping: addMapping 7716042 bytes +source-map-js 6143250 bytes +source-map-0.6.1 6124102 bytes +source-map-0.8.0 6121173 bytes +Smallest memory usage is gen-mapping: addSegment + +Adding speed: +gen-mapping: addSegment x 441 ops/sec ±2.07% (90 runs sampled) +gen-mapping: addMapping x 350 ops/sec ±2.40% (86 runs sampled) +source-map-js: addMapping x 169 ops/sec ±2.42% (80 runs sampled) +source-map-0.6.1: addMapping x 167 ops/sec ±2.56% (80 runs sampled) +source-map-0.8.0: addMapping x 168 ops/sec ±2.52% (80 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 150,824,370 ops/sec ±0.07% (102 runs sampled) +gen-mapping: encoded output x 663 ops/sec ±0.22% (98 runs sampled) +source-map-js: encoded output x 197 ops/sec ±0.45% (84 runs sampled) +source-map-0.6.1: encoded output x 198 ops/sec ±0.33% (85 runs sampled) +source-map-0.8.0: encoded output x 197 ops/sec ±0.06% (93 runs sampled) +Fastest is gen-mapping: decoded output + + +*** + + +babel.min.js.map +Memory Usage: +gen-mapping: addSegment 37578063 bytes +gen-mapping: addMapping 37212897 bytes +source-map-js 47638527 bytes +source-map-0.6.1 47690503 bytes +source-map-0.8.0 47470188 bytes +Smallest memory usage is gen-mapping: addMapping + +Adding speed: +gen-mapping: addSegment x 31.05 ops/sec ±8.31% (43 runs sampled) +gen-mapping: addMapping x 29.83 ops/sec ±7.36% (51 runs sampled) +source-map-js: addMapping x 20.73 ops/sec ±6.22% (38 runs sampled) +source-map-0.6.1: addMapping x 20.03 ops/sec ±10.51% (38 runs sampled) +source-map-0.8.0: addMapping x 19.30 ops/sec ±8.27% (37 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 381,379,234 ops/sec ±0.29% (96 runs sampled) +gen-mapping: encoded output x 95.15 ops/sec ±2.98% (72 runs sampled) +source-map-js: encoded output x 15.20 ops/sec ±7.41% (33 runs sampled) +source-map-0.6.1: encoded output x 16.36 ops/sec ±10.46% (31 runs sampled) +source-map-0.8.0: encoded output x 16.06 ops/sec ±6.45% (31 runs sampled) +Fastest is gen-mapping: decoded output + + +*** + + +preact.js.map +Memory Usage: +gen-mapping: addSegment 416247 bytes +gen-mapping: addMapping 419824 bytes +source-map-js 1024619 bytes +source-map-0.6.1 1146004 bytes +source-map-0.8.0 1113250 bytes +Smallest memory usage is gen-mapping: addSegment + +Adding speed: +gen-mapping: addSegment x 13,755 ops/sec ±0.15% (98 runs sampled) +gen-mapping: addMapping x 13,013 ops/sec ±0.11% (101 runs sampled) +source-map-js: addMapping x 4,564 ops/sec ±0.21% (98 runs sampled) +source-map-0.6.1: addMapping x 4,562 ops/sec ±0.11% (99 runs sampled) +source-map-0.8.0: addMapping x 4,593 ops/sec ±0.11% (100 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 379,864,020 ops/sec ±0.23% (93 runs sampled) +gen-mapping: encoded output x 14,368 ops/sec ±4.07% (82 runs sampled) +source-map-js: encoded output x 5,261 ops/sec ±0.21% (99 runs sampled) +source-map-0.6.1: encoded output x 5,124 ops/sec ±0.58% (99 runs sampled) +source-map-0.8.0: encoded output x 5,434 ops/sec ±0.33% (96 runs sampled) +Fastest is gen-mapping: decoded output + + +*** + + +react.js.map +Memory Usage: +gen-mapping: addSegment 975096 bytes +gen-mapping: addMapping 1102981 bytes +source-map-js 2918836 bytes +source-map-0.6.1 2885435 bytes +source-map-0.8.0 2874336 bytes +Smallest memory usage is gen-mapping: addSegment + +Adding speed: +gen-mapping: addSegment x 4,772 ops/sec ±0.15% (100 runs sampled) +gen-mapping: addMapping x 4,456 ops/sec ±0.13% (97 runs sampled) +source-map-js: addMapping x 1,618 ops/sec ±0.24% (97 runs sampled) +source-map-0.6.1: addMapping x 1,622 ops/sec ±0.12% (99 runs sampled) +source-map-0.8.0: addMapping x 1,631 ops/sec ±0.12% (100 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 379,107,695 ops/sec ±0.07% (99 runs sampled) +gen-mapping: encoded output x 5,421 ops/sec ±1.60% (89 runs sampled) +source-map-js: encoded output x 2,113 ops/sec ±1.81% (98 runs sampled) +source-map-0.6.1: encoded output x 2,126 ops/sec ±0.10% (100 runs sampled) +source-map-0.8.0: encoded output x 2,176 ops/sec ±0.39% (98 runs sampled) +Fastest is gen-mapping: decoded output +``` + +[source-map]: https://www.npmjs.com/package/source-map +[trace-mapping]: https://github.com/jridgewell/trace-mapping diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs new file mode 100644 index 0000000..5aeb5cc --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs @@ -0,0 +1,230 @@ +import { SetArray, put } from '@jridgewell/set-array'; +import { encode } from '@jridgewell/sourcemap-codec'; +import { TraceMap, decodedMappings } from '@jridgewell/trace-mapping'; + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; + +const NO_NAME = -1; +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +let addSegment; +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +let addMapping; +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +let maybeAddSegment; +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +let maybeAddMapping; +/** + * Adds/removes the content of the source file to the source map. + */ +let setSourceContent; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let toDecodedMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let toEncodedMap; +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +let fromMap; +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +let allMappings; +// This split declaration is only so that terser can elminiate the static initialization block. +let addSegmentInternal; +/** + * Provides the state to generate a sourcemap. + */ +class GenMapping { + constructor({ file, sourceRoot } = {}) { + this._names = new SetArray(); + this._sources = new SetArray(); + this._sourcesContent = []; + this._mappings = []; + this.file = file; + this.sourceRoot = sourceRoot; + } +} +(() => { + addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal(false, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); + }; + maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); + }; + addMapping = (map, mapping) => { + return addMappingInternal(false, map, mapping); + }; + maybeAddMapping = (map, mapping) => { + return addMappingInternal(true, map, mapping); + }; + setSourceContent = (map, source, content) => { + const { _sources: sources, _sourcesContent: sourcesContent } = map; + sourcesContent[put(sources, source)] = content; + }; + toDecodedMap = (map) => { + const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + removeEmptyFinalLines(mappings); + return { + version: 3, + file: file || undefined, + names: names.array, + sourceRoot: sourceRoot || undefined, + sources: sources.array, + sourcesContent, + mappings, + }; + }; + toEncodedMap = (map) => { + const decoded = toDecodedMap(map); + return Object.assign(Object.assign({}, decoded), { mappings: encode(decoded.mappings) }); + }; + allMappings = (map) => { + const out = []; + const { _mappings: mappings, _sources: sources, _names: names } = map; + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generated = { line: i + 1, column: seg[COLUMN] }; + let source = undefined; + let original = undefined; + let name = undefined; + if (seg.length !== 1) { + source = sources.array[seg[SOURCES_INDEX]]; + original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] }; + if (seg.length === 5) + name = names.array[seg[NAMES_INDEX]]; + } + out.push({ generated, source, original, name }); + } + } + return out; + }; + fromMap = (input) => { + const map = new TraceMap(input); + const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot }); + putAll(gen._names, map.names); + putAll(gen._sources, map.sources); + gen._sourcesContent = map.sourcesContent || map.sources.map(() => null); + gen._mappings = decodedMappings(map); + return gen; + }; + // Internal helpers + addSegmentInternal = (skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + const line = getLine(mappings, genLine); + const index = getColumnIndex(line, genColumn); + if (!source) { + if (skipable && skipSourceless(line, index)) + return; + return insert(line, index, [genColumn]); + } + const sourcesIndex = put(sources, source); + const namesIndex = name ? put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) + sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null; + if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { + return; + } + return insert(line, index, name + ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] + : [genColumn, sourcesIndex, sourceLine, sourceColumn]); + }; +})(); +function getLine(mappings, index) { + for (let i = mappings.length; i <= index; i++) { + mappings[i] = []; + } + return mappings[index]; +} +function getColumnIndex(line, genColumn) { + let index = line.length; + for (let i = index - 1; i >= 0; index = i--) { + const current = line[i]; + if (genColumn >= current[COLUMN]) + break; + } + return index; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +function removeEmptyFinalLines(mappings) { + const { length } = mappings; + let len = length; + for (let i = len - 1; i >= 0; len = i, i--) { + if (mappings[i].length > 0) + break; + } + if (len < length) + mappings.length = len; +} +function putAll(strarr, array) { + for (let i = 0; i < array.length; i++) + put(strarr, array[i]); +} +function skipSourceless(line, index) { + // The start of a line is already sourceless, so adding a sourceless segment to the beginning + // doesn't generate any useful information. + if (index === 0) + return true; + const prev = line[index - 1]; + // If the previous segment is also sourceless, then adding another sourceless segment doesn't + // genrate any new information. Else, this segment will end the source/named segment and point to + // a sourceless position, which is useful. + return prev.length === 1; +} +function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { + // A source/named segment at the start of a line gives position at that genColumn + if (index === 0) + return false; + const prev = line[index - 1]; + // If the previous segment is sourceless, then we're transitioning to a source. + if (prev.length === 1) + return false; + // If the previous segment maps to the exact same source position, then this segment doesn't + // provide any new position information. + return (sourcesIndex === prev[SOURCES_INDEX] && + sourceLine === prev[SOURCE_LINE] && + sourceColumn === prev[SOURCE_COLUMN] && + namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)); +} +function addMappingInternal(skipable, map, mapping) { + const { generated, source, original, name, content } = mapping; + if (!source) { + return addSegmentInternal(skipable, map, generated.line - 1, generated.column, null, null, null, null, null); + } + const s = source; + return addSegmentInternal(skipable, map, generated.line - 1, generated.column, s, original.line - 1, original.column, name, content); +} + +export { GenMapping, addMapping, addSegment, allMappings, fromMap, maybeAddMapping, maybeAddSegment, setSourceContent, toDecodedMap, toEncodedMap }; +//# sourceMappingURL=gen-mapping.mjs.map diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map new file mode 100644 index 0000000..2fee0cd --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"gen-mapping.mjs","sources":["../src/sourcemap-segment.ts","../src/gen-mapping.ts"],"sourcesContent":["type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n","import { SetArray, put } from '@jridgewell/set-array';\nimport { encode } from '@jridgewell/sourcemap-codec';\nimport { TraceMap, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type { SourceMapInput } from '@jridgewell/trace-mapping';\nimport type { SourceMapSegment } from './sourcemap-segment';\nimport type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types';\n\nexport type { DecodedSourceMap, EncodedSourceMap, Mapping };\n\nexport type Options = {\n file?: string | null;\n sourceRoot?: string | null;\n};\n\nconst NO_NAME = -1;\n\n/**\n * A low-level API to associate a generated position with an original source position. Line and\n * column here are 0-based, unlike `addMapping`.\n */\nexport let addSegment: {\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source?: null,\n sourceLine?: null,\n sourceColumn?: null,\n name?: null,\n content?: null,\n ): void;\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name?: null,\n content?: string | null,\n ): void;\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name: string,\n content?: string | null,\n ): void;\n};\n\n/**\n * A high-level API to associate a generated position with an original source position. Line is\n * 1-based, but column is 0-based, due to legacy behavior in `source-map` library.\n */\nexport let addMapping: {\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source?: null;\n original?: null;\n name?: null;\n content?: null;\n },\n ): void;\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name?: null;\n content?: string | null;\n },\n ): void;\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name: string;\n content?: string | null;\n },\n ): void;\n};\n\n/**\n * Same as `addSegment`, but will only add the segment if it generates useful information in the\n * resulting map. This only works correctly if segments are added **in order**, meaning you should\n * not add a segment with a lower generated line/column than one that came before.\n */\nexport let maybeAddSegment: typeof addSegment;\n\n/**\n * Same as `addMapping`, but will only add the mapping if it generates useful information in the\n * resulting map. This only works correctly if mappings are added **in order**, meaning you should\n * not add a mapping with a lower generated line/column than one that came before.\n */\nexport let maybeAddMapping: typeof addMapping;\n\n/**\n * Adds/removes the content of the source file to the source map.\n */\nexport let setSourceContent: (map: GenMapping, source: string, content: string | null) => void;\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let toDecodedMap: (map: GenMapping) => DecodedSourceMap;\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let toEncodedMap: (map: GenMapping) => EncodedSourceMap;\n\n/**\n * Constructs a new GenMapping, using the already present mappings of the input.\n */\nexport let fromMap: (input: SourceMapInput) => GenMapping;\n\n/**\n * Returns an array of high-level mapping objects for every recorded segment, which could then be\n * passed to the `source-map` library.\n */\nexport let allMappings: (map: GenMapping) => Mapping[];\n\n// This split declaration is only so that terser can elminiate the static initialization block.\nlet addSegmentInternal: (\n skipable: boolean,\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: S,\n sourceLine: S extends string ? number : null | undefined,\n sourceColumn: S extends string ? number : null | undefined,\n name: S extends string ? string | null | undefined : null | undefined,\n content: S extends string ? string | null | undefined : null | undefined,\n) => void;\n\n/**\n * Provides the state to generate a sourcemap.\n */\nexport class GenMapping {\n private _names = new SetArray();\n private _sources = new SetArray();\n private _sourcesContent: (string | null)[] = [];\n private _mappings: SourceMapSegment[][] = [];\n declare file: string | null | undefined;\n declare sourceRoot: string | null | undefined;\n\n constructor({ file, sourceRoot }: Options = {}) {\n this.file = file;\n this.sourceRoot = sourceRoot;\n }\n\n static {\n addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {\n return addSegmentInternal(\n false,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n );\n };\n\n maybeAddSegment = (\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n ) => {\n return addSegmentInternal(\n true,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n );\n };\n\n addMapping = (map, mapping) => {\n return addMappingInternal(false, map, mapping as Parameters[2]);\n };\n\n maybeAddMapping = (map, mapping) => {\n return addMappingInternal(true, map, mapping as Parameters[2]);\n };\n\n setSourceContent = (map, source, content) => {\n const { _sources: sources, _sourcesContent: sourcesContent } = map;\n sourcesContent[put(sources, source)] = content;\n };\n\n toDecodedMap = (map) => {\n const {\n file,\n sourceRoot,\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = map;\n removeEmptyFinalLines(mappings);\n\n return {\n version: 3,\n file: file || undefined,\n names: names.array,\n sourceRoot: sourceRoot || undefined,\n sources: sources.array,\n sourcesContent,\n mappings,\n };\n };\n\n toEncodedMap = (map) => {\n const decoded = toDecodedMap(map);\n return {\n ...decoded,\n mappings: encode(decoded.mappings as SourceMapSegment[][]),\n };\n };\n\n allMappings = (map) => {\n const out: Mapping[] = [];\n const { _mappings: mappings, _sources: sources, _names: names } = map;\n\n for (let i = 0; i < mappings.length; i++) {\n const line = mappings[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generated = { line: i + 1, column: seg[COLUMN] };\n let source: string | undefined = undefined;\n let original: Pos | undefined = undefined;\n let name: string | undefined = undefined;\n\n if (seg.length !== 1) {\n source = sources.array[seg[SOURCES_INDEX]];\n original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] };\n\n if (seg.length === 5) name = names.array[seg[NAMES_INDEX]];\n }\n\n out.push({ generated, source, original, name } as Mapping);\n }\n }\n\n return out;\n };\n\n fromMap = (input) => {\n const map = new TraceMap(input);\n const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot });\n\n putAll(gen._names, map.names);\n putAll(gen._sources, map.sources as string[]);\n gen._sourcesContent = map.sourcesContent || map.sources.map(() => null);\n gen._mappings = decodedMappings(map) as GenMapping['_mappings'];\n\n return gen;\n };\n\n // Internal helpers\n addSegmentInternal = (\n skipable,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n ) => {\n const {\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = map;\n const line = getLine(mappings, genLine);\n const index = getColumnIndex(line, genColumn);\n\n if (!source) {\n if (skipable && skipSourceless(line, index)) return;\n return insert(line, index, [genColumn]);\n }\n\n // Sigh, TypeScript can't figure out sourceLine and sourceColumn aren't nullish if source\n // isn't nullish.\n assert(sourceLine);\n assert(sourceColumn);\n\n const sourcesIndex = put(sources, source);\n const namesIndex = name ? put(names, name) : NO_NAME;\n if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content ?? null;\n\n if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {\n return;\n }\n\n return insert(\n line,\n index,\n name\n ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]\n : [genColumn, sourcesIndex, sourceLine, sourceColumn],\n );\n };\n }\n}\n\nfunction assert(_val: unknown): asserts _val is T {\n // noop.\n}\n\nfunction getLine(mappings: SourceMapSegment[][], index: number): SourceMapSegment[] {\n for (let i = mappings.length; i <= index; i++) {\n mappings[i] = [];\n }\n return mappings[index];\n}\n\nfunction getColumnIndex(line: SourceMapSegment[], genColumn: number): number {\n let index = line.length;\n for (let i = index - 1; i >= 0; index = i--) {\n const current = line[i];\n if (genColumn >= current[COLUMN]) break;\n }\n return index;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\nfunction removeEmptyFinalLines(mappings: SourceMapSegment[][]) {\n const { length } = mappings;\n let len = length;\n for (let i = len - 1; i >= 0; len = i, i--) {\n if (mappings[i].length > 0) break;\n }\n if (len < length) mappings.length = len;\n}\n\nfunction putAll(strarr: SetArray, array: string[]) {\n for (let i = 0; i < array.length; i++) put(strarr, array[i]);\n}\n\nfunction skipSourceless(line: SourceMapSegment[], index: number): boolean {\n // The start of a line is already sourceless, so adding a sourceless segment to the beginning\n // doesn't generate any useful information.\n if (index === 0) return true;\n\n const prev = line[index - 1];\n // If the previous segment is also sourceless, then adding another sourceless segment doesn't\n // genrate any new information. Else, this segment will end the source/named segment and point to\n // a sourceless position, which is useful.\n return prev.length === 1;\n}\n\nfunction skipSource(\n line: SourceMapSegment[],\n index: number,\n sourcesIndex: number,\n sourceLine: number,\n sourceColumn: number,\n namesIndex: number,\n): boolean {\n // A source/named segment at the start of a line gives position at that genColumn\n if (index === 0) return false;\n\n const prev = line[index - 1];\n\n // If the previous segment is sourceless, then we're transitioning to a source.\n if (prev.length === 1) return false;\n\n // If the previous segment maps to the exact same source position, then this segment doesn't\n // provide any new position information.\n return (\n sourcesIndex === prev[SOURCES_INDEX] &&\n sourceLine === prev[SOURCE_LINE] &&\n sourceColumn === prev[SOURCE_COLUMN] &&\n namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)\n );\n}\n\nfunction addMappingInternal(\n skipable: boolean,\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: S;\n original: S extends string ? Pos : null | undefined;\n name: S extends string ? string | null | undefined : null | undefined;\n content: S extends string ? string | null | undefined : null | undefined;\n },\n) {\n const { generated, source, original, name, content } = mapping;\n if (!source) {\n return addSegmentInternal(\n skipable,\n map,\n generated.line - 1,\n generated.column,\n null,\n null,\n null,\n null,\n null,\n );\n }\n const s: string = source;\n assert(original);\n return addSegmentInternal(\n skipable,\n map,\n generated.line - 1,\n generated.column,\n s,\n original.line - 1,\n original.column,\n name,\n content,\n );\n}\n"],"names":[],"mappings":";;;;AAWO,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,WAAW,GAAG,CAAC;;ACQ5B,MAAM,OAAO,GAAG,CAAC,CAAC,CAAC;AAEnB;;;AAGG;AACQ,IAAA,WA+BT;AAEF;;;AAGG;AACQ,IAAA,WA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C,IAAI,GAAG,CAAC,EAClB,SAAS,CAAC,MAAM,EAChB,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,CACL,CAAC;AACH,KAAA;IACD,MAAM,CAAC,GAAW,MAAM,CAAC;AAEzB,IAAA,OAAO,kBAAkB,CACvB,QAAQ,EACR,GAAG,EACH,SAAS,CAAC,IAAI,GAAG,CAAC,EAClB,SAAS,CAAC,MAAM,EAChB,CAAC,EACD,QAAQ,CAAC,IAAI,GAAG,CAAC,EACjB,QAAQ,CAAC,MAAM,EACf,IAAI,EACJ,OAAO,CACR,CAAC;AACJ;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js new file mode 100644 index 0000000..d9fcf5c --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js @@ -0,0 +1,236 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@jridgewell/set-array'), require('@jridgewell/sourcemap-codec'), require('@jridgewell/trace-mapping')) : + typeof define === 'function' && define.amd ? define(['exports', '@jridgewell/set-array', '@jridgewell/sourcemap-codec', '@jridgewell/trace-mapping'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.genMapping = {}, global.setArray, global.sourcemapCodec, global.traceMapping)); +})(this, (function (exports, setArray, sourcemapCodec, traceMapping) { 'use strict'; + + const COLUMN = 0; + const SOURCES_INDEX = 1; + const SOURCE_LINE = 2; + const SOURCE_COLUMN = 3; + const NAMES_INDEX = 4; + + const NO_NAME = -1; + /** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ + exports.addSegment = void 0; + /** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ + exports.addMapping = void 0; + /** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ + exports.maybeAddSegment = void 0; + /** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ + exports.maybeAddMapping = void 0; + /** + * Adds/removes the content of the source file to the source map. + */ + exports.setSourceContent = void 0; + /** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.toDecodedMap = void 0; + /** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.toEncodedMap = void 0; + /** + * Constructs a new GenMapping, using the already present mappings of the input. + */ + exports.fromMap = void 0; + /** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ + exports.allMappings = void 0; + // This split declaration is only so that terser can elminiate the static initialization block. + let addSegmentInternal; + /** + * Provides the state to generate a sourcemap. + */ + class GenMapping { + constructor({ file, sourceRoot } = {}) { + this._names = new setArray.SetArray(); + this._sources = new setArray.SetArray(); + this._sourcesContent = []; + this._mappings = []; + this.file = file; + this.sourceRoot = sourceRoot; + } + } + (() => { + exports.addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal(false, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); + }; + exports.maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); + }; + exports.addMapping = (map, mapping) => { + return addMappingInternal(false, map, mapping); + }; + exports.maybeAddMapping = (map, mapping) => { + return addMappingInternal(true, map, mapping); + }; + exports.setSourceContent = (map, source, content) => { + const { _sources: sources, _sourcesContent: sourcesContent } = map; + sourcesContent[setArray.put(sources, source)] = content; + }; + exports.toDecodedMap = (map) => { + const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + removeEmptyFinalLines(mappings); + return { + version: 3, + file: file || undefined, + names: names.array, + sourceRoot: sourceRoot || undefined, + sources: sources.array, + sourcesContent, + mappings, + }; + }; + exports.toEncodedMap = (map) => { + const decoded = exports.toDecodedMap(map); + return Object.assign(Object.assign({}, decoded), { mappings: sourcemapCodec.encode(decoded.mappings) }); + }; + exports.allMappings = (map) => { + const out = []; + const { _mappings: mappings, _sources: sources, _names: names } = map; + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generated = { line: i + 1, column: seg[COLUMN] }; + let source = undefined; + let original = undefined; + let name = undefined; + if (seg.length !== 1) { + source = sources.array[seg[SOURCES_INDEX]]; + original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] }; + if (seg.length === 5) + name = names.array[seg[NAMES_INDEX]]; + } + out.push({ generated, source, original, name }); + } + } + return out; + }; + exports.fromMap = (input) => { + const map = new traceMapping.TraceMap(input); + const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot }); + putAll(gen._names, map.names); + putAll(gen._sources, map.sources); + gen._sourcesContent = map.sourcesContent || map.sources.map(() => null); + gen._mappings = traceMapping.decodedMappings(map); + return gen; + }; + // Internal helpers + addSegmentInternal = (skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + const line = getLine(mappings, genLine); + const index = getColumnIndex(line, genColumn); + if (!source) { + if (skipable && skipSourceless(line, index)) + return; + return insert(line, index, [genColumn]); + } + const sourcesIndex = setArray.put(sources, source); + const namesIndex = name ? setArray.put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) + sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null; + if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { + return; + } + return insert(line, index, name + ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] + : [genColumn, sourcesIndex, sourceLine, sourceColumn]); + }; + })(); + function getLine(mappings, index) { + for (let i = mappings.length; i <= index; i++) { + mappings[i] = []; + } + return mappings[index]; + } + function getColumnIndex(line, genColumn) { + let index = line.length; + for (let i = index - 1; i >= 0; index = i--) { + const current = line[i]; + if (genColumn >= current[COLUMN]) + break; + } + return index; + } + function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; + } + function removeEmptyFinalLines(mappings) { + const { length } = mappings; + let len = length; + for (let i = len - 1; i >= 0; len = i, i--) { + if (mappings[i].length > 0) + break; + } + if (len < length) + mappings.length = len; + } + function putAll(strarr, array) { + for (let i = 0; i < array.length; i++) + setArray.put(strarr, array[i]); + } + function skipSourceless(line, index) { + // The start of a line is already sourceless, so adding a sourceless segment to the beginning + // doesn't generate any useful information. + if (index === 0) + return true; + const prev = line[index - 1]; + // If the previous segment is also sourceless, then adding another sourceless segment doesn't + // genrate any new information. Else, this segment will end the source/named segment and point to + // a sourceless position, which is useful. + return prev.length === 1; + } + function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { + // A source/named segment at the start of a line gives position at that genColumn + if (index === 0) + return false; + const prev = line[index - 1]; + // If the previous segment is sourceless, then we're transitioning to a source. + if (prev.length === 1) + return false; + // If the previous segment maps to the exact same source position, then this segment doesn't + // provide any new position information. + return (sourcesIndex === prev[SOURCES_INDEX] && + sourceLine === prev[SOURCE_LINE] && + sourceColumn === prev[SOURCE_COLUMN] && + namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)); + } + function addMappingInternal(skipable, map, mapping) { + const { generated, source, original, name, content } = mapping; + if (!source) { + return addSegmentInternal(skipable, map, generated.line - 1, generated.column, null, null, null, null, null); + } + const s = source; + return addSegmentInternal(skipable, map, generated.line - 1, generated.column, s, original.line - 1, original.column, name, content); + } + + exports.GenMapping = GenMapping; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=gen-mapping.umd.js.map diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map new file mode 100644 index 0000000..7cc8d14 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gen-mapping.umd.js","sources":["../src/sourcemap-segment.ts","../src/gen-mapping.ts"],"sourcesContent":["type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n","import { SetArray, put } from '@jridgewell/set-array';\nimport { encode } from '@jridgewell/sourcemap-codec';\nimport { TraceMap, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type { SourceMapInput } from '@jridgewell/trace-mapping';\nimport type { SourceMapSegment } from './sourcemap-segment';\nimport type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types';\n\nexport type { DecodedSourceMap, EncodedSourceMap, Mapping };\n\nexport type Options = {\n file?: string | null;\n sourceRoot?: string | null;\n};\n\nconst NO_NAME = -1;\n\n/**\n * A low-level API to associate a generated position with an original source position. Line and\n * column here are 0-based, unlike `addMapping`.\n */\nexport let addSegment: {\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source?: null,\n sourceLine?: null,\n sourceColumn?: null,\n name?: null,\n content?: null,\n ): void;\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name?: null,\n content?: string | null,\n ): void;\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name: string,\n content?: string | null,\n ): void;\n};\n\n/**\n * A high-level API to associate a generated position with an original source position. Line is\n * 1-based, but column is 0-based, due to legacy behavior in `source-map` library.\n */\nexport let addMapping: {\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source?: null;\n original?: null;\n name?: null;\n content?: null;\n },\n ): void;\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name?: null;\n content?: string | null;\n },\n ): void;\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name: string;\n content?: string | null;\n },\n ): void;\n};\n\n/**\n * Same as `addSegment`, but will only add the segment if it generates useful information in the\n * resulting map. This only works correctly if segments are added **in order**, meaning you should\n * not add a segment with a lower generated line/column than one that came before.\n */\nexport let maybeAddSegment: typeof addSegment;\n\n/**\n * Same as `addMapping`, but will only add the mapping if it generates useful information in the\n * resulting map. This only works correctly if mappings are added **in order**, meaning you should\n * not add a mapping with a lower generated line/column than one that came before.\n */\nexport let maybeAddMapping: typeof addMapping;\n\n/**\n * Adds/removes the content of the source file to the source map.\n */\nexport let setSourceContent: (map: GenMapping, source: string, content: string | null) => void;\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let toDecodedMap: (map: GenMapping) => DecodedSourceMap;\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let toEncodedMap: (map: GenMapping) => EncodedSourceMap;\n\n/**\n * Constructs a new GenMapping, using the already present mappings of the input.\n */\nexport let fromMap: (input: SourceMapInput) => GenMapping;\n\n/**\n * Returns an array of high-level mapping objects for every recorded segment, which could then be\n * passed to the `source-map` library.\n */\nexport let allMappings: (map: GenMapping) => Mapping[];\n\n// This split declaration is only so that terser can elminiate the static initialization block.\nlet addSegmentInternal: (\n skipable: boolean,\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: S,\n sourceLine: S extends string ? number : null | undefined,\n sourceColumn: S extends string ? number : null | undefined,\n name: S extends string ? string | null | undefined : null | undefined,\n content: S extends string ? string | null | undefined : null | undefined,\n) => void;\n\n/**\n * Provides the state to generate a sourcemap.\n */\nexport class GenMapping {\n private _names = new SetArray();\n private _sources = new SetArray();\n private _sourcesContent: (string | null)[] = [];\n private _mappings: SourceMapSegment[][] = [];\n declare file: string | null | undefined;\n declare sourceRoot: string | null | undefined;\n\n constructor({ file, sourceRoot }: Options = {}) {\n this.file = file;\n this.sourceRoot = sourceRoot;\n }\n\n static {\n addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {\n return addSegmentInternal(\n false,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n );\n };\n\n maybeAddSegment = (\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n ) => {\n return addSegmentInternal(\n true,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n );\n };\n\n addMapping = (map, mapping) => {\n return addMappingInternal(false, map, mapping as Parameters[2]);\n };\n\n maybeAddMapping = (map, mapping) => {\n return addMappingInternal(true, map, mapping as Parameters[2]);\n };\n\n setSourceContent = (map, source, content) => {\n const { _sources: sources, _sourcesContent: sourcesContent } = map;\n sourcesContent[put(sources, source)] = content;\n };\n\n toDecodedMap = (map) => {\n const {\n file,\n sourceRoot,\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = map;\n removeEmptyFinalLines(mappings);\n\n return {\n version: 3,\n file: file || undefined,\n names: names.array,\n sourceRoot: sourceRoot || undefined,\n sources: sources.array,\n sourcesContent,\n mappings,\n };\n };\n\n toEncodedMap = (map) => {\n const decoded = toDecodedMap(map);\n return {\n ...decoded,\n mappings: encode(decoded.mappings as SourceMapSegment[][]),\n };\n };\n\n allMappings = (map) => {\n const out: Mapping[] = [];\n const { _mappings: mappings, _sources: sources, _names: names } = map;\n\n for (let i = 0; i < mappings.length; i++) {\n const line = mappings[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generated = { line: i + 1, column: seg[COLUMN] };\n let source: string | undefined = undefined;\n let original: Pos | undefined = undefined;\n let name: string | undefined = undefined;\n\n if (seg.length !== 1) {\n source = sources.array[seg[SOURCES_INDEX]];\n original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] };\n\n if (seg.length === 5) name = names.array[seg[NAMES_INDEX]];\n }\n\n out.push({ generated, source, original, name } as Mapping);\n }\n }\n\n return out;\n };\n\n fromMap = (input) => {\n const map = new TraceMap(input);\n const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot });\n\n putAll(gen._names, map.names);\n putAll(gen._sources, map.sources as string[]);\n gen._sourcesContent = map.sourcesContent || map.sources.map(() => null);\n gen._mappings = decodedMappings(map) as GenMapping['_mappings'];\n\n return gen;\n };\n\n // Internal helpers\n addSegmentInternal = (\n skipable,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n ) => {\n const {\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = map;\n const line = getLine(mappings, genLine);\n const index = getColumnIndex(line, genColumn);\n\n if (!source) {\n if (skipable && skipSourceless(line, index)) return;\n return insert(line, index, [genColumn]);\n }\n\n // Sigh, TypeScript can't figure out sourceLine and sourceColumn aren't nullish if source\n // isn't nullish.\n assert(sourceLine);\n assert(sourceColumn);\n\n const sourcesIndex = put(sources, source);\n const namesIndex = name ? put(names, name) : NO_NAME;\n if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content ?? null;\n\n if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {\n return;\n }\n\n return insert(\n line,\n index,\n name\n ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]\n : [genColumn, sourcesIndex, sourceLine, sourceColumn],\n );\n };\n }\n}\n\nfunction assert(_val: unknown): asserts _val is T {\n // noop.\n}\n\nfunction getLine(mappings: SourceMapSegment[][], index: number): SourceMapSegment[] {\n for (let i = mappings.length; i <= index; i++) {\n mappings[i] = [];\n }\n return mappings[index];\n}\n\nfunction getColumnIndex(line: SourceMapSegment[], genColumn: number): number {\n let index = line.length;\n for (let i = index - 1; i >= 0; index = i--) {\n const current = line[i];\n if (genColumn >= current[COLUMN]) break;\n }\n return index;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\nfunction removeEmptyFinalLines(mappings: SourceMapSegment[][]) {\n const { length } = mappings;\n let len = length;\n for (let i = len - 1; i >= 0; len = i, i--) {\n if (mappings[i].length > 0) break;\n }\n if (len < length) mappings.length = len;\n}\n\nfunction putAll(strarr: SetArray, array: string[]) {\n for (let i = 0; i < array.length; i++) put(strarr, array[i]);\n}\n\nfunction skipSourceless(line: SourceMapSegment[], index: number): boolean {\n // The start of a line is already sourceless, so adding a sourceless segment to the beginning\n // doesn't generate any useful information.\n if (index === 0) return true;\n\n const prev = line[index - 1];\n // If the previous segment is also sourceless, then adding another sourceless segment doesn't\n // genrate any new information. Else, this segment will end the source/named segment and point to\n // a sourceless position, which is useful.\n return prev.length === 1;\n}\n\nfunction skipSource(\n line: SourceMapSegment[],\n index: number,\n sourcesIndex: number,\n sourceLine: number,\n sourceColumn: number,\n namesIndex: number,\n): boolean {\n // A source/named segment at the start of a line gives position at that genColumn\n if (index === 0) return false;\n\n const prev = line[index - 1];\n\n // If the previous segment is sourceless, then we're transitioning to a source.\n if (prev.length === 1) return false;\n\n // If the previous segment maps to the exact same source position, then this segment doesn't\n // provide any new position information.\n return (\n sourcesIndex === prev[SOURCES_INDEX] &&\n sourceLine === prev[SOURCE_LINE] &&\n sourceColumn === prev[SOURCE_COLUMN] &&\n namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)\n );\n}\n\nfunction addMappingInternal(\n skipable: boolean,\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: S;\n original: S extends string ? Pos : null | undefined;\n name: S extends string ? string | null | undefined : null | undefined;\n content: S extends string ? string | null | undefined : null | undefined;\n },\n) {\n const { generated, source, original, name, content } = mapping;\n if (!source) {\n return addSegmentInternal(\n skipable,\n map,\n generated.line - 1,\n generated.column,\n null,\n null,\n null,\n null,\n null,\n );\n }\n const s: string = source;\n assert(original);\n return addSegmentInternal(\n skipable,\n map,\n generated.line - 1,\n generated.column,\n s,\n original.line - 1,\n original.column,\n name,\n content,\n );\n}\n"],"names":["addSegment","addMapping","maybeAddSegment","maybeAddMapping","setSourceContent","toDecodedMap","toEncodedMap","fromMap","allMappings","SetArray","put","encode","TraceMap","decodedMappings"],"mappings":";;;;;;IAWO,MAAM,MAAM,GAAG,CAAC,CAAC;IACjB,MAAM,aAAa,GAAG,CAAC,CAAC;IACxB,MAAM,WAAW,GAAG,CAAC,CAAC;IACtB,MAAM,aAAa,GAAG,CAAC,CAAC;IACxB,MAAM,WAAW,GAAG,CAAC;;ICQ5B,MAAM,OAAO,GAAG,CAAC,CAAC,CAAC;IAEnB;;;IAGG;AACQA,gCA+BT;IAEF;;;IAGG;AACQC,gCA+BT;IAEF;;;;IAIG;AACQC,qCAAmC;IAE9C;;;;IAIG;AACQC,qCAAmC;IAE9C;;IAEG;AACQC,sCAAoF;IAE/F;;;IAGG;AACQC,kCAAoD;IAE/D;;;IAGG;AACQC,kCAAoD;IAE/D;;IAEG;AACQC,6BAA+C;IAE1D;;;IAGG;AACQC,iCAA4C;IAEvD;IACA,IAAI,kBAUK,CAAC;IAEV;;IAEG;UACU,UAAU,CAAA;IAQrB,IAAA,WAAA,CAAY,EAAE,IAAI,EAAE,UAAU,KAAc,EAAE,EAAA;IAPtC,QAA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,MAAM,EACf,IAAI,EACJ,OAAO,CACR,CAAC;IACJ;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts b/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts new file mode 100644 index 0000000..d510d74 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts @@ -0,0 +1,90 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types'; +export type { DecodedSourceMap, EncodedSourceMap, Mapping }; +export declare type Options = { + file?: string | null; + sourceRoot?: string | null; +}; +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +export declare let addSegment: { + (map: GenMapping, genLine: number, genColumn: number, source?: null, sourceLine?: null, sourceColumn?: null, name?: null, content?: null): void; + (map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name?: null, content?: string | null): void; + (map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name: string, content?: string | null): void; +}; +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +export declare let addMapping: { + (map: GenMapping, mapping: { + generated: Pos; + source?: null; + original?: null; + name?: null; + content?: null; + }): void; + (map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name?: null; + content?: string | null; + }): void; + (map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name: string; + content?: string | null; + }): void; +}; +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +export declare let maybeAddSegment: typeof addSegment; +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +export declare let maybeAddMapping: typeof addMapping; +/** + * Adds/removes the content of the source file to the source map. + */ +export declare let setSourceContent: (map: GenMapping, source: string, content: string | null) => void; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let toDecodedMap: (map: GenMapping) => DecodedSourceMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let toEncodedMap: (map: GenMapping) => EncodedSourceMap; +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +export declare let fromMap: (input: SourceMapInput) => GenMapping; +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +export declare let allMappings: (map: GenMapping) => Mapping[]; +/** + * Provides the state to generate a sourcemap. + */ +export declare class GenMapping { + private _names; + private _sources; + private _sourcesContent; + private _mappings; + file: string | null | undefined; + sourceRoot: string | null | undefined; + constructor({ file, sourceRoot }?: Options); +} diff --git a/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts b/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts new file mode 100644 index 0000000..e187ba9 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts @@ -0,0 +1,12 @@ +declare type GeneratedColumn = number; +declare type SourcesIndex = number; +declare type SourceLine = number; +declare type SourceColumn = number; +declare type NamesIndex = number; +export declare type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export {}; diff --git a/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts b/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts new file mode 100644 index 0000000..b309c81 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts @@ -0,0 +1,35 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +export interface SourceMapV3 { + file?: string | null; + names: readonly string[]; + sourceRoot?: string; + sources: readonly (string | null)[]; + sourcesContent?: readonly (string | null)[]; + version: 3; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: readonly SourceMapSegment[][]; +} +export interface Pos { + line: number; + column: number; +} +export declare type Mapping = { + generated: Pos; + source: undefined; + original: undefined; + name: undefined; +} | { + generated: Pos; + source: string; + original: Pos; + name: string; +} | { + generated: Pos; + source: string; + original: Pos; + name: undefined; +}; diff --git a/node_modules/@jridgewell/gen-mapping/package.json b/node_modules/@jridgewell/gen-mapping/package.json new file mode 100644 index 0000000..69e0ac8 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/package.json @@ -0,0 +1,77 @@ +{ + "name": "@jridgewell/gen-mapping", + "version": "0.3.3", + "description": "Generate source maps", + "keywords": [ + "source", + "map" + ], + "author": "Justin Ridgewell ", + "license": "MIT", + "repository": "https://github.com/jridgewell/gen-mapping", + "main": "dist/gen-mapping.umd.js", + "module": "dist/gen-mapping.mjs", + "types": "dist/types/gen-mapping.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/gen-mapping.d.ts", + "browser": "./dist/gen-mapping.umd.js", + "require": "./dist/gen-mapping.umd.js", + "import": "./dist/gen-mapping.mjs" + }, + "./dist/gen-mapping.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node benchmark/index.mjs", + "prebuild": "rm -rf dist", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:coverage", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "run-p 'build:rollup -- --watch' 'test:only -- --watch'", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build" + }, + "devDependencies": { + "@rollup/plugin-typescript": "8.3.2", + "@types/mocha": "9.1.1", + "@types/node": "17.0.29", + "@typescript-eslint/eslint-plugin": "5.21.0", + "@typescript-eslint/parser": "5.21.0", + "benchmark": "2.1.4", + "c8": "7.11.2", + "eslint": "8.14.0", + "eslint-config-prettier": "8.5.0", + "mocha": "9.2.2", + "npm-run-all": "4.1.5", + "prettier": "2.6.2", + "rollup": "2.70.2", + "typescript": "4.6.3" + }, + "dependencies": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" + } +} diff --git a/node_modules/@jridgewell/resolve-uri/LICENSE b/node_modules/@jridgewell/resolve-uri/LICENSE new file mode 100644 index 0000000..0a81b2a --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/LICENSE @@ -0,0 +1,19 @@ +Copyright 2019 Justin Ridgewell + +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/@jridgewell/resolve-uri/README.md b/node_modules/@jridgewell/resolve-uri/README.md new file mode 100644 index 0000000..2fe70df --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/README.md @@ -0,0 +1,40 @@ +# @jridgewell/resolve-uri + +> Resolve a URI relative to an optional base URI + +Resolve any combination of absolute URIs, protocol-realtive URIs, absolute paths, or relative paths. + +## Installation + +```sh +npm install @jridgewell/resolve-uri +``` + +## Usage + +```typescript +function resolve(input: string, base?: string): string; +``` + +```js +import resolve from '@jridgewell/resolve-uri'; + +resolve('foo', 'https://example.com'); // => 'https://example.com/foo' +``` + +| Input | Base | Resolution | Explanation | +|-----------------------|-------------------------|--------------------------------|--------------------------------------------------------------| +| `https://example.com` | _any_ | `https://example.com/` | Input is normalized only | +| `//example.com` | `https://base.com/` | `https://example.com/` | Input inherits the base's protocol | +| `//example.com` | _rest_ | `//example.com/` | Input is normalized only | +| `/example` | `https://base.com/` | `https://base.com/example` | Input inherits the base's origin | +| `/example` | `//base.com/` | `//base.com/example` | Input inherits the base's host and remains protocol relative | +| `/example` | _rest_ | `/example` | Input is normalized only | +| `example` | `https://base.com/dir/` | `https://base.com/dir/example` | Input is joined with the base | +| `example` | `https://base.com/file` | `https://base.com/example` | Input is joined with the base without its file | +| `example` | `//base.com/dir/` | `//base.com/dir/example` | Input is joined with the base's last directory | +| `example` | `//base.com/file` | `//base.com/example` | Input is joined with the base without its file | +| `example` | `/base/dir/` | `/base/dir/example` | Input is joined with the base's last directory | +| `example` | `/base/file` | `/base/example` | Input is joined with the base without its file | +| `example` | `base/dir/` | `base/dir/example` | Input is joined with the base's last directory | +| `example` | `base/file` | `base/example` | Input is joined with the base without its file | diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs new file mode 100644 index 0000000..94d8dce --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs @@ -0,0 +1,242 @@ +// Matches the scheme of a URL, eg "http://" +const schemeRegex = /^[\w+.-]+:\/\//; +/** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ +const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; +/** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ +const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; +var UrlType; +(function (UrlType) { + UrlType[UrlType["Empty"] = 1] = "Empty"; + UrlType[UrlType["Hash"] = 2] = "Hash"; + UrlType[UrlType["Query"] = 3] = "Query"; + UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; + UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; + UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; + UrlType[UrlType["Absolute"] = 7] = "Absolute"; +})(UrlType || (UrlType = {})); +function isAbsoluteUrl(input) { + return schemeRegex.test(input); +} +function isSchemeRelativeUrl(input) { + return input.startsWith('//'); +} +function isAbsolutePath(input) { + return input.startsWith('/'); +} +function isFileUrl(input) { + return input.startsWith('file:'); +} +function isRelative(input) { + return /^[.?#]/.test(input); +} +function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); +} +function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); +} +function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: UrlType.Absolute, + }; +} +function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = UrlType.SchemeRelative; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = UrlType.AbsolutePath; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? UrlType.Query + : input.startsWith('#') + ? UrlType.Hash + : UrlType.RelativePath + : UrlType.Empty; + return url; +} +function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} +function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } +} +/** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ +function normalizePath(url, type) { + const rel = type <= UrlType.RelativePath; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; +} +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== UrlType.Absolute) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case UrlType.Empty: + url.hash = baseUrl.hash; + // fall through + case UrlType.Hash: + url.query = baseUrl.query; + // fall through + case UrlType.Query: + case UrlType.RelativePath: + mergePaths(url, baseUrl); + // fall through + case UrlType.AbsolutePath: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case UrlType.SchemeRelative: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case UrlType.Hash: + case UrlType.Query: + return queryHash; + case UrlType.RelativePath: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case UrlType.AbsolutePath: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } +} + +export { resolve as default }; +//# sourceMappingURL=resolve-uri.mjs.map diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map new file mode 100644 index 0000000..009d043 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.mjs","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nenum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":"AAAA;AACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAErC;;;;;;;;;;AAUA,MAAM,QAAQ,GAAG,0EAA0E,CAAC;AAE5F;;;;;;;;;AASA,MAAM,SAAS,GAAG,iEAAiE,CAAC;AAapF,IAAK,OAQJ;AARD,WAAK,OAAO;IACV,uCAAS,CAAA;IACT,qCAAQ,CAAA;IACR,uCAAS,CAAA;IACT,qDAAgB,CAAA;IAChB,qDAAgB,CAAA;IAChB,yDAAkB,CAAA;IAClB,6CAAY,CAAA;AACd,CAAC,EARI,OAAO,KAAP,OAAO,QAQX;AAED,SAAS,aAAa,CAAC,KAAa;IAClC,OAAO,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACjC,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAa;IACxC,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAChC,CAAC;AAED,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,SAAS,CAAC,KAAa;IAC9B,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;AACnC,CAAC;AAED,SAAS,UAAU,CAAC,KAAa;IAC/B,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAa;IACrC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC;IACpC,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C;;YAG1B,KAAK,OAAO,CAAC,cAAc;;gBAEzB,GAAG,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;SAC/B;QACD,IAAI,QAAQ,GAAG,SAAS;YAAE,SAAS,GAAG,QAAQ,CAAC;KAChD;IAED,aAAa,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;IAE9B,MAAM,SAAS,GAAG,GAAG,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC;IACvC,QAAQ,SAAS;;;QAIf,KAAK,OAAO,CAAC,IAAI,CAAC;QAClB,KAAK,OAAO,CAAC,KAAK;YAChB,OAAO,SAAS,CAAC;QAEnB,KAAK,OAAO,CAAC,YAAY,EAAE;;YAEzB,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAE/B,IAAI,CAAC,IAAI;gBAAE,OAAO,SAAS,IAAI,GAAG,CAAC;YAEnC,IAAI,UAAU,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;;;;gBAIlD,OAAO,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;aAChC;YAED,OAAO,IAAI,GAAG,SAAS,CAAC;SACzB;QAED,KAAK,OAAO,CAAC,YAAY;YACvB,OAAO,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;QAE9B;YACE,OAAO,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;KACpF;AACH;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js new file mode 100644 index 0000000..0700a2d --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js @@ -0,0 +1,250 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.resolveURI = factory()); +})(this, (function () { 'use strict'; + + // Matches the scheme of a URL, eg "http://" + const schemeRegex = /^[\w+.-]+:\/\//; + /** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ + const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; + /** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ + const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; + var UrlType; + (function (UrlType) { + UrlType[UrlType["Empty"] = 1] = "Empty"; + UrlType[UrlType["Hash"] = 2] = "Hash"; + UrlType[UrlType["Query"] = 3] = "Query"; + UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; + UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; + UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; + UrlType[UrlType["Absolute"] = 7] = "Absolute"; + })(UrlType || (UrlType = {})); + function isAbsoluteUrl(input) { + return schemeRegex.test(input); + } + function isSchemeRelativeUrl(input) { + return input.startsWith('//'); + } + function isAbsolutePath(input) { + return input.startsWith('/'); + } + function isFileUrl(input) { + return input.startsWith('file:'); + } + function isRelative(input) { + return /^[.?#]/.test(input); + } + function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); + } + function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); + } + function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: UrlType.Absolute, + }; + } + function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = UrlType.SchemeRelative; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = UrlType.AbsolutePath; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? UrlType.Query + : input.startsWith('#') + ? UrlType.Hash + : UrlType.RelativePath + : UrlType.Empty; + return url; + } + function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } + } + /** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ + function normalizePath(url, type) { + const rel = type <= UrlType.RelativePath; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; + } + /** + * Attempts to resolve `input` URL/path relative to `base`. + */ + function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== UrlType.Absolute) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case UrlType.Empty: + url.hash = baseUrl.hash; + // fall through + case UrlType.Hash: + url.query = baseUrl.query; + // fall through + case UrlType.Query: + case UrlType.RelativePath: + mergePaths(url, baseUrl); + // fall through + case UrlType.AbsolutePath: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case UrlType.SchemeRelative: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case UrlType.Hash: + case UrlType.Query: + return queryHash; + case UrlType.RelativePath: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case UrlType.AbsolutePath: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } + } + + return resolve; + +})); +//# sourceMappingURL=resolve-uri.umd.js.map diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map new file mode 100644 index 0000000..a3e39eb --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.umd.js","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nenum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":";;;;;;IAAA;IACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;IAErC;;;;;;;;;;IAUA,MAAM,QAAQ,GAAG,0EAA0E,CAAC;IAE5F;;;;;;;;;IASA,MAAM,SAAS,GAAG,iEAAiE,CAAC;IAapF,IAAK,OAQJ;IARD,WAAK,OAAO;QACV,uCAAS,CAAA;QACT,qCAAQ,CAAA;QACR,uCAAS,CAAA;QACT,qDAAgB,CAAA;QAChB,qDAAgB,CAAA;QAChB,yDAAkB,CAAA;QAClB,6CAAY,CAAA;IACd,CAAC,EARI,OAAO,KAAP,OAAO,QAQX;IAED,SAAS,aAAa,CAAC,KAAa;QAClC,OAAO,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IAED,SAAS,mBAAmB,CAAC,KAAa;QACxC,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;IAED,SAAS,cAAc,CAAC,KAAa;QACnC,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC;IAED,SAAS,SAAS,CAAC,KAAa;QAC9B,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACnC,CAAC;IAED,SAAS,UAAU,CAAC,KAAa;QAC/B,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;IAED,SAAS,gBAAgB,CAAC,KAAa;QACrC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC;QACpC,OAAO,OAAO,CACZ,KAAK,CAAC,CAAC,CAAC,EACR,KAAK,CAAC,CA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,GAAG,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;aAC/B;YACD,IAAI,QAAQ,GAAG,SAAS;gBAAE,SAAS,GAAG,QAAQ,CAAC;SAChD;QAED,aAAa,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;QAE9B,MAAM,SAAS,GAAG,GAAG,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC;QACvC,QAAQ,SAAS;;;YAIf,KAAK,OAAO,CAAC,IAAI,CAAC;YAClB,KAAK,OAAO,CAAC,KAAK;gBAChB,OAAO,SAAS,CAAC;YAEnB,KAAK,OAAO,CAAC,YAAY,EAAE;;gBAEzB,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;gBAE/B,IAAI,CAAC,IAAI;oBAAE,OAAO,SAAS,IAAI,GAAG,CAAC;gBAEnC,IAAI,UAAU,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;;;;oBAIlD,OAAO,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;iBAChC;gBAED,OAAO,IAAI,GAAG,SAAS,CAAC;aACzB;YAED,KAAK,OAAO,CAAC,YAAY;gBACvB,OAAO,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;YAE9B;gBACE,OAAO,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;SACpF;IACH;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts b/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts new file mode 100644 index 0000000..b7f0b3b --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts @@ -0,0 +1,4 @@ +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/@jridgewell/resolve-uri/package.json b/node_modules/@jridgewell/resolve-uri/package.json new file mode 100644 index 0000000..114937a --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/package.json @@ -0,0 +1,69 @@ +{ + "name": "@jridgewell/resolve-uri", + "version": "3.1.0", + "description": "Resolve a URI relative to an optional base URI", + "keywords": [ + "resolve", + "uri", + "url", + "path" + ], + "author": "Justin Ridgewell ", + "license": "MIT", + "repository": "https://github.com/jridgewell/resolve-uri", + "main": "dist/resolve-uri.umd.js", + "module": "dist/resolve-uri.mjs", + "typings": "dist/types/resolve-uri.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/resolve-uri.d.ts", + "browser": "./dist/resolve-uri.umd.js", + "require": "./dist/resolve-uri.umd.js", + "import": "./dist/resolve-uri.mjs" + }, + "./dist/resolve-uri.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "prebuild": "rm -rf dist", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build" + }, + "devDependencies": { + "@jridgewell/resolve-uri-latest": "npm:@jridgewell/resolve-uri@*", + "@rollup/plugin-typescript": "8.3.0", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "c8": "7.11.0", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.66.0", + "typescript": "4.5.5" + } +} diff --git a/node_modules/@jridgewell/set-array/LICENSE b/node_modules/@jridgewell/set-array/LICENSE new file mode 100644 index 0000000..352f071 --- /dev/null +++ b/node_modules/@jridgewell/set-array/LICENSE @@ -0,0 +1,19 @@ +Copyright 2022 Justin Ridgewell + +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/@jridgewell/set-array/README.md b/node_modules/@jridgewell/set-array/README.md new file mode 100644 index 0000000..2ed155f --- /dev/null +++ b/node_modules/@jridgewell/set-array/README.md @@ -0,0 +1,37 @@ +# @jridgewell/set-array + +> Like a Set, but provides the index of the `key` in the backing array + +This is designed to allow synchronizing a second array with the contents of the backing array, like +how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, and there +are never duplicates. + +## Installation + +```sh +npm install @jridgewell/set-array +``` + +## Usage + +```js +import { SetArray, get, put, pop } from '@jridgewell/set-array'; + +const sa = new SetArray(); + +let index = put(sa, 'first'); +assert.strictEqual(index, 0); + +index = put(sa, 'second'); +assert.strictEqual(index, 1); + +assert.deepEqual(sa.array, [ 'first', 'second' ]); + +index = get(sa, 'first'); +assert.strictEqual(index, 0); + +pop(sa); +index = get(sa, 'second'); +assert.strictEqual(index, undefined); +assert.deepEqual(sa.array, [ 'first' ]); +``` diff --git a/node_modules/@jridgewell/set-array/dist/set-array.mjs b/node_modules/@jridgewell/set-array/dist/set-array.mjs new file mode 100644 index 0000000..b7f1a9c --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/set-array.mjs @@ -0,0 +1,48 @@ +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +let get; +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +let put; +/** + * Pops the last added item out of the SetArray. + */ +let pop; +/** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +class SetArray { + constructor() { + this._indexes = { __proto__: null }; + this.array = []; + } +} +(() => { + get = (strarr, key) => strarr._indexes[key]; + put = (strarr, key) => { + // The key may or may not be present. If it is present, it's a number. + const index = get(strarr, key); + if (index !== undefined) + return index; + const { array, _indexes: indexes } = strarr; + return (indexes[key] = array.push(key) - 1); + }; + pop = (strarr) => { + const { array, _indexes: indexes } = strarr; + if (array.length === 0) + return; + const last = array.pop(); + indexes[last] = undefined; + }; +})(); + +export { SetArray, get, pop, put }; +//# sourceMappingURL=set-array.mjs.map diff --git a/node_modules/@jridgewell/set-array/dist/set-array.mjs.map b/node_modules/@jridgewell/set-array/dist/set-array.mjs.map new file mode 100644 index 0000000..ead5643 --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/set-array.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"set-array.mjs","sources":["../src/set-array.ts"],"sourcesContent":["/**\n * Gets the index associated with `key` in the backing array, if it is already present.\n */\nexport let get: (strarr: SetArray, key: string) => number | undefined;\n\n/**\n * Puts `key` into the backing array, if it is not already present. Returns\n * the index of the `key` in the backing array.\n */\nexport let put: (strarr: SetArray, key: string) => number;\n\n/**\n * Pops the last added item out of the SetArray.\n */\nexport let pop: (strarr: SetArray) => void;\n\n/**\n * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the\n * index of the `key` in the backing array.\n *\n * This is designed to allow synchronizing a second array with the contents of the backing array,\n * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,\n * and there are never duplicates.\n */\nexport class SetArray {\n private declare _indexes: { [key: string]: number | undefined };\n declare array: readonly string[];\n\n constructor() {\n this._indexes = { __proto__: null } as any;\n this.array = [];\n }\n\n static {\n get = (strarr, key) => strarr._indexes[key];\n\n put = (strarr, key) => {\n // The key may or may not be present. If it is present, it's a number.\n const index = get(strarr, key);\n if (index !== undefined) return index;\n\n const { array, _indexes: indexes } = strarr;\n\n return (indexes[key] = (array as string[]).push(key) - 1);\n };\n\n pop = (strarr) => {\n const { array, _indexes: indexes } = strarr;\n if (array.length === 0) return;\n\n const last = (array as string[]).pop()!;\n indexes[last] = undefined;\n };\n }\n}\n"],"names":[],"mappings":"AAAA;;;IAGW,IAA2D;AAEtE;;;;IAIW,IAA+C;AAE1D;;;IAGW,IAAgC;AAE3C;;;;;;;;MAQa,QAAQ;IAInB;QACE,IAAI,CAAC,QAAQ,GAAG,EAAE,SAAS,EAAE,IAAI,EAAS,CAAC;QAC3C,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;KACjB;CAuBF;AArBC;IACE,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG,KAAK,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IAE5C,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG;;QAEhB,MAAM,KAAK,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAC/B,IAAI,KAAK,KAAK,SAAS;YAAE,OAAO,KAAK,CAAC;QAEtC,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;QAE5C,QAAQ,OAAO,CAAC,GAAG,CAAC,GAAI,KAAkB,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;KAC3D,CAAC;IAEF,GAAG,GAAG,CAAC,MAAM;QACX,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;QAC5C,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO;QAE/B,MAAM,IAAI,GAAI,KAAkB,CAAC,GAAG,EAAG,CAAC;QACxC,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC;KAC3B,CAAC;AACJ,CAAC,GAAA;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/set-array/dist/set-array.umd.js b/node_modules/@jridgewell/set-array/dist/set-array.umd.js new file mode 100644 index 0000000..a1c200a --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/set-array.umd.js @@ -0,0 +1,58 @@ +(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.setArray = {})); +})(this, (function (exports) { 'use strict'; + + /** + * Gets the index associated with `key` in the backing array, if it is already present. + */ + exports.get = void 0; + /** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ + exports.put = void 0; + /** + * Pops the last added item out of the SetArray. + */ + exports.pop = void 0; + /** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ + class SetArray { + constructor() { + this._indexes = { __proto__: null }; + this.array = []; + } + } + (() => { + exports.get = (strarr, key) => strarr._indexes[key]; + exports.put = (strarr, key) => { + // The key may or may not be present. If it is present, it's a number. + const index = exports.get(strarr, key); + if (index !== undefined) + return index; + const { array, _indexes: indexes } = strarr; + return (indexes[key] = array.push(key) - 1); + }; + exports.pop = (strarr) => { + const { array, _indexes: indexes } = strarr; + if (array.length === 0) + return; + const last = array.pop(); + indexes[last] = undefined; + }; + })(); + + exports.SetArray = SetArray; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=set-array.umd.js.map diff --git a/node_modules/@jridgewell/set-array/dist/set-array.umd.js.map b/node_modules/@jridgewell/set-array/dist/set-array.umd.js.map new file mode 100644 index 0000000..10005af --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/set-array.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"set-array.umd.js","sources":["../src/set-array.ts"],"sourcesContent":["/**\n * Gets the index associated with `key` in the backing array, if it is already present.\n */\nexport let get: (strarr: SetArray, key: string) => number | undefined;\n\n/**\n * Puts `key` into the backing array, if it is not already present. Returns\n * the index of the `key` in the backing array.\n */\nexport let put: (strarr: SetArray, key: string) => number;\n\n/**\n * Pops the last added item out of the SetArray.\n */\nexport let pop: (strarr: SetArray) => void;\n\n/**\n * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the\n * index of the `key` in the backing array.\n *\n * This is designed to allow synchronizing a second array with the contents of the backing array,\n * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,\n * and there are never duplicates.\n */\nexport class SetArray {\n private declare _indexes: { [key: string]: number | undefined };\n declare array: readonly string[];\n\n constructor() {\n this._indexes = { __proto__: null } as any;\n this.array = [];\n }\n\n static {\n get = (strarr, key) => strarr._indexes[key];\n\n put = (strarr, key) => {\n // The key may or may not be present. If it is present, it's a number.\n const index = get(strarr, key);\n if (index !== undefined) return index;\n\n const { array, _indexes: indexes } = strarr;\n\n return (indexes[key] = (array as string[]).push(key) - 1);\n };\n\n pop = (strarr) => {\n const { array, _indexes: indexes } = strarr;\n if (array.length === 0) return;\n\n const last = (array as string[]).pop()!;\n indexes[last] = undefined;\n };\n }\n}\n"],"names":["get","put","pop"],"mappings":";;;;;;IAAA;;;AAGWA,yBAA2D;IAEtE;;;;AAIWC,yBAA+C;IAE1D;;;AAGWC,yBAAgC;IAE3C;;;;;;;;UAQa,QAAQ;QAInB;YACE,IAAI,CAAC,QAAQ,GAAG,EAAE,SAAS,EAAE,IAAI,EAAS,CAAC;YAC3C,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;SACjB;KAuBF;IArBC;QACEF,WAAG,GAAG,CAAC,MAAM,EAAE,GAAG,KAAK,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;QAE5CC,WAAG,GAAG,CAAC,MAAM,EAAE,GAAG;;YAEhB,MAAM,KAAK,GAAGD,WAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;YAC/B,IAAI,KAAK,KAAK,SAAS;gBAAE,OAAO,KAAK,CAAC;YAEtC,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;YAE5C,QAAQ,OAAO,CAAC,GAAG,CAAC,GAAI,KAAkB,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;SAC3D,CAAC;QAEFE,WAAG,GAAG,CAAC,MAAM;YACX,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;YAC5C,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;gBAAE,OAAO;YAE/B,MAAM,IAAI,GAAI,KAAkB,CAAC,GAAG,EAAG,CAAC;YACxC,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC;SAC3B,CAAC;IACJ,CAAC,GAAA;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/set-array/dist/types/set-array.d.ts b/node_modules/@jridgewell/set-array/dist/types/set-array.d.ts new file mode 100644 index 0000000..7ed59b9 --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/types/set-array.d.ts @@ -0,0 +1,26 @@ +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +export declare let get: (strarr: SetArray, key: string) => number | undefined; +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +export declare let put: (strarr: SetArray, key: string) => number; +/** + * Pops the last added item out of the SetArray. + */ +export declare let pop: (strarr: SetArray) => void; +/** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +export declare class SetArray { + private _indexes; + array: readonly string[]; + constructor(); +} diff --git a/node_modules/@jridgewell/set-array/package.json b/node_modules/@jridgewell/set-array/package.json new file mode 100644 index 0000000..aec4ee0 --- /dev/null +++ b/node_modules/@jridgewell/set-array/package.json @@ -0,0 +1,66 @@ +{ + "name": "@jridgewell/set-array", + "version": "1.1.2", + "description": "Like a Set, but provides the index of the `key` in the backing array", + "keywords": [], + "author": "Justin Ridgewell ", + "license": "MIT", + "repository": "https://github.com/jridgewell/set-array", + "main": "dist/set-array.umd.js", + "module": "dist/set-array.mjs", + "typings": "dist/types/set-array.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/set-array.d.ts", + "browser": "./dist/set-array.umd.js", + "require": "./dist/set-array.umd.js", + "import": "./dist/set-array.mjs" + }, + "./dist/set-array.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist", + "src" + ], + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "prebuild": "rm -rf dist", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build" + }, + "devDependencies": { + "@rollup/plugin-typescript": "8.3.0", + "@types/mocha": "9.1.1", + "@types/node": "17.0.29", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "c8": "7.11.0", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.66.0", + "typescript": "4.5.5" + } +} diff --git a/node_modules/@jridgewell/set-array/src/set-array.ts b/node_modules/@jridgewell/set-array/src/set-array.ts new file mode 100644 index 0000000..f9ff604 --- /dev/null +++ b/node_modules/@jridgewell/set-array/src/set-array.ts @@ -0,0 +1,55 @@ +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +export let get: (strarr: SetArray, key: string) => number | undefined; + +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +export let put: (strarr: SetArray, key: string) => number; + +/** + * Pops the last added item out of the SetArray. + */ +export let pop: (strarr: SetArray) => void; + +/** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +export class SetArray { + private declare _indexes: { [key: string]: number | undefined }; + declare array: readonly string[]; + + constructor() { + this._indexes = { __proto__: null } as any; + this.array = []; + } + + static { + get = (strarr, key) => strarr._indexes[key]; + + put = (strarr, key) => { + // The key may or may not be present. If it is present, it's a number. + const index = get(strarr, key); + if (index !== undefined) return index; + + const { array, _indexes: indexes } = strarr; + + return (indexes[key] = (array as string[]).push(key) - 1); + }; + + pop = (strarr) => { + const { array, _indexes: indexes } = strarr; + if (array.length === 0) return; + + const last = (array as string[]).pop()!; + indexes[last] = undefined; + }; + } +} diff --git a/node_modules/@jridgewell/sourcemap-codec/LICENSE b/node_modules/@jridgewell/sourcemap-codec/LICENSE new file mode 100644 index 0000000..a331065 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2015 Rich Harris + +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/@jridgewell/sourcemap-codec/README.md b/node_modules/@jridgewell/sourcemap-codec/README.md new file mode 100644 index 0000000..5cbb315 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/README.md @@ -0,0 +1,200 @@ +# @jridgewell/sourcemap-codec + +Encode/decode the `mappings` property of a [sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). + + +## Why? + +Sourcemaps are difficult to generate and manipulate, because the `mappings` property – the part that actually links the generated code back to the original source – is encoded using an obscure method called [Variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity). On top of that, each segment in the mapping contains offsets rather than absolute indices, which means that you can't look at a segment in isolation – you have to understand the whole sourcemap. + +This package makes the process slightly easier. + + +## Installation + +```bash +npm install @jridgewell/sourcemap-codec +``` + + +## Usage + +```js +import { encode, decode } from '@jridgewell/sourcemap-codec'; + +var decoded = decode( ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); + +assert.deepEqual( decoded, [ + // the first line (of the generated code) has no mappings, + // as shown by the starting semi-colon (which separates lines) + [], + + // the second line contains four (comma-separated) segments + [ + // segments are encoded as you'd expect: + // [ generatedCodeColumn, sourceIndex, sourceCodeLine, sourceCodeColumn, nameIndex ] + + // i.e. the first segment begins at column 2, and maps back to the second column + // of the second line (both zero-based) of the 0th source, and uses the 0th + // name in the `map.names` array + [ 2, 0, 2, 2, 0 ], + + // the remaining segments are 4-length rather than 5-length, + // because they don't map a name + [ 4, 0, 2, 4 ], + [ 6, 0, 2, 5 ], + [ 7, 0, 2, 7 ] + ], + + // the final line contains two segments + [ + [ 2, 1, 10, 19 ], + [ 12, 1, 11, 20 ] + ] +]); + +var encoded = encode( decoded ); +assert.equal( encoded, ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map - 45120 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 5479160 bytes +sourcemap-codec 5659336 bytes +source-map-0.6.1 17144440 bytes +source-map-0.8.0 6867424 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 502 ops/sec ±1.03% (90 runs sampled) +decode: sourcemap-codec x 445 ops/sec ±0.97% (92 runs sampled) +decode: source-map-0.6.1 x 36.01 ops/sec ±1.64% (49 runs sampled) +decode: source-map-0.8.0 x 367 ops/sec ±0.04% (95 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 1261620 bytes +sourcemap-codec 9119248 bytes +source-map-0.6.1 8968560 bytes +source-map-0.8.0 8952952 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 738 ops/sec ±0.42% (98 runs sampled) +encode: sourcemap-codec x 238 ops/sec ±0.73% (88 runs sampled) +encode: source-map-0.6.1 x 162 ops/sec ±0.43% (84 runs sampled) +encode: source-map-0.8.0 x 191 ops/sec ±0.34% (90 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +babel.min.js.map - 347793 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 35338184 bytes +sourcemap-codec 35922736 bytes +source-map-0.6.1 62366360 bytes +source-map-0.8.0 44337416 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 40.35 ops/sec ±4.47% (54 runs sampled) +decode: sourcemap-codec x 36.76 ops/sec ±3.67% (51 runs sampled) +decode: source-map-0.6.1 x 4.44 ops/sec ±2.15% (16 runs sampled) +decode: source-map-0.8.0 x 59.35 ops/sec ±0.05% (78 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +@jridgewell/sourcemap-codec 7212604 bytes +sourcemap-codec 21421456 bytes +source-map-0.6.1 25286888 bytes +source-map-0.8.0 25498744 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 112 ops/sec ±0.13% (84 runs sampled) +encode: sourcemap-codec x 30.23 ops/sec ±2.76% (53 runs sampled) +encode: source-map-0.6.1 x 19.43 ops/sec ±3.70% (37 runs sampled) +encode: source-map-0.8.0 x 19.40 ops/sec ±3.26% (37 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +preact.js.map - 1992 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 500272 bytes +sourcemap-codec 516864 bytes +source-map-0.6.1 1596672 bytes +source-map-0.8.0 517272 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 16,137 ops/sec ±0.17% (99 runs sampled) +decode: sourcemap-codec x 12,139 ops/sec ±0.13% (99 runs sampled) +decode: source-map-0.6.1 x 1,264 ops/sec ±0.12% (100 runs sampled) +decode: source-map-0.8.0 x 9,894 ops/sec ±0.08% (101 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 321026 bytes +sourcemap-codec 830832 bytes +source-map-0.6.1 586608 bytes +source-map-0.8.0 586680 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 19,876 ops/sec ±0.78% (95 runs sampled) +encode: sourcemap-codec x 6,983 ops/sec ±0.15% (100 runs sampled) +encode: source-map-0.6.1 x 5,070 ops/sec ±0.12% (102 runs sampled) +encode: source-map-0.8.0 x 5,641 ops/sec ±0.17% (100 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +react.js.map - 5726 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 734848 bytes +sourcemap-codec 954200 bytes +source-map-0.6.1 2276432 bytes +source-map-0.8.0 955488 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 5,723 ops/sec ±0.12% (98 runs sampled) +decode: sourcemap-codec x 4,555 ops/sec ±0.09% (101 runs sampled) +decode: source-map-0.6.1 x 437 ops/sec ±0.11% (93 runs sampled) +decode: source-map-0.8.0 x 3,441 ops/sec ±0.15% (100 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 638672 bytes +sourcemap-codec 1109840 bytes +source-map-0.6.1 1321224 bytes +source-map-0.8.0 1324448 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 6,801 ops/sec ±0.48% (98 runs sampled) +encode: sourcemap-codec x 2,533 ops/sec ±0.13% (101 runs sampled) +encode: source-map-0.6.1 x 2,248 ops/sec ±0.08% (100 runs sampled) +encode: source-map-0.8.0 x 2,303 ops/sec ±0.15% (100 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec +``` + +# License + +MIT diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs new file mode 100644 index 0000000..3dff372 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs @@ -0,0 +1,164 @@ +const comma = ','.charCodeAt(0); +const semicolon = ';'.charCodeAt(0); +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const intToChar = new Uint8Array(64); // 64 possible chars. +const charToInt = new Uint8Array(128); // z is 122 in ASCII +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +// Provide a fallback for older environments. +const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; +function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; +} +function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; +} +function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; +} +function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); +} +function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; +} + +export { decode, encode }; +//# sourceMappingURL=sourcemap-codec.mjs.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map new file mode 100644 index 0000000..236fd12 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.mjs","sources":["../src/sourcemap-codec.ts"],"sourcesContent":["export type SourceMapSegment =\n | [number]\n | [number, number, number, number]\n | [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nconst comma = ','.charCodeAt(0);\nconst semicolon = ';'.charCodeAt(0);\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst intToChar = new Uint8Array(64); // 64 possible chars.\nconst charToInt = new Uint8Array(128); // z is 122 in ASCII\n\nfor (let i = 0; i < chars.length; i++) {\n const c = chars.charCodeAt(i);\n intToChar[i] = c;\n charToInt[c] = i;\n}\n\n// Provide a fallback for older environments.\nconst td =\n typeof TextDecoder !== 'undefined'\n ? /* #__PURE__ */ new TextDecoder()\n : typeof Buffer !== 'undefined'\n ? {\n decode(buf: Uint8Array) {\n const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);\n return out.toString();\n },\n }\n : {\n decode(buf: Uint8Array) {\n let out = '';\n for (let i = 0; i < buf.length; i++) {\n out += String.fromCharCode(buf[i]);\n }\n return out;\n },\n };\n\nexport function decode(mappings: string): SourceMapMappings {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const decoded: SourceMapMappings = [];\n\n let index = 0;\n do {\n const semi = indexOf(mappings, index);\n const line: SourceMapLine = [];\n let sorted = true;\n let lastCol = 0;\n state[0] = 0;\n\n for (let i = index; i < semi; i++) {\n let seg: SourceMapSegment;\n\n i = decodeInteger(mappings, i, state, 0); // genColumn\n const col = state[0];\n if (col < lastCol) sorted = false;\n lastCol = col;\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 1); // sourcesIndex\n i = decodeInteger(mappings, i, state, 2); // sourceLine\n i = decodeInteger(mappings, i, state, 3); // sourceColumn\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 4); // namesIndex\n seg = [col, state[1], state[2], state[3], state[4]];\n } else {\n seg = [col, state[1], state[2], state[3]];\n }\n } else {\n seg = [col];\n }\n\n line.push(seg);\n }\n\n if (!sorted) sort(line);\n decoded.push(line);\n index = semi + 1;\n } while (index <= mappings.length);\n\n return decoded;\n}\n\nfunction indexOf(mappings: string, index: number): number {\n const idx = mappings.indexOf(';', index);\n return idx === -1 ? mappings.length : idx;\n}\n\nfunction decodeInteger(mappings: string, pos: number, state: SourceMapSegment, j: number): number {\n let value = 0;\n let shift = 0;\n let integer = 0;\n\n do {\n const c = mappings.charCodeAt(pos++);\n integer = charToInt[c];\n value |= (integer & 31) << shift;\n shift += 5;\n } while (integer & 32);\n\n const shouldNegate = value & 1;\n value >>>= 1;\n\n if (shouldNegate) {\n value = -0x80000000 | -value;\n }\n\n state[j] += value;\n return pos;\n}\n\nfunction hasMoreVlq(mappings: string, i: number, length: number): boolean {\n if (i >= length) return false;\n return mappings.charCodeAt(i) !== comma;\n}\n\nfunction sort(line: SourceMapSegment[]) {\n line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[0] - b[0];\n}\n\nexport function encode(decoded: SourceMapMappings): string;\nexport function encode(decoded: Readonly): string;\nexport function encode(decoded: Readonly): string {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const bufLength = 1024 * 16;\n const subLength = bufLength - 36;\n const buf = new Uint8Array(bufLength);\n const sub = buf.subarray(0, subLength);\n let pos = 0;\n let out = '';\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n if (i > 0) {\n if (pos === bufLength) {\n out += td.decode(buf);\n pos = 0;\n }\n buf[pos++] = semicolon;\n }\n if (line.length === 0) continue;\n\n state[0] = 0;\n\n for (let j = 0; j < line.length; j++) {\n const segment = line[j];\n // We can push up to 5 ints, each int can take at most 7 chars, and we\n // may push a comma.\n if (pos > subLength) {\n out += td.decode(sub);\n buf.copyWithin(0, subLength, pos);\n pos -= subLength;\n }\n if (j > 0) buf[pos++] = comma;\n\n pos = encodeInteger(buf, pos, state, segment, 0); // genColumn\n\n if (segment.length === 1) continue;\n pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex\n pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine\n pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn\n\n if (segment.length === 4) continue;\n pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex\n }\n }\n\n return out + td.decode(buf.subarray(0, pos));\n}\n\nfunction encodeInteger(\n buf: Uint8Array,\n pos: number,\n state: SourceMapSegment,\n segment: SourceMapSegment,\n j: number,\n): number {\n const next = segment[j];\n let num = next - state[j];\n state[j] = next;\n\n num = num < 0 ? (-num << 1) | 1 : num << 1;\n do {\n let clamped = num & 0b011111;\n num >>>= 5;\n if (num > 0) clamped |= 0b100000;\n buf[pos++] = intToChar[clamped];\n } while (num > 0);\n\n return pos;\n}\n"],"names":[],"mappings":"AAOA,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AAChC,MAAM,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AACpC,MAAM,KAAK,GAAG,kEAAkE,CAAC;AACjF,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,E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EAAE,GAAG,CAAC,CAAC,CAAC;AAC/C,CAAC;AAED,SAAS,aAAa,CACpB,GAAe,EACf,GAAW,EACX,KAAuB,EACvB,OAAyB,EACzB,CAAS;IAET,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACxB,IAAI,GAAG,GAAG,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IAC1B,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IAEhB,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;IAC3C,GAAG;QACD,IAAI,OAAO,GAAG,GAAG,GAAG,QAAQ,CAAC;QAC7B,GAAG,MAAM,CAAC,CAAC;QACX,IAAI,GAAG,GAAG,CAAC;YAAE,OAAO,IAAI,QAAQ,CAAC;QACjC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;KACjC,QAAQ,GAAG,GAAG,CAAC,EAAE;IAElB,OAAO,GAAG,CAAC;AACb;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js new file mode 100644 index 0000000..bec92a9 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js @@ -0,0 +1,175 @@ +(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.sourcemapCodec = {})); +})(this, (function (exports) { 'use strict'; + + const comma = ','.charCodeAt(0); + const semicolon = ';'.charCodeAt(0); + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + const intToChar = new Uint8Array(64); // 64 possible chars. + const charToInt = new Uint8Array(128); // z is 122 in ASCII + for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; + } + // Provide a fallback for older environments. + const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; + function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; + } + function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; + } + function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; + } + function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; + } + function sort(line) { + line.sort(sortComparator); + } + function sortComparator(a, b) { + return a[0] - b[0]; + } + function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); + } + function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; + } + + exports.decode = decode; + exports.encode = encode; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=sourcemap-codec.umd.js.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map new file mode 100644 index 0000000..b6b2003 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.umd.js","sources":["../src/sourcemap-codec.ts"],"sourcesContent":["export type SourceMapSegment =\n | [number]\n | [number, number, number, number]\n | [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nconst comma = ','.charCodeAt(0);\nconst semicolon = ';'.charCodeAt(0);\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst intToChar = new Uint8Array(64); // 64 possible chars.\nconst charToInt = new Uint8Array(128); // z is 122 in ASCII\n\nfor (let i = 0; i < chars.length; i++) {\n const c = chars.charCodeAt(i);\n intToChar[i] = c;\n charToInt[c] = i;\n}\n\n// Provide a fallback for older environments.\nconst td =\n typeof TextDecoder !== 'undefined'\n ? /* #__PURE__ */ new TextDecoder()\n : typeof Buffer !== 'undefined'\n ? {\n decode(buf: Uint8Array) {\n const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);\n return out.toString();\n },\n }\n : {\n decode(buf: Uint8Array) {\n let out = '';\n for (let i = 0; i < buf.length; i++) {\n out += String.fromCharCode(buf[i]);\n }\n return out;\n },\n };\n\nexport function decode(mappings: string): SourceMapMappings {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const decoded: SourceMapMappings = [];\n\n let index = 0;\n do {\n const semi = indexOf(mappings, index);\n const line: SourceMapLine = [];\n let sorted = true;\n let lastCol = 0;\n state[0] = 0;\n\n for (let i = index; i < semi; i++) {\n let seg: SourceMapSegment;\n\n i = decodeInteger(mappings, i, state, 0); // genColumn\n const col = state[0];\n if (col < lastCol) sorted = false;\n lastCol = col;\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 1); // sourcesIndex\n i = decodeInteger(mappings, i, state, 2); // sourceLine\n i = decodeInteger(mappings, i, state, 3); // sourceColumn\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 4); // namesIndex\n seg = [col, state[1], state[2], state[3], state[4]];\n } else {\n seg = [col, state[1], state[2], state[3]];\n }\n } else {\n seg = [col];\n }\n\n line.push(seg);\n }\n\n if (!sorted) sort(line);\n decoded.push(line);\n index = semi + 1;\n } while (index <= mappings.length);\n\n return decoded;\n}\n\nfunction indexOf(mappings: string, index: number): number {\n const idx = mappings.indexOf(';', index);\n return idx === -1 ? mappings.length : idx;\n}\n\nfunction decodeInteger(mappings: string, pos: number, state: SourceMapSegment, j: number): number {\n let value = 0;\n let shift = 0;\n let integer = 0;\n\n do {\n const c = mappings.charCodeAt(pos++);\n integer = charToInt[c];\n value |= (integer & 31) << shift;\n shift += 5;\n } while (integer & 32);\n\n const shouldNegate = value & 1;\n value >>>= 1;\n\n if (shouldNegate) {\n value = -0x80000000 | -value;\n }\n\n state[j] += value;\n return pos;\n}\n\nfunction hasMoreVlq(mappings: string, i: number, length: number): boolean {\n if (i >= length) return false;\n return mappings.charCodeAt(i) !== comma;\n}\n\nfunction sort(line: SourceMapSegment[]) {\n line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[0] - b[0];\n}\n\nexport function encode(decoded: SourceMapMappings): string;\nexport function encode(decoded: Readonly): string;\nexport function encode(decoded: Readonly): string {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const bufLength = 1024 * 16;\n const subLength = bufLength - 36;\n const buf = new Uint8Array(bufLength);\n const sub = buf.subarray(0, subLength);\n let pos = 0;\n let out = '';\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n if (i > 0) {\n if (pos === bufLength) {\n out += td.decode(buf);\n pos = 0;\n }\n buf[pos++] = semicolon;\n }\n if (line.length === 0) continue;\n\n state[0] = 0;\n\n for (let j = 0; j < line.length; j++) {\n const segment = line[j];\n // We can push up to 5 ints, each int can take at most 7 chars, and we\n // may push a comma.\n if (pos > subLength) {\n out += td.decode(sub);\n buf.copyWithin(0, subLength, pos);\n pos -= subLength;\n }\n if (j > 0) buf[pos++] = comma;\n\n pos = encodeInteger(buf, pos, state, segment, 0); // genColumn\n\n if (segment.length === 1) continue;\n pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex\n pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine\n pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn\n\n if (segment.length === 4) continue;\n pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex\n }\n }\n\n return out + td.decode(buf.subarray(0, pos));\n}\n\nfunction encodeInteger(\n buf: Uint8Array,\n pos: number,\n state: SourceMapSegment,\n segment: SourceMapSegment,\n j: number,\n): number {\n const next = segment[j];\n let num = next - state[j];\n state[j] = next;\n\n num = num < 0 ? (-num << 1) | 1 : num << 1;\n do {\n let clamped = num & 0b011111;\n num >>>= 5;\n if (num > 0) clamped |= 0b100000;\n buf[pos++] = intToChar[clamped];\n } while (num > 0);\n\n return pos;\n}\n"],"names":[],"mappings":";;;;;;IAOA,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAChC,MAAM,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IACpC,MAAM,KAAK,GAAG,kEAAkE,CAAC;IACjF,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;IACrC,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;IAEtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACrC,MAAM,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC9B,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACjB,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAClB;IAED;IACA,MAAM,EAAE,GACN,OAAO,WAAW,KAAK,WAAW;0BACd,IAAI,WAAW,EAAE;UACjC,OA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CAAC,CAAC;QAC3C,GAAG;YACD,IAAI,OAAO,GAAG,GAAG,GAAG,QAAQ,CAAC;YAC7B,GAAG,MAAM,CAAC,CAAC;YACX,IAAI,GAAG,GAAG,CAAC;gBAAE,OAAO,IAAI,QAAQ,CAAC;YACjC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;SACjC,QAAQ,GAAG,GAAG,CAAC,EAAE;QAElB,OAAO,GAAG,CAAC;IACb;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts b/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts new file mode 100644 index 0000000..410d320 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts @@ -0,0 +1,6 @@ +export declare type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export declare type SourceMapLine = SourceMapSegment[]; +export declare type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; diff --git a/node_modules/@jridgewell/sourcemap-codec/package.json b/node_modules/@jridgewell/sourcemap-codec/package.json new file mode 100644 index 0000000..578448f --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/package.json @@ -0,0 +1,74 @@ +{ + "name": "@jridgewell/sourcemap-codec", + "version": "1.4.15", + "description": "Encode/decode sourcemap mappings", + "keywords": [ + "sourcemap", + "vlq" + ], + "main": "dist/sourcemap-codec.umd.js", + "module": "dist/sourcemap-codec.mjs", + "types": "dist/types/sourcemap-codec.d.ts", + "files": [ + "dist" + ], + "exports": { + ".": [ + { + "types": "./dist/types/sourcemap-codec.d.ts", + "browser": "./dist/sourcemap-codec.umd.js", + "require": "./dist/sourcemap-codec.umd.js", + "import": "./dist/sourcemap-codec.mjs" + }, + "./dist/sourcemap-codec.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.js", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemap-codec.git" + }, + "author": "Rich Harris", + "license": "MIT", + "devDependencies": { + "@rollup/plugin-typescript": "8.3.0", + "@types/node": "17.0.15", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "benchmark": "2.1.4", + "c8": "7.11.2", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.64.0", + "source-map": "0.6.1", + "source-map-js": "1.0.2", + "sourcemap-codec": "1.4.8", + "typescript": "4.5.4" + } +} diff --git a/node_modules/@jridgewell/trace-mapping/LICENSE b/node_modules/@jridgewell/trace-mapping/LICENSE new file mode 100644 index 0000000..37bb488 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2022 Justin Ridgewell + +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/@jridgewell/trace-mapping/README.md b/node_modules/@jridgewell/trace-mapping/README.md new file mode 100644 index 0000000..cc5e4f9 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/README.md @@ -0,0 +1,252 @@ +# @jridgewell/trace-mapping + +> Trace the original position through a source map + +`trace-mapping` allows you to take the line and column of an output file and trace it to the +original location in the source file through a source map. + +You may already be familiar with the [`source-map`][source-map] package's `SourceMapConsumer`. This +provides the same `originalPositionFor` and `generatedPositionFor` API, without requiring WASM. + +## Installation + +```sh +npm install @jridgewell/trace-mapping +``` + +## Usage + +```typescript +import { + TraceMap, + originalPositionFor, + generatedPositionFor, + sourceContentFor, +} from '@jridgewell/trace-mapping'; + +const tracer = new TraceMap({ + version: 3, + sources: ['input.js'], + sourcesContent: ['content of input.js'], + names: ['foo'], + mappings: 'KAyCIA', +}); + +// Lines start at line 1, columns at column 0. +const traced = originalPositionFor(tracer, { line: 1, column: 5 }); +assert.deepEqual(traced, { + source: 'input.js', + line: 42, + column: 4, + name: 'foo', +}); + +const content = sourceContentFor(tracer, traced.source); +assert.strictEqual(content, 'content for input.js'); + +const generated = generatedPositionFor(tracer, { + source: 'input.js', + line: 42, + column: 4, +}); +assert.deepEqual(generated, { + line: 1, + column: 5, +}); +``` + +We also provide a lower level API to get the actual segment that matches our line and column. Unlike +`originalPositionFor`, `traceSegment` uses a 0-base for `line`: + +```typescript +import { traceSegment } from '@jridgewell/trace-mapping'; + +// line is 0-base. +const traced = traceSegment(tracer, /* line */ 0, /* column */ 5); + +// Segments are [outputColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] +// Again, line is 0-base and so is sourceLine +assert.deepEqual(traced, [5, 0, 41, 4, 0]); +``` + +### SectionedSourceMaps + +The sourcemap spec defines a special `sections` field that's designed to handle concatenation of +output code with associated sourcemaps. This type of sourcemap is rarely used (no major build tool +produces it), but if you are hand coding a concatenation you may need it. We provide an `AnyMap` +helper that can receive either a regular sourcemap or a `SectionedSourceMap` and returns a +`TraceMap` instance: + +```typescript +import { AnyMap } from '@jridgewell/trace-mapping'; +const fooOutput = 'foo'; +const barOutput = 'bar'; +const output = [fooOutput, barOutput].join('\n'); + +const sectioned = new AnyMap({ + version: 3, + sections: [ + { + // 0-base line and column + offset: { line: 0, column: 0 }, + // fooOutput's sourcemap + map: { + version: 3, + sources: ['foo.js'], + names: ['foo'], + mappings: 'AAAAA', + }, + }, + { + // barOutput's sourcemap will not affect the first line, only the second + offset: { line: 1, column: 0 }, + map: { + version: 3, + sources: ['bar.js'], + names: ['bar'], + mappings: 'AAAAA', + }, + }, + ], +}); + +const traced = originalPositionFor(sectioned, { + line: 2, + column: 0, +}); + +assert.deepEqual(traced, { + source: 'bar.js', + line: 1, + column: 0, + name: 'bar', +}); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map - 45120 segments + +Memory Usage: +trace-mapping decoded 562400 bytes +trace-mapping encoded 5706544 bytes +source-map-js 10717664 bytes +source-map-0.6.1 17446384 bytes +source-map-0.8.0 9701757 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 180 ops/sec ±0.34% (85 runs sampled) +trace-mapping: encoded JSON input x 364 ops/sec ±1.77% (89 runs sampled) +trace-mapping: decoded Object input x 3,116 ops/sec ±0.50% (96 runs sampled) +trace-mapping: encoded Object input x 410 ops/sec ±2.62% (85 runs sampled) +source-map-js: encoded Object input x 84.23 ops/sec ±0.91% (73 runs sampled) +source-map-0.6.1: encoded Object input x 37.21 ops/sec ±2.08% (51 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed: +trace-mapping: decoded originalPositionFor x 3,952,212 ops/sec ±0.17% (98 runs sampled) +trace-mapping: encoded originalPositionFor x 3,487,468 ops/sec ±1.58% (90 runs sampled) +source-map-js: encoded originalPositionFor x 827,730 ops/sec ±0.78% (97 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 748,991 ops/sec ±0.53% (94 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 2,532,894 ops/sec ±0.57% (95 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +babel.min.js.map - 347793 segments + +Memory Usage: +trace-mapping decoded 89832 bytes +trace-mapping encoded 35474640 bytes +source-map-js 51257176 bytes +source-map-0.6.1 63515664 bytes +source-map-0.8.0 42933752 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 15.41 ops/sec ±8.65% (34 runs sampled) +trace-mapping: encoded JSON input x 28.20 ops/sec ±12.87% (42 runs sampled) +trace-mapping: decoded Object input x 964 ops/sec ±0.36% (99 runs sampled) +trace-mapping: encoded Object input x 31.77 ops/sec ±13.79% (45 runs sampled) +source-map-js: encoded Object input x 6.45 ops/sec ±5.16% (21 runs sampled) +source-map-0.6.1: encoded Object input x 4.07 ops/sec ±5.24% (15 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed: +trace-mapping: decoded originalPositionFor x 7,183,038 ops/sec ±0.58% (95 runs sampled) +trace-mapping: encoded originalPositionFor x 5,192,185 ops/sec ±0.41% (100 runs sampled) +source-map-js: encoded originalPositionFor x 4,259,489 ops/sec ±0.79% (94 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 3,742,629 ops/sec ±0.71% (95 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 6,270,211 ops/sec ±0.64% (94 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +preact.js.map - 1992 segments + +Memory Usage: +trace-mapping decoded 37128 bytes +trace-mapping encoded 247280 bytes +source-map-js 1143536 bytes +source-map-0.6.1 1290992 bytes +source-map-0.8.0 96544 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 3,483 ops/sec ±0.30% (98 runs sampled) +trace-mapping: encoded JSON input x 6,092 ops/sec ±0.18% (97 runs sampled) +trace-mapping: decoded Object input x 249,076 ops/sec ±0.24% (98 runs sampled) +trace-mapping: encoded Object input x 14,555 ops/sec ±0.48% (100 runs sampled) +source-map-js: encoded Object input x 2,447 ops/sec ±0.36% (99 runs sampled) +source-map-0.6.1: encoded Object input x 1,201 ops/sec ±0.57% (96 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed: +trace-mapping: decoded originalPositionFor x 7,620,192 ops/sec ±0.09% (99 runs sampled) +trace-mapping: encoded originalPositionFor x 6,872,554 ops/sec ±0.30% (97 runs sampled) +source-map-js: encoded originalPositionFor x 2,489,570 ops/sec ±0.35% (94 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 1,698,633 ops/sec ±0.28% (98 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 4,015,644 ops/sec ±0.22% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +react.js.map - 5726 segments + +Memory Usage: +trace-mapping decoded 16176 bytes +trace-mapping encoded 681552 bytes +source-map-js 2418352 bytes +source-map-0.6.1 2443672 bytes +source-map-0.8.0 111768 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 1,720 ops/sec ±0.34% (98 runs sampled) +trace-mapping: encoded JSON input x 4,406 ops/sec ±0.35% (100 runs sampled) +trace-mapping: decoded Object input x 92,122 ops/sec ±0.10% (99 runs sampled) +trace-mapping: encoded Object input x 5,385 ops/sec ±0.37% (99 runs sampled) +source-map-js: encoded Object input x 794 ops/sec ±0.40% (98 runs sampled) +source-map-0.6.1: encoded Object input x 416 ops/sec ±0.54% (91 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed: +trace-mapping: decoded originalPositionFor x 32,759,519 ops/sec ±0.33% (100 runs sampled) +trace-mapping: encoded originalPositionFor x 31,116,306 ops/sec ±0.33% (97 runs sampled) +source-map-js: encoded originalPositionFor x 17,458,435 ops/sec ±0.44% (97 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 12,687,097 ops/sec ±0.43% (95 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 23,538,275 ops/sec ±0.38% (95 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor +``` + +[source-map]: https://www.npmjs.com/package/source-map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs new file mode 100644 index 0000000..917a330 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs @@ -0,0 +1,552 @@ +import { encode, decode } from '@jridgewell/sourcemap-codec'; +import resolveUri from '@jridgewell/resolve-uri'; + +function resolve(input, base) { + // The base is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + if (base && !base.endsWith('/')) + base += '/'; + return resolveUri(input, base); +} + +/** + * Removes everything after the last "/", but leaves the slash. + */ +function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; +const REV_GENERATED_LINE = 1; +const REV_GENERATED_COLUMN = 2; + +function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} +function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; +} +function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; +} +function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; +} + +let found = false; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; +} +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); +} + +// Rebuilds the original source files, with mappings that are ordered by source line/column instead +// of generated line/column. +function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) + continue; + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = [])); + const memo = memos[sourceIndex]; + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like +// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. +// Numeric properties on objects are magically sorted in ascending order by the engine regardless of +// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending +// order when iterating with for-in. +function buildNullArray() { + return { __proto__: null }; +} + +const AnyMap = function (map, mapUrl) { + const parsed = typeof map === 'string' ? JSON.parse(map) : map; + if (!('sections' in parsed)) + return new TraceMap(parsed, mapUrl); + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, 0, 0, Infinity, Infinity); + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + }; + return presortedDecodedMap(joined); +}; +function recurse(input, mapUrl, mappings, sources, sourcesContent, names, lineOffset, columnOffset, stopLine, stopColumn) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } + else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + addSection(map, mapUrl, mappings, sources, sourcesContent, names, lineOffset + offset.line, columnOffset + offset.column, sl, sc); + } +} +function addSection(input, mapUrl, mappings, sources, sourcesContent, names, lineOffset, columnOffset, stopLine, stopColumn) { + if ('sections' in input) + return recurse(...arguments); + const map = new TraceMap(input, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources, sourcesContent: contents } = map; + append(sources, resolvedSources); + append(names, map.names); + if (contents) + append(sourcesContent, contents); + else + for (let i = 0; i < resolvedSources.length; i++) + sourcesContent.push(null); + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. But it may not have any columns that overstep, so we + // still need to check that we don't overstep lines, too. + if (lineI > stopLine) + return; + // The out line may already exist in mappings (if we're continuing the line started by a + // previous section). Or, we may have jumped ahead several lines to start this section. + const out = getLine(mappings, lineI); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (lineI === stopLine && column >= stopColumn) + return; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push(seg.length === 4 + ? [column, sourcesIndex, sourceLine, sourceColumn] + : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); + } + } +} +function append(arr, other) { + for (let i = 0; i < other.length; i++) + arr.push(other[i]); +} +function getLine(arr, index) { + for (let i = arr.length; i <= index; i++) + arr[i] = []; + return arr[index]; +} + +const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; +const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; +const LEAST_UPPER_BOUND = -1; +const GREATEST_LOWER_BOUND = 1; +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +let encodedMappings; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +let decodedMappings; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +let traceSegment; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +let originalPositionFor; +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +let generatedPositionFor; +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +let allGeneratedPositionsFor; +/** + * Iterates each mapping in generated position order. + */ +let eachMapping; +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +let sourceContentFor; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +let presortedDecodedMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let decodedMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let encodedMap; +class TraceMap { + constructor(map, mapUrl) { + const isString = typeof map === 'string'; + if (!isString && map._decodedMemo) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } +} +(() => { + encodedMappings = (map) => { + var _a; + return ((_a = map._encoded) !== null && _a !== void 0 ? _a : (map._encoded = encode(map._decoded))); + }; + decodedMappings = (map) => { + return (map._decoded || (map._decoded = decode(map._encoded))); + }; + traceSegment = (map, line, column) => { + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + const segments = decoded[line]; + const index = traceSegmentInternal(segments, map._decodedMemo, line, column, GREATEST_LOWER_BOUND); + return index === -1 ? null : segments[index]; + }; + originalPositionFor = (map, { line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (index === -1) + return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) + return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null); + }; + allGeneratedPositionsFor = (map, { source, line, column, bias }) => { + // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit. + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); + }; + generatedPositionFor = (map, { source, line, column, bias }) => { + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); + }; + eachMapping = (map, cb) => { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) + name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + }); + } + } + }; + sourceContentFor = (map, source) => { + const { sources, resolvedSources, sourcesContent } = map; + if (sourcesContent == null) + return null; + let index = sources.indexOf(source); + if (index === -1) + index = resolvedSources.indexOf(source); + return index === -1 ? null : sourcesContent[index]; + }; + presortedDecodedMap = (map, mapUrl) => { + const tracer = new TraceMap(clone(map, []), mapUrl); + tracer._decoded = map.mappings; + return tracer; + }; + decodedMap = (map) => { + return clone(map, decodedMappings(map)); + }; + encodedMap = (map) => { + return clone(map, encodedMappings(map)); + }; + function generatedPosition(map, source, line, column, bias, all) { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) + sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) + return all ? [] : GMapping(null, null); + const generated = (map._bySources || (map._bySources = buildBySources(decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState))))); + const segments = generated[sourceIndex][line]; + if (segments == null) + return all ? [] : GMapping(null, null); + const memo = map._bySourceMemos[sourceIndex]; + if (all) + return sliceGeneratedPositions(segments, memo, line, column, bias); + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) + return GMapping(null, null); + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); + } +})(); +function clone(map, mappings) { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + }; +} +function OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function GMapping(line, column) { + return { line, column }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return -1; + return index; +} +function sliceGeneratedPositions(segments, memo, line, column, bias) { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in + // insertion order) segment that matched. Even if we did respect the bias when tracing, we would + // still need to call `lowerBound()` to find the first segment, which is slower than just looking + // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the + // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to + // match LEAST_UPPER_BOUND. + if (!found && bias === LEAST_UPPER_BOUND) + min++; + if (min === -1 || min === segments.length) + return []; + // We may have found the segment that started at an earlier column. If this is the case, then we + // need to slice all generated segments that match _that_ column, because all such segments span + // to our desired column. + const matchedColumn = found ? column : segments[min][COLUMN]; + // The binary search is not guaranteed to find the lower bound when a match wasn't found. + if (!found) + min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; +} + +export { AnyMap, GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap, allGeneratedPositionsFor, decodedMap, decodedMappings, eachMapping, encodedMap, encodedMappings, generatedPositionFor, originalPositionFor, presortedDecodedMap, sourceContentFor, traceSegment }; +//# sourceMappingURL=trace-mapping.mjs.map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map new file mode 100644 index 0000000..4d40aa1 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.mjs","sources":["../src/resolve.ts","../src/strip-filename.ts","../src/sourcemap-segment.ts","../src/sort.ts","../src/binary-search.ts","../src/by-source.ts","../src/any-map.ts","../src/trace-mapping.ts"],"sourcesContent":["import resolveUri from '@jridgewell/resolve-uri';\n\nexport default function resolve(input: string, base: string | undefined): string {\n // The base is always treated as a directory, if it's not empty.\n // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327\n // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401\n if (base && !base.endsWith('/')) base += '/';\n\n return resolveUri(input, base);\n}\n","/**\n * Removes everything after the last \"/\", but leaves the slash.\n */\nexport default function stripFilename(path: string | undefined | null): string {\n if (!path) return '';\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n","type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\ntype GeneratedLine = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n\nexport const REV_GENERATED_LINE = 1;\nexport const REV_GENERATED_COLUMN = 2;\n","import { COLUMN } from './sourcemap-segment';\n\nimport type { SourceMapSegment } from './sourcemap-segment';\n\nexport default function maybeSort(\n mappings: SourceMapSegment[][],\n owned: boolean,\n): SourceMapSegment[][] {\n const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);\n if (unsortedIndex === mappings.length) return mappings;\n\n // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If\n // not, we do not want to modify the consumer's input array.\n if (!owned) mappings = mappings.slice();\n\n for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {\n mappings[i] = sortSegments(mappings[i], owned);\n }\n return mappings;\n}\n\nfunction nextUnsortedSegmentLine(mappings: SourceMapSegment[][], start: number): number {\n for (let i = start; i < mappings.length; i++) {\n if (!isSorted(mappings[i])) return i;\n }\n return mappings.length;\n}\n\nfunction isSorted(line: SourceMapSegment[]): boolean {\n for (let j = 1; j < line.length; j++) {\n if (line[j][COLUMN] < line[j - 1][COLUMN]) {\n return false;\n }\n }\n return true;\n}\n\nfunction sortSegments(line: SourceMapSegment[], owned: boolean): SourceMapSegment[] {\n if (!owned) line = line.slice();\n return line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[COLUMN] - b[COLUMN];\n}\n","import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport { COLUMN } from './sourcemap-segment';\n\nexport type MemoState = {\n lastKey: number;\n lastNeedle: number;\n lastIndex: number;\n};\n\nexport let found = false;\n\n/**\n * A binary search implementation that returns the index if a match is found.\n * If no match is found, then the left-index (the index associated with the item that comes just\n * before the desired index) is returned. To maintain proper sort order, a splice would happen at\n * the next index:\n *\n * ```js\n * const array = [1, 3];\n * const needle = 2;\n * const index = binarySearch(array, needle, (item, needle) => item - needle);\n *\n * assert.equal(index, 0);\n * array.splice(index + 1, 0, needle);\n * assert.deepEqual(array, [1, 2, 3]);\n * ```\n */\nexport function binarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n low: number,\n high: number,\n): number {\n while (low <= high) {\n const mid = low + ((high - low) >> 1);\n const cmp = haystack[mid][COLUMN] - needle;\n\n if (cmp === 0) {\n found = true;\n return mid;\n }\n\n if (cmp < 0) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n found = false;\n return low - 1;\n}\n\nexport function upperBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index + 1; i < haystack.length; index = i++) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function lowerBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index - 1; i >= 0; index = i--) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function memoizedState(): MemoState {\n return {\n lastKey: -1,\n lastNeedle: -1,\n lastIndex: -1,\n };\n}\n\n/**\n * This overly complicated beast is just to record the last tested line/column and the resulting\n * index, allowing us to skip a few tests if mappings are monotonically increasing.\n */\nexport function memoizedBinarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n state: MemoState,\n key: number,\n): number {\n const { lastKey, lastNeedle, lastIndex } = state;\n\n let low = 0;\n let high = haystack.length - 1;\n if (key === lastKey) {\n if (needle === lastNeedle) {\n found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;\n return lastIndex;\n }\n\n if (needle >= lastNeedle) {\n // lastIndex may be -1 if the previous needle was not found.\n low = lastIndex === -1 ? 0 : lastIndex;\n } else {\n high = lastIndex;\n }\n }\n state.lastKey = key;\n state.lastNeedle = needle;\n\n return (state.lastIndex = binarySearch(haystack, needle, low, high));\n}\n","import { COLUMN, SOURCES_INDEX, SOURCE_LINE, SOURCE_COLUMN } from './sourcemap-segment';\nimport { memoizedBinarySearch, upperBound } from './binary-search';\n\nimport type { ReverseSegment, SourceMapSegment } from './sourcemap-segment';\nimport type { MemoState } from './binary-search';\n\nexport type Source = {\n __proto__: null;\n [line: number]: Exclude[];\n};\n\n// Rebuilds the original source files, with mappings that are ordered by source line/column instead\n// of generated line/column.\nexport default function buildBySources(\n decoded: readonly SourceMapSegment[][],\n memos: MemoState[],\n): Source[] {\n const sources: Source[] = memos.map(buildNullArray);\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n if (seg.length === 1) continue;\n\n const sourceIndex = seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n const originalSource = sources[sourceIndex];\n const originalLine = (originalSource[sourceLine] ||= []);\n const memo = memos[sourceIndex];\n\n // The binary search either found a match, or it found the left-index just before where the\n // segment should go. Either way, we want to insert after that. And there may be multiple\n // generated segments associated with an original location, so there may need to move several\n // indexes before we find where we need to insert.\n const index = upperBound(\n originalLine,\n sourceColumn,\n memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine),\n );\n\n insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]);\n }\n }\n\n return sources;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\n// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like\n// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations.\n// Numeric properties on objects are magically sorted in ascending order by the engine regardless of\n// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending\n// order when iterating with for-in.\nfunction buildNullArray(): T {\n return { __proto__: null } as T;\n}\n","import { TraceMap, presortedDecodedMap, decodedMappings } from './trace-mapping';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type {\n Section,\n SectionedSourceMap,\n DecodedSourceMap,\n SectionedSourceMapInput,\n Ro,\n} from './types';\nimport type { SourceMapSegment } from './sourcemap-segment';\n\ntype AnyMap = {\n new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n};\n\nexport const AnyMap: AnyMap = function (map, mapUrl) {\n const parsed =\n typeof map === 'string' ? (JSON.parse(map) as Exclude) : map;\n\n if (!('sections' in parsed)) return new TraceMap(parsed, mapUrl);\n\n const mappings: SourceMapSegment[][] = [];\n const sources: string[] = [];\n const sourcesContent: (string | null)[] = [];\n const names: string[] = [];\n\n recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, 0, 0, Infinity, Infinity);\n\n const joined: DecodedSourceMap = {\n version: 3,\n file: parsed.file,\n names,\n sources,\n sourcesContent,\n mappings,\n };\n\n return presortedDecodedMap(joined);\n} as AnyMap;\n\nfunction recurse(\n input: Ro,\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n const { sections } = input;\n for (let i = 0; i < sections.length; i++) {\n const { map, offset } = sections[i];\n\n let sl = stopLine;\n let sc = stopColumn;\n if (i + 1 < sections.length) {\n const nextOffset = sections[i + 1].offset;\n sl = Math.min(stopLine, lineOffset + nextOffset.line);\n\n if (sl === stopLine) {\n sc = Math.min(stopColumn, columnOffset + nextOffset.column);\n } else if (sl < stopLine) {\n sc = columnOffset + nextOffset.column;\n }\n }\n\n addSection(\n map,\n mapUrl,\n mappings,\n sources,\n sourcesContent,\n names,\n lineOffset + offset.line,\n columnOffset + offset.column,\n sl,\n sc,\n );\n }\n}\n\nfunction addSection(\n input: Ro,\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n if ('sections' in input) return recurse(...(arguments as unknown as Parameters));\n\n const map = new TraceMap(input, mapUrl);\n const sourcesOffset = sources.length;\n const namesOffset = names.length;\n const decoded = decodedMappings(map);\n const { resolvedSources, sourcesContent: contents } = map;\n\n append(sources, resolvedSources);\n append(names, map.names);\n if (contents) append(sourcesContent, contents);\n else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null);\n\n for (let i = 0; i < decoded.length; i++) {\n const lineI = lineOffset + i;\n\n // We can only add so many lines before we step into the range that the next section's map\n // controls. When we get to the last line, then we'll start checking the segments to see if\n // they've crossed into the column range. But it may not have any columns that overstep, so we\n // still need to check that we don't overstep lines, too.\n if (lineI > stopLine) return;\n\n // The out line may already exist in mappings (if we're continuing the line started by a\n // previous section). Or, we may have jumped ahead several lines to start this section.\n const out = getLine(mappings, lineI);\n // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the\n // map can be multiple lines), it doesn't.\n const cOffset = i === 0 ? columnOffset : 0;\n\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n const column = cOffset + seg[COLUMN];\n\n // If this segment steps into the column range that the next section's map controls, we need\n // to stop early.\n if (lineI === stopLine && column >= stopColumn) return;\n\n if (seg.length === 1) {\n out.push([column]);\n continue;\n }\n\n const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n out.push(\n seg.length === 4\n ? [column, sourcesIndex, sourceLine, sourceColumn]\n : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]],\n );\n }\n }\n}\n\nfunction append(arr: T[], other: T[]) {\n for (let i = 0; i < other.length; i++) arr.push(other[i]);\n}\n\nfunction getLine(arr: T[][], index: number): T[] {\n for (let i = arr.length; i <= index; i++) arr[i] = [];\n return arr[index];\n}\n","import { encode, decode } from '@jridgewell/sourcemap-codec';\n\nimport resolve from './resolve';\nimport stripFilename from './strip-filename';\nimport maybeSort from './sort';\nimport buildBySources from './by-source';\nimport {\n memoizedState,\n memoizedBinarySearch,\n upperBound,\n lowerBound,\n found as bsFound,\n} from './binary-search';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n REV_GENERATED_LINE,\n REV_GENERATED_COLUMN,\n} from './sourcemap-segment';\n\nimport type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport type {\n SourceMapV3,\n DecodedSourceMap,\n EncodedSourceMap,\n InvalidOriginalMapping,\n OriginalMapping,\n InvalidGeneratedMapping,\n GeneratedMapping,\n SourceMapInput,\n Needle,\n SourceNeedle,\n SourceMap,\n EachMapping,\n Bias,\n} from './types';\nimport type { Source } from './by-source';\nimport type { MemoState } from './binary-search';\n\nexport type { SourceMapSegment } from './sourcemap-segment';\nexport type {\n SourceMapInput,\n SectionedSourceMapInput,\n DecodedSourceMap,\n EncodedSourceMap,\n SectionedSourceMap,\n InvalidOriginalMapping,\n OriginalMapping as Mapping,\n OriginalMapping,\n InvalidGeneratedMapping,\n GeneratedMapping,\n EachMapping,\n} from './types';\n\nconst LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';\nconst COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';\n\nexport const LEAST_UPPER_BOUND = -1;\nexport const GREATEST_LOWER_BOUND = 1;\n\n/**\n * Returns the encoded (VLQ string) form of the SourceMap's mappings field.\n */\nexport let encodedMappings: (map: TraceMap) => EncodedSourceMap['mappings'];\n\n/**\n * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.\n */\nexport let decodedMappings: (map: TraceMap) => Readonly;\n\n/**\n * A low-level API to find the segment associated with a generated line/column (think, from a\n * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.\n */\nexport let traceSegment: (\n map: TraceMap,\n line: number,\n column: number,\n) => Readonly | null;\n\n/**\n * A higher-level API to find the source/line/column associated with a generated line/column\n * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in\n * `source-map` library.\n */\nexport let originalPositionFor: (\n map: TraceMap,\n needle: Needle,\n) => OriginalMapping | InvalidOriginalMapping;\n\n/**\n * Finds the generated line/column position of the provided source/line/column source position.\n */\nexport let generatedPositionFor: (\n map: TraceMap,\n needle: SourceNeedle,\n) => GeneratedMapping | InvalidGeneratedMapping;\n\n/**\n * Finds all generated line/column positions of the provided source/line/column source position.\n */\nexport let allGeneratedPositionsFor: (map: TraceMap, needle: SourceNeedle) => GeneratedMapping[];\n\n/**\n * Iterates each mapping in generated position order.\n */\nexport let eachMapping: (map: TraceMap, cb: (mapping: EachMapping) => void) => void;\n\n/**\n * Retrieves the source content for a particular source, if its found. Returns null if not.\n */\nexport let sourceContentFor: (map: TraceMap, source: string) => string | null;\n\n/**\n * A helper that skips sorting of the input map's mappings array, which can be expensive for larger\n * maps.\n */\nexport let presortedDecodedMap: (map: DecodedSourceMap, mapUrl?: string) => TraceMap;\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let decodedMap: (\n map: TraceMap,\n) => Omit & { mappings: readonly SourceMapSegment[][] };\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let encodedMap: (map: TraceMap) => EncodedSourceMap;\n\nexport { AnyMap } from './any-map';\n\nexport class TraceMap implements SourceMap {\n declare version: SourceMapV3['version'];\n declare file: SourceMapV3['file'];\n declare names: SourceMapV3['names'];\n declare sourceRoot: SourceMapV3['sourceRoot'];\n declare sources: SourceMapV3['sources'];\n declare sourcesContent: SourceMapV3['sourcesContent'];\n\n declare resolvedSources: string[];\n private declare _encoded: string | undefined;\n\n private declare _decoded: SourceMapSegment[][] | undefined;\n private declare _decodedMemo: MemoState;\n\n private declare _bySources: Source[] | undefined;\n private declare _bySourceMemos: MemoState[] | undefined;\n\n constructor(map: SourceMapInput, mapUrl?: string | null) {\n const isString = typeof map === 'string';\n\n if (!isString && (map as unknown as { _decodedMemo: any })._decodedMemo) return map as TraceMap;\n\n const parsed = (isString ? JSON.parse(map) : map) as DecodedSourceMap | EncodedSourceMap;\n\n const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;\n this.version = version;\n this.file = file;\n this.names = names;\n this.sourceRoot = sourceRoot;\n this.sources = sources;\n this.sourcesContent = sourcesContent;\n\n const from = resolve(sourceRoot || '', stripFilename(mapUrl));\n this.resolvedSources = sources.map((s) => resolve(s || '', from));\n\n const { mappings } = parsed;\n if (typeof mappings === 'string') {\n this._encoded = mappings;\n this._decoded = undefined;\n } else {\n this._encoded = undefined;\n this._decoded = maybeSort(mappings, isString);\n }\n\n this._decodedMemo = memoizedState();\n this._bySources = undefined;\n this._bySourceMemos = undefined;\n }\n\n static {\n encodedMappings = (map) => {\n return (map._encoded ??= encode(map._decoded!));\n };\n\n decodedMappings = (map) => {\n return (map._decoded ||= decode(map._encoded!));\n };\n\n traceSegment = (map, line, column) => {\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return null;\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n map._decodedMemo,\n line,\n column,\n GREATEST_LOWER_BOUND,\n );\n\n return index === -1 ? null : segments[index];\n };\n\n originalPositionFor = (map, { line, column, bias }) => {\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return OMapping(null, null, null, null);\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n map._decodedMemo,\n line,\n column,\n bias || GREATEST_LOWER_BOUND,\n );\n\n if (index === -1) return OMapping(null, null, null, null);\n\n const segment = segments[index];\n if (segment.length === 1) return OMapping(null, null, null, null);\n\n const { names, resolvedSources } = map;\n return OMapping(\n resolvedSources[segment[SOURCES_INDEX]],\n segment[SOURCE_LINE] + 1,\n segment[SOURCE_COLUMN],\n segment.length === 5 ? names[segment[NAMES_INDEX]] : null,\n );\n };\n\n allGeneratedPositionsFor = (map, { source, line, column, bias }) => {\n // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit.\n return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true);\n };\n\n generatedPositionFor = (map, { source, line, column, bias }) => {\n return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);\n };\n\n eachMapping = (map, cb) => {\n const decoded = decodedMappings(map);\n const { names, resolvedSources } = map;\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generatedLine = i + 1;\n const generatedColumn = seg[0];\n let source = null;\n let originalLine = null;\n let originalColumn = null;\n let name = null;\n if (seg.length !== 1) {\n source = resolvedSources[seg[1]];\n originalLine = seg[2] + 1;\n originalColumn = seg[3];\n }\n if (seg.length === 5) name = names[seg[4]];\n\n cb({\n generatedLine,\n generatedColumn,\n source,\n originalLine,\n originalColumn,\n name,\n } as EachMapping);\n }\n }\n };\n\n sourceContentFor = (map, source) => {\n const { sources, resolvedSources, sourcesContent } = map;\n if (sourcesContent == null) return null;\n\n let index = sources.indexOf(source);\n if (index === -1) index = resolvedSources.indexOf(source);\n\n return index === -1 ? null : sourcesContent[index];\n };\n\n presortedDecodedMap = (map, mapUrl) => {\n const tracer = new TraceMap(clone(map, []), mapUrl);\n tracer._decoded = map.mappings;\n return tracer;\n };\n\n decodedMap = (map) => {\n return clone(map, decodedMappings(map));\n };\n\n encodedMap = (map) => {\n return clone(map, encodedMappings(map));\n };\n\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: false,\n ): GeneratedMapping | InvalidGeneratedMapping;\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: true,\n ): GeneratedMapping[];\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: boolean,\n ): GeneratedMapping | InvalidGeneratedMapping | GeneratedMapping[] {\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const { sources, resolvedSources } = map;\n let sourceIndex = sources.indexOf(source);\n if (sourceIndex === -1) sourceIndex = resolvedSources.indexOf(source);\n if (sourceIndex === -1) return all ? [] : GMapping(null, null);\n\n const generated = (map._bySources ||= buildBySources(\n decodedMappings(map),\n (map._bySourceMemos = sources.map(memoizedState)),\n ));\n\n const segments = generated[sourceIndex][line];\n if (segments == null) return all ? [] : GMapping(null, null);\n\n const memo = map._bySourceMemos![sourceIndex];\n\n if (all) return sliceGeneratedPositions(segments, memo, line, column, bias);\n\n const index = traceSegmentInternal(segments, memo, line, column, bias);\n if (index === -1) return GMapping(null, null);\n\n const segment = segments[index];\n return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);\n }\n }\n}\n\nfunction clone(\n map: TraceMap | DecodedSourceMap | EncodedSourceMap,\n mappings: T,\n): T extends string ? EncodedSourceMap : DecodedSourceMap {\n return {\n version: map.version,\n file: map.file,\n names: map.names,\n sourceRoot: map.sourceRoot,\n sources: map.sources,\n sourcesContent: map.sourcesContent,\n mappings,\n } as any;\n}\n\nfunction OMapping(source: null, line: null, column: null, name: null): InvalidOriginalMapping;\nfunction OMapping(\n source: string,\n line: number,\n column: number,\n name: string | null,\n): OriginalMapping;\nfunction OMapping(\n source: string | null,\n line: number | null,\n column: number | null,\n name: string | null,\n): OriginalMapping | InvalidOriginalMapping {\n return { source, line, column, name } as any;\n}\n\nfunction GMapping(line: null, column: null): InvalidGeneratedMapping;\nfunction GMapping(line: number, column: number): GeneratedMapping;\nfunction GMapping(\n line: number | null,\n column: number | null,\n): GeneratedMapping | InvalidGeneratedMapping {\n return { line, column } as any;\n}\n\nfunction traceSegmentInternal(\n segments: SourceMapSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: SourceMapSegment[] | ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number {\n let index = memoizedBinarySearch(segments, column, memo, line);\n if (bsFound) {\n index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);\n } else if (bias === LEAST_UPPER_BOUND) index++;\n\n if (index === -1 || index === segments.length) return -1;\n return index;\n}\n\nfunction sliceGeneratedPositions(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): GeneratedMapping[] {\n let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);\n\n // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in\n // insertion order) segment that matched. Even if we did respect the bias when tracing, we would\n // still need to call `lowerBound()` to find the first segment, which is slower than just looking\n // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the\n // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to\n // match LEAST_UPPER_BOUND.\n if (!bsFound && bias === LEAST_UPPER_BOUND) min++;\n\n if (min === -1 || min === segments.length) return [];\n\n // We may have found the segment that started at an earlier column. If this is the case, then we\n // need to slice all generated segments that match _that_ column, because all such segments span\n // to our desired column.\n const matchedColumn = bsFound ? column : segments[min][COLUMN];\n\n // The binary search is not guaranteed to find the lower bound when a match wasn't found.\n if (!bsFound) min = lowerBound(segments, matchedColumn, min);\n const max = upperBound(segments, matchedColumn, min);\n\n const result = [];\n for (; min <= max; min++) {\n const segment = segments[min];\n result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));\n }\n return result;\n}\n"],"names":["bsFound"],"mappings":";;;AAEc,SAAU,OAAO,CAAC,KAAa,EAAE,IAAwB,EAAA;;;;IAIrE,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,IAAI,IAAI,GAAG,CAAC;AAE7C,IAAA,OAAO,UAAU,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACjC;;ACTA;;AAEG;AACqB,SAAA,aAAa,CAAC,IAA+B,EAAA;AACnE,IAAA,IAAI,CAAC,IAAI;AAAE,QAAA,OAAO,EAAE,CAAC;IACrB,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;IACpC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;AAClC;;ACQO,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,WAAW,GAAG,CAAC,CAAC;AAEtB,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,MAAM,oBAAoB,GAAG,CAAC;;AClBvB,SAAU,SAAS,CAC/B,QAA8B,EAC9B,KAAc,EAAA;IAEd,MAAM,aAAa,GAAG,uBAAuB,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;AAC3D,IAAA,IAAI,aAAa,KAAK,QAAQ,CAAC,MAAM;AAAE,QAAA,OAAO,QAAQ,CAAC;;;AAIvD,IAAA,IAAI,CAAC,KAAK;AAAE,QAAA,QAAQ,GAAG,QAAQ,CAAC,KAAK,EAAE,CAAC;IAExC,KAAK,IAAI,CAAC,GAAG,aAAa,EAAE,CAAC,GAAG,QAAQ,CAAC,M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CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC;AACvF,KAAA;AACD,IAAA,OAAO,MAAM,CAAC;AAChB;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js new file mode 100644 index 0000000..a3251f1 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js @@ -0,0 +1,566 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@jridgewell/sourcemap-codec'), require('@jridgewell/resolve-uri')) : + typeof define === 'function' && define.amd ? define(['exports', '@jridgewell/sourcemap-codec', '@jridgewell/resolve-uri'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.traceMapping = {}, global.sourcemapCodec, global.resolveURI)); +})(this, (function (exports, sourcemapCodec, resolveUri) { 'use strict'; + + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + + var resolveUri__default = /*#__PURE__*/_interopDefaultLegacy(resolveUri); + + function resolve(input, base) { + // The base is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + if (base && !base.endsWith('/')) + base += '/'; + return resolveUri__default["default"](input, base); + } + + /** + * Removes everything after the last "/", but leaves the slash. + */ + function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + + const COLUMN = 0; + const SOURCES_INDEX = 1; + const SOURCE_LINE = 2; + const SOURCE_COLUMN = 3; + const NAMES_INDEX = 4; + const REV_GENERATED_LINE = 1; + const REV_GENERATED_COLUMN = 2; + + function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; + } + function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; + } + function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; + } + function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); + } + function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; + } + + let found = false; + /** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ + function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; + } + function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; + } + function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; + } + function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; + } + /** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ + function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); + } + + // Rebuilds the original source files, with mappings that are ordered by source line/column instead + // of generated line/column. + function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) + continue; + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = [])); + const memo = memos[sourceIndex]; + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; + } + function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; + } + // Null arrays allow us to use ordered index keys without actually allocating contiguous memory like + // a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. + // Numeric properties on objects are magically sorted in ascending order by the engine regardless of + // the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending + // order when iterating with for-in. + function buildNullArray() { + return { __proto__: null }; + } + + const AnyMap = function (map, mapUrl) { + const parsed = typeof map === 'string' ? JSON.parse(map) : map; + if (!('sections' in parsed)) + return new TraceMap(parsed, mapUrl); + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, 0, 0, Infinity, Infinity); + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + }; + return exports.presortedDecodedMap(joined); + }; + function recurse(input, mapUrl, mappings, sources, sourcesContent, names, lineOffset, columnOffset, stopLine, stopColumn) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } + else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + addSection(map, mapUrl, mappings, sources, sourcesContent, names, lineOffset + offset.line, columnOffset + offset.column, sl, sc); + } + } + function addSection(input, mapUrl, mappings, sources, sourcesContent, names, lineOffset, columnOffset, stopLine, stopColumn) { + if ('sections' in input) + return recurse(...arguments); + const map = new TraceMap(input, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = exports.decodedMappings(map); + const { resolvedSources, sourcesContent: contents } = map; + append(sources, resolvedSources); + append(names, map.names); + if (contents) + append(sourcesContent, contents); + else + for (let i = 0; i < resolvedSources.length; i++) + sourcesContent.push(null); + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. But it may not have any columns that overstep, so we + // still need to check that we don't overstep lines, too. + if (lineI > stopLine) + return; + // The out line may already exist in mappings (if we're continuing the line started by a + // previous section). Or, we may have jumped ahead several lines to start this section. + const out = getLine(mappings, lineI); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (lineI === stopLine && column >= stopColumn) + return; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push(seg.length === 4 + ? [column, sourcesIndex, sourceLine, sourceColumn] + : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); + } + } + } + function append(arr, other) { + for (let i = 0; i < other.length; i++) + arr.push(other[i]); + } + function getLine(arr, index) { + for (let i = arr.length; i <= index; i++) + arr[i] = []; + return arr[index]; + } + + const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; + const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; + const LEAST_UPPER_BOUND = -1; + const GREATEST_LOWER_BOUND = 1; + /** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ + exports.encodedMappings = void 0; + /** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ + exports.decodedMappings = void 0; + /** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ + exports.traceSegment = void 0; + /** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ + exports.originalPositionFor = void 0; + /** + * Finds the generated line/column position of the provided source/line/column source position. + */ + exports.generatedPositionFor = void 0; + /** + * Finds all generated line/column positions of the provided source/line/column source position. + */ + exports.allGeneratedPositionsFor = void 0; + /** + * Iterates each mapping in generated position order. + */ + exports.eachMapping = void 0; + /** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ + exports.sourceContentFor = void 0; + /** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ + exports.presortedDecodedMap = void 0; + /** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.decodedMap = void 0; + /** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.encodedMap = void 0; + class TraceMap { + constructor(map, mapUrl) { + const isString = typeof map === 'string'; + if (!isString && map._decodedMemo) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } + } + (() => { + exports.encodedMappings = (map) => { + var _a; + return ((_a = map._encoded) !== null && _a !== void 0 ? _a : (map._encoded = sourcemapCodec.encode(map._decoded))); + }; + exports.decodedMappings = (map) => { + return (map._decoded || (map._decoded = sourcemapCodec.decode(map._encoded))); + }; + exports.traceSegment = (map, line, column) => { + const decoded = exports.decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + const segments = decoded[line]; + const index = traceSegmentInternal(segments, map._decodedMemo, line, column, GREATEST_LOWER_BOUND); + return index === -1 ? null : segments[index]; + }; + exports.originalPositionFor = (map, { line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = exports.decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (index === -1) + return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) + return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null); + }; + exports.allGeneratedPositionsFor = (map, { source, line, column, bias }) => { + // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit. + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); + }; + exports.generatedPositionFor = (map, { source, line, column, bias }) => { + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); + }; + exports.eachMapping = (map, cb) => { + const decoded = exports.decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) + name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + }); + } + } + }; + exports.sourceContentFor = (map, source) => { + const { sources, resolvedSources, sourcesContent } = map; + if (sourcesContent == null) + return null; + let index = sources.indexOf(source); + if (index === -1) + index = resolvedSources.indexOf(source); + return index === -1 ? null : sourcesContent[index]; + }; + exports.presortedDecodedMap = (map, mapUrl) => { + const tracer = new TraceMap(clone(map, []), mapUrl); + tracer._decoded = map.mappings; + return tracer; + }; + exports.decodedMap = (map) => { + return clone(map, exports.decodedMappings(map)); + }; + exports.encodedMap = (map) => { + return clone(map, exports.encodedMappings(map)); + }; + function generatedPosition(map, source, line, column, bias, all) { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) + sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) + return all ? [] : GMapping(null, null); + const generated = (map._bySources || (map._bySources = buildBySources(exports.decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState))))); + const segments = generated[sourceIndex][line]; + if (segments == null) + return all ? [] : GMapping(null, null); + const memo = map._bySourceMemos[sourceIndex]; + if (all) + return sliceGeneratedPositions(segments, memo, line, column, bias); + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) + return GMapping(null, null); + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); + } + })(); + function clone(map, mappings) { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + }; + } + function OMapping(source, line, column, name) { + return { source, line, column, name }; + } + function GMapping(line, column) { + return { line, column }; + } + function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return -1; + return index; + } + function sliceGeneratedPositions(segments, memo, line, column, bias) { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in + // insertion order) segment that matched. Even if we did respect the bias when tracing, we would + // still need to call `lowerBound()` to find the first segment, which is slower than just looking + // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the + // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to + // match LEAST_UPPER_BOUND. + if (!found && bias === LEAST_UPPER_BOUND) + min++; + if (min === -1 || min === segments.length) + return []; + // We may have found the segment that started at an earlier column. If this is the case, then we + // need to slice all generated segments that match _that_ column, because all such segments span + // to our desired column. + const matchedColumn = found ? column : segments[min][COLUMN]; + // The binary search is not guaranteed to find the lower bound when a match wasn't found. + if (!found) + min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; + } + + exports.AnyMap = AnyMap; + exports.GREATEST_LOWER_BOUND = GREATEST_LOWER_BOUND; + exports.LEAST_UPPER_BOUND = LEAST_UPPER_BOUND; + exports.TraceMap = TraceMap; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=trace-mapping.umd.js.map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map new file mode 100644 index 0000000..fee1219 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.umd.js","sources":["../src/resolve.ts","../src/strip-filename.ts","../src/sourcemap-segment.ts","../src/sort.ts","../src/binary-search.ts","../src/by-source.ts","../src/any-map.ts","../src/trace-mapping.ts"],"sourcesContent":["import resolveUri from '@jridgewell/resolve-uri';\n\nexport default function resolve(input: string, base: string | undefined): string {\n // The base is always treated as a directory, if it's not empty.\n // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327\n // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401\n if (base && !base.endsWith('/')) base += '/';\n\n return resolveUri(input, base);\n}\n","/**\n * Removes everything after the last \"/\", but leaves the slash.\n */\nexport default function stripFilename(path: string | undefined | null): string {\n if (!path) return '';\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n","type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\ntype GeneratedLine = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n\nexport const REV_GENERATED_LINE = 1;\nexport const REV_GENERATED_COLUMN = 2;\n","import { COLUMN } from './sourcemap-segment';\n\nimport type { SourceMapSegment } from './sourcemap-segment';\n\nexport default function maybeSort(\n mappings: SourceMapSegment[][],\n owned: boolean,\n): SourceMapSegment[][] {\n const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);\n if (unsortedIndex === mappings.length) return mappings;\n\n // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If\n // not, we do not want to modify the consumer's input array.\n if (!owned) mappings = mappings.slice();\n\n for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {\n mappings[i] = sortSegments(mappings[i], owned);\n }\n return mappings;\n}\n\nfunction nextUnsortedSegmentLine(mappings: SourceMapSegment[][], start: number): number {\n for (let i = start; i < mappings.length; i++) {\n if (!isSorted(mappings[i])) return i;\n }\n return mappings.length;\n}\n\nfunction isSorted(line: SourceMapSegment[]): boolean {\n for (let j = 1; j < line.length; j++) {\n if (line[j][COLUMN] < line[j - 1][COLUMN]) {\n return false;\n }\n }\n return true;\n}\n\nfunction sortSegments(line: SourceMapSegment[], owned: boolean): SourceMapSegment[] {\n if (!owned) line = line.slice();\n return line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[COLUMN] - b[COLUMN];\n}\n","import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport { COLUMN } from './sourcemap-segment';\n\nexport type MemoState = {\n lastKey: number;\n lastNeedle: number;\n lastIndex: number;\n};\n\nexport let found = false;\n\n/**\n * A binary search implementation that returns the index if a match is found.\n * If no match is found, then the left-index (the index associated with the item that comes just\n * before the desired index) is returned. To maintain proper sort order, a splice would happen at\n * the next index:\n *\n * ```js\n * const array = [1, 3];\n * const needle = 2;\n * const index = binarySearch(array, needle, (item, needle) => item - needle);\n *\n * assert.equal(index, 0);\n * array.splice(index + 1, 0, needle);\n * assert.deepEqual(array, [1, 2, 3]);\n * ```\n */\nexport function binarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n low: number,\n high: number,\n): number {\n while (low <= high) {\n const mid = low + ((high - low) >> 1);\n const cmp = haystack[mid][COLUMN] - needle;\n\n if (cmp === 0) {\n found = true;\n return mid;\n }\n\n if (cmp < 0) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n found = false;\n return low - 1;\n}\n\nexport function upperBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index + 1; i < haystack.length; index = i++) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function lowerBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index - 1; i >= 0; index = i--) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function memoizedState(): MemoState {\n return {\n lastKey: -1,\n lastNeedle: -1,\n lastIndex: -1,\n };\n}\n\n/**\n * This overly complicated beast is just to record the last tested line/column and the resulting\n * index, allowing us to skip a few tests if mappings are monotonically increasing.\n */\nexport function memoizedBinarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n state: MemoState,\n key: number,\n): number {\n const { lastKey, lastNeedle, lastIndex } = state;\n\n let low = 0;\n let high = haystack.length - 1;\n if (key === lastKey) {\n if (needle === lastNeedle) {\n found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;\n return lastIndex;\n }\n\n if (needle >= lastNeedle) {\n // lastIndex may be -1 if the previous needle was not found.\n low = lastIndex === -1 ? 0 : lastIndex;\n } else {\n high = lastIndex;\n }\n }\n state.lastKey = key;\n state.lastNeedle = needle;\n\n return (state.lastIndex = binarySearch(haystack, needle, low, high));\n}\n","import { COLUMN, SOURCES_INDEX, SOURCE_LINE, SOURCE_COLUMN } from './sourcemap-segment';\nimport { memoizedBinarySearch, upperBound } from './binary-search';\n\nimport type { ReverseSegment, SourceMapSegment } from './sourcemap-segment';\nimport type { MemoState } from './binary-search';\n\nexport type Source = {\n __proto__: null;\n [line: number]: Exclude[];\n};\n\n// Rebuilds the original source files, with mappings that are ordered by source line/column instead\n// of generated line/column.\nexport default function buildBySources(\n decoded: readonly SourceMapSegment[][],\n memos: MemoState[],\n): Source[] {\n const sources: Source[] = memos.map(buildNullArray);\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n if (seg.length === 1) continue;\n\n const sourceIndex = seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n const originalSource = sources[sourceIndex];\n const originalLine = (originalSource[sourceLine] ||= []);\n const memo = memos[sourceIndex];\n\n // The binary search either found a match, or it found the left-index just before where the\n // segment should go. Either way, we want to insert after that. And there may be multiple\n // generated segments associated with an original location, so there may need to move several\n // indexes before we find where we need to insert.\n const index = upperBound(\n originalLine,\n sourceColumn,\n memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine),\n );\n\n insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]);\n }\n }\n\n return sources;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\n// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like\n// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations.\n// Numeric properties on objects are magically sorted in ascending order by the engine regardless of\n// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending\n// order when iterating with for-in.\nfunction buildNullArray(): T {\n return { __proto__: null } as T;\n}\n","import { TraceMap, presortedDecodedMap, decodedMappings } from './trace-mapping';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type {\n Section,\n SectionedSourceMap,\n DecodedSourceMap,\n SectionedSourceMapInput,\n Ro,\n} from './types';\nimport type { SourceMapSegment } from './sourcemap-segment';\n\ntype AnyMap = {\n new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n};\n\nexport const AnyMap: AnyMap = function (map, mapUrl) {\n const parsed =\n typeof map === 'string' ? (JSON.parse(map) as Exclude) : map;\n\n if (!('sections' in parsed)) return new TraceMap(parsed, mapUrl);\n\n const mappings: SourceMapSegment[][] = [];\n const sources: string[] = [];\n const sourcesContent: (string | null)[] = [];\n const names: string[] = [];\n\n recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, 0, 0, Infinity, Infinity);\n\n const joined: DecodedSourceMap = {\n version: 3,\n file: parsed.file,\n names,\n sources,\n sourcesContent,\n mappings,\n };\n\n return presortedDecodedMap(joined);\n} as AnyMap;\n\nfunction recurse(\n input: Ro,\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n const { sections } = input;\n for (let i = 0; i < sections.length; i++) {\n const { map, offset } = sections[i];\n\n let sl = stopLine;\n let sc = stopColumn;\n if (i + 1 < sections.length) {\n const nextOffset = sections[i + 1].offset;\n sl = Math.min(stopLine, lineOffset + nextOffset.line);\n\n if (sl === stopLine) {\n sc = Math.min(stopColumn, columnOffset + nextOffset.column);\n } else if (sl < stopLine) {\n sc = columnOffset + nextOffset.column;\n }\n }\n\n addSection(\n map,\n mapUrl,\n mappings,\n sources,\n sourcesContent,\n names,\n lineOffset + offset.line,\n columnOffset + offset.column,\n sl,\n sc,\n );\n }\n}\n\nfunction addSection(\n input: Ro,\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n if ('sections' in input) return recurse(...(arguments as unknown as Parameters));\n\n const map = new TraceMap(input, mapUrl);\n const sourcesOffset = sources.length;\n const namesOffset = names.length;\n const decoded = decodedMappings(map);\n const { resolvedSources, sourcesContent: contents } = map;\n\n append(sources, resolvedSources);\n append(names, map.names);\n if (contents) append(sourcesContent, contents);\n else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null);\n\n for (let i = 0; i < decoded.length; i++) {\n const lineI = lineOffset + i;\n\n // We can only add so many lines before we step into the range that the next section's map\n // controls. When we get to the last line, then we'll start checking the segments to see if\n // they've crossed into the column range. But it may not have any columns that overstep, so we\n // still need to check that we don't overstep lines, too.\n if (lineI > stopLine) return;\n\n // The out line may already exist in mappings (if we're continuing the line started by a\n // previous section). Or, we may have jumped ahead several lines to start this section.\n const out = getLine(mappings, lineI);\n // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the\n // map can be multiple lines), it doesn't.\n const cOffset = i === 0 ? columnOffset : 0;\n\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n const column = cOffset + seg[COLUMN];\n\n // If this segment steps into the column range that the next section's map controls, we need\n // to stop early.\n if (lineI === stopLine && column >= stopColumn) return;\n\n if (seg.length === 1) {\n out.push([column]);\n continue;\n }\n\n const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n out.push(\n seg.length === 4\n ? [column, sourcesIndex, sourceLine, sourceColumn]\n : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]],\n );\n }\n }\n}\n\nfunction append(arr: T[], other: T[]) {\n for (let i = 0; i < other.length; i++) arr.push(other[i]);\n}\n\nfunction getLine(arr: T[][], index: number): T[] {\n for (let i = arr.length; i <= index; i++) arr[i] = [];\n return arr[index];\n}\n","import { encode, decode } from '@jridgewell/sourcemap-codec';\n\nimport resolve from './resolve';\nimport stripFilename from './strip-filename';\nimport maybeSort from './sort';\nimport buildBySources from './by-source';\nimport {\n memoizedState,\n memoizedBinarySearch,\n upperBound,\n lowerBound,\n found as bsFound,\n} from './binary-search';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n REV_GENERATED_LINE,\n REV_GENERATED_COLUMN,\n} from './sourcemap-segment';\n\nimport type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport type {\n SourceMapV3,\n DecodedSourceMap,\n EncodedSourceMap,\n InvalidOriginalMapping,\n OriginalMapping,\n InvalidGeneratedMapping,\n GeneratedMapping,\n SourceMapInput,\n Needle,\n SourceNeedle,\n SourceMap,\n EachMapping,\n Bias,\n} from './types';\nimport type { Source } from './by-source';\nimport type { MemoState } from './binary-search';\n\nexport type { SourceMapSegment } from './sourcemap-segment';\nexport type {\n SourceMapInput,\n SectionedSourceMapInput,\n DecodedSourceMap,\n EncodedSourceMap,\n SectionedSourceMap,\n InvalidOriginalMapping,\n OriginalMapping as Mapping,\n OriginalMapping,\n InvalidGeneratedMapping,\n GeneratedMapping,\n EachMapping,\n} from './types';\n\nconst LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';\nconst COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';\n\nexport const LEAST_UPPER_BOUND = -1;\nexport const GREATEST_LOWER_BOUND = 1;\n\n/**\n * Returns the encoded (VLQ string) form of the SourceMap's mappings field.\n */\nexport let encodedMappings: (map: TraceMap) => EncodedSourceMap['mappings'];\n\n/**\n * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.\n */\nexport let decodedMappings: (map: TraceMap) => Readonly;\n\n/**\n * A low-level API to find the segment associated with a generated line/column (think, from a\n * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.\n */\nexport let traceSegment: (\n map: TraceMap,\n line: number,\n column: number,\n) => Readonly | null;\n\n/**\n * A higher-level API to find the source/line/column associated with a generated line/column\n * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in\n * `source-map` library.\n */\nexport let originalPositionFor: (\n map: TraceMap,\n needle: Needle,\n) => OriginalMapping | InvalidOriginalMapping;\n\n/**\n * Finds the generated line/column position of the provided source/line/column source position.\n */\nexport let generatedPositionFor: (\n map: TraceMap,\n needle: SourceNeedle,\n) => GeneratedMapping | InvalidGeneratedMapping;\n\n/**\n * Finds all generated line/column positions of the provided source/line/column source position.\n */\nexport let allGeneratedPositionsFor: (map: TraceMap, needle: SourceNeedle) => GeneratedMapping[];\n\n/**\n * Iterates each mapping in generated position order.\n */\nexport let eachMapping: (map: TraceMap, cb: (mapping: EachMapping) => void) => void;\n\n/**\n * Retrieves the source content for a particular source, if its found. Returns null if not.\n */\nexport let sourceContentFor: (map: TraceMap, source: string) => string | null;\n\n/**\n * A helper that skips sorting of the input map's mappings array, which can be expensive for larger\n * maps.\n */\nexport let presortedDecodedMap: (map: DecodedSourceMap, mapUrl?: string) => TraceMap;\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let decodedMap: (\n map: TraceMap,\n) => Omit & { mappings: readonly SourceMapSegment[][] };\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let encodedMap: (map: TraceMap) => EncodedSourceMap;\n\nexport { AnyMap } from './any-map';\n\nexport class TraceMap implements SourceMap {\n declare version: SourceMapV3['version'];\n declare file: SourceMapV3['file'];\n declare names: SourceMapV3['names'];\n declare sourceRoot: SourceMapV3['sourceRoot'];\n declare sources: SourceMapV3['sources'];\n declare sourcesContent: SourceMapV3['sourcesContent'];\n\n declare resolvedSources: string[];\n private declare _encoded: string | undefined;\n\n private declare _decoded: SourceMapSegment[][] | undefined;\n private declare _decodedMemo: MemoState;\n\n private declare _bySources: Source[] | undefined;\n private declare _bySourceMemos: MemoState[] | undefined;\n\n constructor(map: SourceMapInput, mapUrl?: string | null) {\n const isString = typeof map === 'string';\n\n if (!isString && (map as unknown as { _decodedMemo: any })._decodedMemo) return map as TraceMap;\n\n const parsed = (isString ? JSON.parse(map) : map) as DecodedSourceMap | EncodedSourceMap;\n\n const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;\n this.version = version;\n this.file = file;\n this.names = names;\n this.sourceRoot = sourceRoot;\n this.sources = sources;\n this.sourcesContent = sourcesContent;\n\n const from = resolve(sourceRoot || '', stripFilename(mapUrl));\n this.resolvedSources = sources.map((s) => resolve(s || '', from));\n\n const { mappings } = parsed;\n if (typeof mappings === 'string') {\n this._encoded = mappings;\n this._decoded = undefined;\n } else {\n this._encoded = undefined;\n this._decoded = maybeSort(mappings, isString);\n }\n\n this._decodedMemo = memoizedState();\n this._bySources = undefined;\n this._bySourceMemos = undefined;\n }\n\n static {\n encodedMappings = (map) => {\n return (map._encoded ??= encode(map._decoded!));\n };\n\n decodedMappings = (map) => {\n return (map._decoded ||= decode(map._encoded!));\n };\n\n traceSegment = (map, line, column) => {\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return null;\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n map._decodedMemo,\n line,\n column,\n GREATEST_LOWER_BOUND,\n );\n\n return index === -1 ? null : segments[index];\n };\n\n originalPositionFor = (map, { line, column, bias }) => {\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return OMapping(null, null, null, null);\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n map._decodedMemo,\n line,\n column,\n bias || GREATEST_LOWER_BOUND,\n );\n\n if (index === -1) return OMapping(null, null, null, null);\n\n const segment = segments[index];\n if (segment.length === 1) return OMapping(null, null, null, null);\n\n const { names, resolvedSources } = map;\n return OMapping(\n resolvedSources[segment[SOURCES_INDEX]],\n segment[SOURCE_LINE] + 1,\n segment[SOURCE_COLUMN],\n segment.length === 5 ? names[segment[NAMES_INDEX]] : null,\n );\n };\n\n allGeneratedPositionsFor = (map, { source, line, column, bias }) => {\n // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit.\n return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true);\n };\n\n generatedPositionFor = (map, { source, line, column, bias }) => {\n return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);\n };\n\n eachMapping = (map, cb) => {\n const decoded = decodedMappings(map);\n const { names, resolvedSources } = map;\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generatedLine = i + 1;\n const generatedColumn = seg[0];\n let source = null;\n let originalLine = null;\n let originalColumn = null;\n let name = null;\n if (seg.length !== 1) {\n source = resolvedSources[seg[1]];\n originalLine = seg[2] + 1;\n originalColumn = seg[3];\n }\n if (seg.length === 5) name = names[seg[4]];\n\n cb({\n generatedLine,\n generatedColumn,\n source,\n originalLine,\n originalColumn,\n name,\n } as EachMapping);\n }\n }\n };\n\n sourceContentFor = (map, source) => {\n const { sources, resolvedSources, sourcesContent } = map;\n if (sourcesContent == null) return null;\n\n let index = sources.indexOf(source);\n if (index === -1) index = resolvedSources.indexOf(source);\n\n return index === -1 ? null : sourcesContent[index];\n };\n\n presortedDecodedMap = (map, mapUrl) => {\n const tracer = new TraceMap(clone(map, []), mapUrl);\n tracer._decoded = map.mappings;\n return tracer;\n };\n\n decodedMap = (map) => {\n return clone(map, decodedMappings(map));\n };\n\n encodedMap = (map) => {\n return clone(map, encodedMappings(map));\n };\n\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: false,\n ): GeneratedMapping | InvalidGeneratedMapping;\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: true,\n ): GeneratedMapping[];\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: boolean,\n ): GeneratedMapping | InvalidGeneratedMapping | GeneratedMapping[] {\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const { sources, resolvedSources } = map;\n let sourceIndex = sources.indexOf(source);\n if (sourceIndex === -1) sourceIndex = resolvedSources.indexOf(source);\n if (sourceIndex === -1) return all ? [] : GMapping(null, null);\n\n const generated = (map._bySources ||= buildBySources(\n decodedMappings(map),\n (map._bySourceMemos = sources.map(memoizedState)),\n ));\n\n const segments = generated[sourceIndex][line];\n if (segments == null) return all ? [] : GMapping(null, null);\n\n const memo = map._bySourceMemos![sourceIndex];\n\n if (all) return sliceGeneratedPositions(segments, memo, line, column, bias);\n\n const index = traceSegmentInternal(segments, memo, line, column, bias);\n if (index === -1) return GMapping(null, null);\n\n const segment = segments[index];\n return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);\n }\n }\n}\n\nfunction clone(\n map: TraceMap | DecodedSourceMap | EncodedSourceMap,\n mappings: T,\n): T extends string ? EncodedSourceMap : DecodedSourceMap {\n return {\n version: map.version,\n file: map.file,\n names: map.names,\n sourceRoot: map.sourceRoot,\n sources: map.sources,\n sourcesContent: map.sourcesContent,\n mappings,\n } as any;\n}\n\nfunction OMapping(source: null, line: null, column: null, name: null): InvalidOriginalMapping;\nfunction OMapping(\n source: string,\n line: number,\n column: number,\n name: string | null,\n): OriginalMapping;\nfunction OMapping(\n source: string | null,\n line: number | null,\n column: number | null,\n name: string | null,\n): OriginalMapping | InvalidOriginalMapping {\n return { source, line, column, name } as any;\n}\n\nfunction GMapping(line: null, column: null): InvalidGeneratedMapping;\nfunction GMapping(line: number, column: number): GeneratedMapping;\nfunction GMapping(\n line: number | null,\n column: number | null,\n): GeneratedMapping | InvalidGeneratedMapping {\n return { line, column } as any;\n}\n\nfunction traceSegmentInternal(\n segments: SourceMapSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: SourceMapSegment[] | ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number {\n let index = memoizedBinarySearch(segments, column, memo, line);\n if (bsFound) {\n index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);\n } else if (bias === LEAST_UPPER_BOUND) index++;\n\n if (index === -1 || index === segments.length) return -1;\n return index;\n}\n\nfunction sliceGeneratedPositions(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): GeneratedMapping[] {\n let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);\n\n // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in\n // insertion order) segment that matched. Even if we did respect the bias when tracing, we would\n // still need to call `lowerBound()` to find the first segment, which is slower than just looking\n // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the\n // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to\n // match LEAST_UPPER_BOUND.\n if (!bsFound && bias === LEAST_UPPER_BOUND) min++;\n\n if (min === -1 || min === segments.length) return [];\n\n // We may have found the segment that started at an earlier column. If this is the case, then we\n // need to slice all generated segments that match _that_ column, because all such segments span\n // to our desired column.\n const matchedColumn = bsFound ? column : segments[min][COLUMN];\n\n // The binary search is not guaranteed to find the lower bound when a match wasn't found.\n if (!bsFound) min = lowerBound(segments, matchedColumn, min);\n const max = upperBound(segments, matchedColumn, min);\n\n const result = [];\n for (; min <= max; min++) {\n const segment = segments[min];\n result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));\n }\n return result;\n}\n"],"names":["resolveUri","presortedDecodedMap","decodedMappings","encodedMappings","traceSegment","originalPositionFor","generatedPositionFor","allGeneratedPositionsFor","eachMapping","sourceContentFor","decodedMap","encodedMap","encode","decode","bsFound"],"mappings":";;;;;;;;;;IAEc,SAAU,OAAO,CAAC,KAAa,EAAE,IAAwB,EAAA;;;;QAIrE,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,IAAI,IAAI,GAAG,CAAC;IAE7C,IAAA,OAAOA,8BAAU,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACjC;;ICTA;;IAEG;IACqB,SAAA,aAAa,CAAC,IAA+B,EAAA;IACnE,IAAA,IAAI,CAAC,IAAI;IAAE,QAAA,OAAO,EAAE,CAAC;QACrB,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;QACpC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;IAClC;;ICQO,MAAM,MAAM,GAAG,CAAC,CAAC;IACjB,MAAM,aAAa,GAAG,CAAC,CAAC;IACxB,MAAM,WAAW,GAAG,CAAC,CAAC;IACtB,MAAM,aAAa,GAAG,CAAC,CAAC;IACxB,MAAM,WAAW,GAAG,CAAC,CAAC;IAEtB,MAAM,kBAAkB,GAAG,CAAC,CAAC;IAC7B,MAAM,oBAAoB,GAAG,CAAC;;IClBvB,SAAU,SAAS,CAC/B,QAA8B,EAC9B,KAAc,EAAA;QAEd,MAAM,aAAa,GAAG,uBAAuB,CAAC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AAa,EAAE,GAAG,CAAC,CAAC;QAErD,MAAM,MAAM,GAAG,EAAE,CAAC;IAClB,IAAA,OAAO,GAAG,IAAI,GAAG,EAAE,GAAG,EAAE,EAAE;IACxB,QAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;IAC9B,QAAA,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC;IACvF,KAAA;IACD,IAAA,OAAO,MAAM,CAAC;IAChB;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts new file mode 100644 index 0000000..08bca6b --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts @@ -0,0 +1,8 @@ +import { TraceMap } from './trace-mapping'; +import type { SectionedSourceMapInput } from './types'; +declare type AnyMap = { + new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap; + (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap; +}; +export declare const AnyMap: AnyMap; +export {}; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts new file mode 100644 index 0000000..88820e5 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts @@ -0,0 +1,32 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment'; +export declare type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; +export declare let found: boolean; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export declare function binarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, low: number, high: number): number; +export declare function upperBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function lowerBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function memoizedState(): MemoState; +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export declare function memoizedBinarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, state: MemoState, key: number): number; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts new file mode 100644 index 0000000..8d1e538 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts @@ -0,0 +1,7 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment'; +import type { MemoState } from './binary-search'; +export declare type Source = { + __proto__: null; + [line: number]: Exclude[]; +}; +export default function buildBySources(decoded: readonly SourceMapSegment[][], memos: MemoState[]): Source[]; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts new file mode 100644 index 0000000..cf7d4f8 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts @@ -0,0 +1 @@ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts new file mode 100644 index 0000000..2bfb5dc --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts @@ -0,0 +1,2 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +export default function maybeSort(mappings: SourceMapSegment[][], owned: boolean): SourceMapSegment[][]; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts new file mode 100644 index 0000000..6d70924 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts @@ -0,0 +1,16 @@ +declare type GeneratedColumn = number; +declare type SourcesIndex = number; +declare type SourceLine = number; +declare type SourceColumn = number; +declare type NamesIndex = number; +declare type GeneratedLine = number; +export declare type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export declare type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export declare const REV_GENERATED_LINE = 1; +export declare const REV_GENERATED_COLUMN = 2; +export {}; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts new file mode 100644 index 0000000..bead5c1 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts @@ -0,0 +1,4 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export default function stripFilename(path: string | undefined | null): string; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts new file mode 100644 index 0000000..c125ead --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts @@ -0,0 +1,74 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { SourceMapV3, DecodedSourceMap, EncodedSourceMap, InvalidOriginalMapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, SourceMapInput, Needle, SourceNeedle, SourceMap, EachMapping } from './types'; +export type { SourceMapSegment } from './sourcemap-segment'; +export type { SourceMapInput, SectionedSourceMapInput, DecodedSourceMap, EncodedSourceMap, SectionedSourceMap, InvalidOriginalMapping, OriginalMapping as Mapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, EachMapping, } from './types'; +export declare const LEAST_UPPER_BOUND = -1; +export declare const GREATEST_LOWER_BOUND = 1; +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export declare let encodedMappings: (map: TraceMap) => EncodedSourceMap['mappings']; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export declare let decodedMappings: (map: TraceMap) => Readonly; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export declare let traceSegment: (map: TraceMap, line: number, column: number) => Readonly | null; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export declare let originalPositionFor: (map: TraceMap, needle: Needle) => OriginalMapping | InvalidOriginalMapping; +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +export declare let generatedPositionFor: (map: TraceMap, needle: SourceNeedle) => GeneratedMapping | InvalidGeneratedMapping; +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +export declare let allGeneratedPositionsFor: (map: TraceMap, needle: SourceNeedle) => GeneratedMapping[]; +/** + * Iterates each mapping in generated position order. + */ +export declare let eachMapping: (map: TraceMap, cb: (mapping: EachMapping) => void) => void; +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +export declare let sourceContentFor: (map: TraceMap, source: string) => string | null; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export declare let presortedDecodedMap: (map: DecodedSourceMap, mapUrl?: string) => TraceMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let decodedMap: (map: TraceMap) => Omit & { + mappings: readonly SourceMapSegment[][]; +}; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let encodedMap: (map: TraceMap) => EncodedSourceMap; +export { AnyMap } from './any-map'; +export declare class TraceMap implements SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: string[]; + private _encoded; + private _decoded; + private _decodedMemo; + private _bySources; + private _bySourceMemos; + constructor(map: SourceMapInput, mapUrl?: string | null); +} diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts new file mode 100644 index 0000000..2f4fd45 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts @@ -0,0 +1,92 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap } from './trace-mapping'; +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} +export interface Section { + offset: { + line: number; + column: number; + }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} +export declare type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; +export declare type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; +export declare type GeneratedMapping = { + line: number; + column: number; +}; +export declare type InvalidGeneratedMapping = { + line: null; + column: null; +}; +export declare type Bias = typeof GREATEST_LOWER_BOUND | typeof LEAST_UPPER_BOUND; +export declare type SourceMapInput = string | Ro | Ro | TraceMap; +export declare type SectionedSourceMapInput = SourceMapInput | Ro; +export declare type Needle = { + line: number; + column: number; + bias?: Bias; +}; +export declare type SourceNeedle = { + source: string; + line: number; + column: number; + bias?: Bias; +}; +export declare type EachMapping = { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; +} | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; +}; +export declare abstract class SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: SourceMapV3['sources']; +} +export declare type Ro = T extends Array ? V[] | Readonly | RoArray | Readonly> : T extends object ? T | Readonly | RoObject | Readonly> : T; +declare type RoArray = Ro[]; +declare type RoObject = { + [K in keyof T]: T[K] | Ro; +}; +export {}; diff --git a/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/LICENSE b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/LICENSE new file mode 100644 index 0000000..a331065 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2015 Rich Harris + +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/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/README.md b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/README.md new file mode 100644 index 0000000..2b9e397 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/README.md @@ -0,0 +1,200 @@ +# sourcemap-codec + +Encode/decode the `mappings` property of a [sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). + + +## Why? + +Sourcemaps are difficult to generate and manipulate, because the `mappings` property – the part that actually links the generated code back to the original source – is encoded using an obscure method called [Variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity). On top of that, each segment in the mapping contains offsets rather than absolute indices, which means that you can't look at a segment in isolation – you have to understand the whole sourcemap. + +This package makes the process slightly easier. + + +## Installation + +```bash +npm install sourcemap-codec +``` + + +## Usage + +```js +import { encode, decode } from 'sourcemap-codec'; + +var decoded = decode( ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); + +assert.deepEqual( decoded, [ + // the first line (of the generated code) has no mappings, + // as shown by the starting semi-colon (which separates lines) + [], + + // the second line contains four (comma-separated) segments + [ + // segments are encoded as you'd expect: + // [ generatedCodeColumn, sourceIndex, sourceCodeLine, sourceCodeColumn, nameIndex ] + + // i.e. the first segment begins at column 2, and maps back to the second column + // of the second line (both zero-based) of the 0th source, and uses the 0th + // name in the `map.names` array + [ 2, 0, 2, 2, 0 ], + + // the remaining segments are 4-length rather than 5-length, + // because they don't map a name + [ 4, 0, 2, 4 ], + [ 6, 0, 2, 5 ], + [ 7, 0, 2, 7 ] + ], + + // the final line contains two segments + [ + [ 2, 1, 10, 19 ], + [ 12, 1, 11, 20 ] + ] +]); + +var encoded = encode( decoded ); +assert.equal( encoded, ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map - 45120 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 5479160 bytes +sourcemap-codec 5659336 bytes +source-map-0.6.1 17144440 bytes +source-map-0.8.0 6867424 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 502 ops/sec ±1.03% (90 runs sampled) +decode: sourcemap-codec x 445 ops/sec ±0.97% (92 runs sampled) +decode: source-map-0.6.1 x 36.01 ops/sec ±1.64% (49 runs sampled) +decode: source-map-0.8.0 x 367 ops/sec ±0.04% (95 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 1261620 bytes +sourcemap-codec 9119248 bytes +source-map-0.6.1 8968560 bytes +source-map-0.8.0 8952952 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 738 ops/sec ±0.42% (98 runs sampled) +encode: sourcemap-codec x 238 ops/sec ±0.73% (88 runs sampled) +encode: source-map-0.6.1 x 162 ops/sec ±0.43% (84 runs sampled) +encode: source-map-0.8.0 x 191 ops/sec ±0.34% (90 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +babel.min.js.map - 347793 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 35338184 bytes +sourcemap-codec 35922736 bytes +source-map-0.6.1 62366360 bytes +source-map-0.8.0 44337416 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 40.35 ops/sec ±4.47% (54 runs sampled) +decode: sourcemap-codec x 36.76 ops/sec ±3.67% (51 runs sampled) +decode: source-map-0.6.1 x 4.44 ops/sec ±2.15% (16 runs sampled) +decode: source-map-0.8.0 x 59.35 ops/sec ±0.05% (78 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +@jridgewell/sourcemap-codec 7212604 bytes +sourcemap-codec 21421456 bytes +source-map-0.6.1 25286888 bytes +source-map-0.8.0 25498744 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 112 ops/sec ±0.13% (84 runs sampled) +encode: sourcemap-codec x 30.23 ops/sec ±2.76% (53 runs sampled) +encode: source-map-0.6.1 x 19.43 ops/sec ±3.70% (37 runs sampled) +encode: source-map-0.8.0 x 19.40 ops/sec ±3.26% (37 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +preact.js.map - 1992 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 500272 bytes +sourcemap-codec 516864 bytes +source-map-0.6.1 1596672 bytes +source-map-0.8.0 517272 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 16,137 ops/sec ±0.17% (99 runs sampled) +decode: sourcemap-codec x 12,139 ops/sec ±0.13% (99 runs sampled) +decode: source-map-0.6.1 x 1,264 ops/sec ±0.12% (100 runs sampled) +decode: source-map-0.8.0 x 9,894 ops/sec ±0.08% (101 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 321026 bytes +sourcemap-codec 830832 bytes +source-map-0.6.1 586608 bytes +source-map-0.8.0 586680 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 19,876 ops/sec ±0.78% (95 runs sampled) +encode: sourcemap-codec x 6,983 ops/sec ±0.15% (100 runs sampled) +encode: source-map-0.6.1 x 5,070 ops/sec ±0.12% (102 runs sampled) +encode: source-map-0.8.0 x 5,641 ops/sec ±0.17% (100 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +react.js.map - 5726 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 734848 bytes +sourcemap-codec 954200 bytes +source-map-0.6.1 2276432 bytes +source-map-0.8.0 955488 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 5,723 ops/sec ±0.12% (98 runs sampled) +decode: sourcemap-codec x 4,555 ops/sec ±0.09% (101 runs sampled) +decode: source-map-0.6.1 x 437 ops/sec ±0.11% (93 runs sampled) +decode: source-map-0.8.0 x 3,441 ops/sec ±0.15% (100 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 638672 bytes +sourcemap-codec 1109840 bytes +source-map-0.6.1 1321224 bytes +source-map-0.8.0 1324448 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 6,801 ops/sec ±0.48% (98 runs sampled) +encode: sourcemap-codec x 2,533 ops/sec ±0.13% (101 runs sampled) +encode: source-map-0.6.1 x 2,248 ops/sec ±0.08% (100 runs sampled) +encode: source-map-0.8.0 x 2,303 ops/sec ±0.15% (100 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec +``` + +# License + +MIT diff --git a/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs new file mode 100644 index 0000000..3dff372 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs @@ -0,0 +1,164 @@ +const comma = ','.charCodeAt(0); +const semicolon = ';'.charCodeAt(0); +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const intToChar = new Uint8Array(64); // 64 possible chars. +const charToInt = new Uint8Array(128); // z is 122 in ASCII +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +// Provide a fallback for older environments. +const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; +function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; +} +function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; +} +function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; +} +function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); +} +function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; +} + +export { decode, encode }; +//# sourceMappingURL=sourcemap-codec.mjs.map diff --git a/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map new file mode 100644 index 0000000..36d7249 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.mjs","sources":["../src/sourcemap-codec.ts"],"sourcesContent":[null],"names":[],"mappings":"AAOA,MAAM,KAAK,GAAG,GA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S;YACnC,GAAG,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;SAClD;KACF;IAED,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;AAC/C,CAAC;AAED,SAAS,aAAa,CACpB,GAAe,EACf,GAAW,EACX,KAAuB,EACvB,OAAyB,EACzB,CAAS;IAET,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACxB,IAAI,GAAG,GAAG,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IAC1B,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IAEhB,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;IAC3C,GAAG;QACD,IAAI,OAAO,GAAG,GAAG,GAAG,QAAQ,CAAC;QAC7B,GAAG,MAAM,CAAC,CAAC;QACX,IAAI,GAAG,GAAG,CAAC;YAAE,OAAO,IAAI,QAAQ,CAAC;QACjC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;KACjC,QAAQ,GAAG,GAAG,CAAC,EAAE;IAElB,OAAO,GAAG,CAAC;AACb;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js new file mode 100644 index 0000000..bec92a9 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js @@ -0,0 +1,175 @@ +(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.sourcemapCodec = {})); +})(this, (function (exports) { 'use strict'; + + const comma = ','.charCodeAt(0); + const semicolon = ';'.charCodeAt(0); + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + const intToChar = new Uint8Array(64); // 64 possible chars. + const charToInt = new Uint8Array(128); // z is 122 in ASCII + for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; + } + // Provide a fallback for older environments. + const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; + function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; + } + function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; + } + function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; + } + function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; + } + function sort(line) { + line.sort(sortComparator); + } + function sortComparator(a, b) { + return a[0] - b[0]; + } + function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); + } + function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; + } + + exports.decode = decode; + exports.encode = encode; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=sourcemap-codec.umd.js.map diff --git a/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map new file mode 100644 index 0000000..a7a4628 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.umd.js","sources":["../src/sourcemap-codec.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;;;IAOA,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAChC,MAAM,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IACpC,MAAM,KAAK,GAAG,kEAAkE,CAAC;IACjF,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;IACrC,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;IAEtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACrC,MAAM,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC9B,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACjB,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAClB;IAED;IACA,MAAM,EAAE,GACN,OAAO,WAAW,KAAK,WAAW;0BACd,IAAI,WAAW,EAAE;UACjC,OAAO,MAAM,KAAK,WAAW;cAC7B;gBACE,MAAM,CAAC,GAAe;oBACpB,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,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AG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;SACjC,QAAQ,GAAG,GAAG,CAAC,EAAE;QAElB,OAAO,GAAG,CAAC;IACb;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts new file mode 100644 index 0000000..410d320 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts @@ -0,0 +1,6 @@ +export declare type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export declare type SourceMapLine = SourceMapSegment[]; +export declare type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; diff --git a/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/package.json b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/package.json new file mode 100644 index 0000000..5945072 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/package.json @@ -0,0 +1,75 @@ +{ + "name": "@jridgewell/sourcemap-codec", + "version": "1.4.14", + "description": "Encode/decode sourcemap mappings", + "keywords": [ + "sourcemap", + "vlq" + ], + "main": "dist/sourcemap-codec.umd.js", + "module": "dist/sourcemap-codec.mjs", + "typings": "dist/types/sourcemap-codec.d.ts", + "files": [ + "dist", + "src" + ], + "exports": { + ".": [ + { + "types": "./dist/types/sourcemap-codec.d.ts", + "browser": "./dist/sourcemap-codec.umd.js", + "import": "./dist/sourcemap-codec.mjs", + "require": "./dist/sourcemap-codec.umd.js" + }, + "./dist/sourcemap-codec.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.js", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemap-codec.git" + }, + "author": "Rich Harris", + "license": "MIT", + "devDependencies": { + "@rollup/plugin-typescript": "8.3.0", + "@types/node": "17.0.15", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "benchmark": "2.1.4", + "c8": "7.11.2", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.64.0", + "source-map": "0.6.1", + "source-map-js": "1.0.2", + "sourcemap-codec": "1.4.8", + "typescript": "4.5.4" + } +} diff --git a/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts new file mode 100644 index 0000000..cafd90e --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts @@ -0,0 +1,198 @@ +export type SourceMapSegment = + | [number] + | [number, number, number, number] + | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; + +const comma = ','.charCodeAt(0); +const semicolon = ';'.charCodeAt(0); +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const intToChar = new Uint8Array(64); // 64 possible chars. +const charToInt = new Uint8Array(128); // z is 122 in ASCII + +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} + +// Provide a fallback for older environments. +const td = + typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf: Uint8Array) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf: Uint8Array) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; + +export function decode(mappings: string): SourceMapMappings { + const state: [number, number, number, number, number] = new Int32Array(5) as any; + const decoded: SourceMapMappings = []; + + let index = 0; + do { + const semi = indexOf(mappings, index); + const line: SourceMapLine = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + + for (let i = index; i < semi; i++) { + let seg: SourceMapSegment; + + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) sorted = false; + lastCol = col; + + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } else { + seg = [col, state[1], state[2], state[3]]; + } + } else { + seg = [col]; + } + + line.push(seg); + } + + if (!sorted) sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + + return decoded; +} + +function indexOf(mappings: string, index: number): number { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; +} + +function decodeInteger(mappings: string, pos: number, state: SourceMapSegment, j: number): number { + let value = 0; + let shift = 0; + let integer = 0; + + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + + const shouldNegate = value & 1; + value >>>= 1; + + if (shouldNegate) { + value = -0x80000000 | -value; + } + + state[j] += value; + return pos; +} + +function hasMoreVlq(mappings: string, i: number, length: number): boolean { + if (i >= length) return false; + return mappings.charCodeAt(i) !== comma; +} + +function sort(line: SourceMapSegment[]) { + line.sort(sortComparator); +} + +function sortComparator(a: SourceMapSegment, b: SourceMapSegment): number { + return a[0] - b[0]; +} + +export function encode(decoded: SourceMapMappings): string; +export function encode(decoded: Readonly): string; +export function encode(decoded: Readonly): string { + const state: [number, number, number, number, number] = new Int32Array(5) as any; + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) continue; + + state[0] = 0; + + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) buf[pos++] = comma; + + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + + if (segment.length === 1) continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + + if (segment.length === 4) continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + + return out + td.decode(buf.subarray(0, pos)); +} + +function encodeInteger( + buf: Uint8Array, + pos: number, + state: SourceMapSegment, + segment: SourceMapSegment, + j: number, +): number { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + + return pos; +} diff --git a/node_modules/@jridgewell/trace-mapping/package.json b/node_modules/@jridgewell/trace-mapping/package.json new file mode 100644 index 0000000..9fcc07f --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/package.json @@ -0,0 +1,75 @@ +{ + "name": "@jridgewell/trace-mapping", + "version": "0.3.18", + "description": "Trace the original position through a source map", + "keywords": [ + "source", + "map" + ], + "main": "dist/trace-mapping.umd.js", + "module": "dist/trace-mapping.mjs", + "types": "dist/types/trace-mapping.d.ts", + "files": [ + "dist" + ], + "exports": { + ".": [ + { + "types": "./dist/types/trace-mapping.d.ts", + "browser": "./dist/trace-mapping.umd.js", + "require": "./dist/trace-mapping.umd.js", + "import": "./dist/trace-mapping.mjs" + }, + "./dist/trace-mapping.umd.js" + ], + "./package.json": "./package.json" + }, + "author": "Justin Ridgewell ", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/trace-mapping.git" + }, + "license": "MIT", + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.mjs", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "test": "run-s -n test:lint test:only", + "test:debug": "ava debug", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts' '**/*.md'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "c8 ava", + "test:watch": "ava --watch" + }, + "devDependencies": { + "@rollup/plugin-typescript": "8.5.0", + "@typescript-eslint/eslint-plugin": "5.39.0", + "@typescript-eslint/parser": "5.39.0", + "ava": "4.3.3", + "benchmark": "2.1.4", + "c8": "7.12.0", + "esbuild": "0.15.10", + "eslint": "8.25.0", + "eslint-config-prettier": "8.5.0", + "eslint-plugin-no-only-tests": "3.0.0", + "npm-run-all": "4.1.5", + "prettier": "2.7.1", + "rollup": "2.79.1", + "tsx": "3.10.1", + "typescript": "4.8.4" + }, + "dependencies": { + "@jridgewell/resolve-uri": "3.1.0", + "@jridgewell/sourcemap-codec": "1.4.14" + } +} diff --git a/node_modules/@polka/url/build.js b/node_modules/@polka/url/build.js new file mode 100644 index 0000000..33dfc56 --- /dev/null +++ b/node_modules/@polka/url/build.js @@ -0,0 +1,42 @@ +const qs = require('querystring'); + +/** + * @typedef ParsedURL + * @type {import('.').ParsedURL} + */ + +/** + * @typedef Request + * @property {string} url + * @property {ParsedURL} _parsedUrl + */ + +/** + * @param {Request} req + * @returns {ParsedURL|void} + */ +function parse(req) { + let raw = req.url; + if (raw == null) return; + + let prev = req._parsedUrl; + if (prev && prev.raw === raw) return prev; + + let pathname=raw, search='', query; + + if (raw.length > 1) { + let idx = raw.indexOf('?', 1); + + if (idx !== -1) { + search = raw.substring(idx); + pathname = raw.substring(0, idx); + if (search.length > 1) { + query = qs.parse(search.substring(1)); + } + } + } + + return req._parsedUrl = { pathname, search, query, raw }; +} + +exports.parse = parse; \ No newline at end of file diff --git a/node_modules/@polka/url/build.mjs b/node_modules/@polka/url/build.mjs new file mode 100644 index 0000000..9d5e7b9 --- /dev/null +++ b/node_modules/@polka/url/build.mjs @@ -0,0 +1,40 @@ +import * as qs from 'querystring'; + +/** + * @typedef ParsedURL + * @type {import('.').ParsedURL} + */ + +/** + * @typedef Request + * @property {string} url + * @property {ParsedURL} _parsedUrl + */ + +/** + * @param {Request} req + * @returns {ParsedURL|void} + */ +export function parse(req) { + let raw = req.url; + if (raw == null) return; + + let prev = req._parsedUrl; + if (prev && prev.raw === raw) return prev; + + let pathname=raw, search='', query; + + if (raw.length > 1) { + let idx = raw.indexOf('?', 1); + + if (idx !== -1) { + search = raw.substring(idx); + pathname = raw.substring(0, idx); + if (search.length > 1) { + query = qs.parse(search.substring(1)); + } + } + } + + return req._parsedUrl = { pathname, search, query, raw }; +} diff --git a/node_modules/@polka/url/index.d.ts b/node_modules/@polka/url/index.d.ts new file mode 100644 index 0000000..9b27c04 --- /dev/null +++ b/node_modules/@polka/url/index.d.ts @@ -0,0 +1,10 @@ +import type { IncomingMessage } from 'http'; + +export interface ParsedURL { + pathname: string; + search: string; + query: Record | void; + raw: string; +} + +export function parse(req: IncomingMessage): ParsedURL; diff --git a/node_modules/@polka/url/license b/node_modules/@polka/url/license new file mode 100644 index 0000000..d46889a --- /dev/null +++ b/node_modules/@polka/url/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Luke Edwards (https://lukeed.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. diff --git a/node_modules/@polka/url/package.json b/node_modules/@polka/url/package.json new file mode 100644 index 0000000..2d36518 --- /dev/null +++ b/node_modules/@polka/url/package.json @@ -0,0 +1,30 @@ +{ + "version": "1.0.0-next.21", + "name": "@polka/url", + "repository": "lukeed/polka", + "description": "Super fast, memoized `req.url` parser", + "module": "build.mjs", + "types": "index.d.ts", + "main": "build.js", + "license": "MIT", + "exports": { + ".": { + "import": "./build.mjs", + "require": "./build.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "*.d.ts", + "build.*" + ], + "author": { + "name": "Luke Edwards", + "email": "luke@lukeed.com", + "url": "https://lukeed.com" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "8d6e31871225f4449e645ecba13de7014f772b34" +} diff --git a/node_modules/@polka/url/readme.md b/node_modules/@polka/url/readme.md new file mode 100644 index 0000000..69947a7 --- /dev/null +++ b/node_modules/@polka/url/readme.md @@ -0,0 +1,68 @@ +# @polka/url [![npm](https://badgen.now.sh/npm/v/@polka/url)](https://npmjs.org/package/@polka/url) + +> Super fast, memoized `req.url` parser; _not_ limited to [Polka][polka]! + +Parses the `url` from a [`IncomingMessage`](https://nodejs.org/api/http.html#http_class_http_incomingmessage) request. The returned object will always only contain the following keys: `search`, `query`, `pathname`, and `raw`. + +> **Note:** This library does not process `protocol`, `hostname`, `port`, etc.
This is because the incoming `req.url` value only begins with the path information. + +Parsed requests will be mutated with a `_parsedUrl` key, containing the returned output. This is used for future memoization, avoiding the need to fully parse the same `url` value multiple times. + +## Install + +``` +$ npm install --save @polka/url +``` + +## Usage + +```js +const parse = require('@polka/url'); + +let req = { + url: '/foo/bar?fizz=buzz' +}; +let output = parse(req); +//=> { +//=> pathname: '/foo/bar', +//=> raw: '/foo/bar?fizz=buzz', +//=> search: '?fizz=buzz', +//=> query: { +//=> fizz: 'buzz' +//=> }, +//=> } + +// Attaches result for future memoization +assert.deepEqual(output, req._parsedUrl); //=> true +``` + +## API + +### url(req) +Returns: `Object` or `undefined` + +> **Important:** The `req` must have a `url` key, otherwise `undefined` will be returned.
If no input is provided at all, a `TypeError` will be thrown. + +#### req +Type: `IncomingMessage` or `{ url: string }` + +The incoming HTTP request (`req`) or a plain `Object` with a `url` key. + +> **Note:** In Node.js servers, the [`req.url`](https://nodejs.org/api/http.html#http_message_url) begins with a pathname & does not include a `hash`. + + +## Benchmarks + +Check out the [`bench`](/bench) directory for in-depth benchmark results and comparisons. + + +## Support + +Any issues or questions can be sent to the [Polka][polka] repository.
However, please specify that your inquiry is about `@polka/url` specifically. + + +## License + +MIT © [Luke Edwards](https://lukeed.com) + +[polka]: https://github.com/lukeed/polka diff --git a/node_modules/@supabase/auth-helpers-shared/LICENSE b/node_modules/@supabase/auth-helpers-shared/LICENSE new file mode 100644 index 0000000..8433b09 --- /dev/null +++ b/node_modules/@supabase/auth-helpers-shared/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Supabase + +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/@supabase/auth-helpers-shared/dist/index.d.ts b/node_modules/@supabase/auth-helpers-shared/dist/index.d.ts new file mode 100644 index 0000000..8469b9f --- /dev/null +++ b/node_modules/@supabase/auth-helpers-shared/dist/index.d.ts @@ -0,0 +1,47 @@ +import * as _supabase_supabase_js from '@supabase/supabase-js'; +import { SupabaseClientOptions, GoTrueClientOptions, Session } from '@supabase/supabase-js'; +import { CookieSerializeOptions } from 'cookie'; +export { parse as parseCookies, serialize as serializeCookie } from 'cookie'; +import { GenericSchema } from '@supabase/supabase-js/dist/module/lib/types'; + +declare type CookieOptions = Pick; +declare type CookieOptionsWithName = { + name?: string; +} & CookieOptions; +declare type SupabaseClientOptionsWithoutAuth = Omit, 'auth'>; + +interface StorageAdapter extends Exclude { +} +declare abstract class CookieAuthStorageAdapter implements StorageAdapter { + protected readonly cookieOptions: CookieOptions; + constructor(cookieOptions?: CookieOptions); + protected abstract getCookie(name: string): string | undefined | null; + protected abstract setCookie(name: string, value: string): void; + protected abstract deleteCookie(name: string): void; + getItem(key: string): string | Promise | null; + setItem(key: string, value: string): void | Promise; + removeItem(key: string): void | Promise; +} + +declare class BrowserCookieAuthStorageAdapter extends CookieAuthStorageAdapter { + constructor(cookieOptions?: CookieOptions); + protected getCookie(name: string): string | null; + protected setCookie(name: string, value: string): null | undefined; + protected deleteCookie(name: string): null | undefined; +} + +declare function createSupabaseClient(supabaseUrl: string, supabaseKey: string, options: SupabaseClientOptionsWithoutAuth & { + auth: { + storage: StorageAdapter; + storageKey?: string; + }; +}): _supabase_supabase_js.SupabaseClient; + +declare function parseSupabaseCookie(str: string | null | undefined): Partial | null; +declare function stringifySupabaseSession(session: Session): string; + +declare function isBrowser(): boolean; + +declare const DEFAULT_COOKIE_OPTIONS: CookieOptions; + +export { BrowserCookieAuthStorageAdapter, CookieAuthStorageAdapter, CookieOptions, CookieOptionsWithName, DEFAULT_COOKIE_OPTIONS, StorageAdapter, SupabaseClientOptionsWithoutAuth, createSupabaseClient, isBrowser, parseSupabaseCookie, stringifySupabaseSession }; diff --git a/node_modules/@supabase/auth-helpers-shared/dist/index.js b/node_modules/@supabase/auth-helpers-shared/dist/index.js new file mode 100644 index 0000000..3428d31 --- /dev/null +++ b/node_modules/@supabase/auth-helpers-shared/dist/index.js @@ -0,0 +1,350 @@ +"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 __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( + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// ../../node_modules/.pnpm/cookie@0.5.0/node_modules/cookie/index.js +var require_cookie = __commonJS({ + "../../node_modules/.pnpm/cookie@0.5.0/node_modules/cookie/index.js"(exports) { + "use strict"; + exports.parse = parse3; + exports.serialize = serialize3; + var __toString = Object.prototype.toString; + var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + function parse3(str, options) { + if (typeof str !== "string") { + throw new TypeError("argument str must be a string"); + } + var obj = {}; + var opt = options || {}; + var dec = opt.decode || decode; + var index = 0; + while (index < str.length) { + var eqIdx = str.indexOf("=", index); + if (eqIdx === -1) { + break; + } + var endIdx = str.indexOf(";", index); + if (endIdx === -1) { + endIdx = str.length; + } else if (endIdx < eqIdx) { + index = str.lastIndexOf(";", eqIdx - 1) + 1; + continue; + } + var key = str.slice(index, eqIdx).trim(); + if (void 0 === obj[key]) { + var val = str.slice(eqIdx + 1, endIdx).trim(); + if (val.charCodeAt(0) === 34) { + val = val.slice(1, -1); + } + obj[key] = tryDecode(val, dec); + } + index = endIdx + 1; + } + return obj; + } + function serialize3(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + if (typeof enc !== "function") { + throw new TypeError("option encode is invalid"); + } + if (!fieldContentRegExp.test(name)) { + throw new TypeError("argument name is invalid"); + } + var value = enc(val); + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError("argument val is invalid"); + } + var str = name + "=" + value; + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + if (isNaN(maxAge) || !isFinite(maxAge)) { + throw new TypeError("option maxAge is invalid"); + } + str += "; Max-Age=" + Math.floor(maxAge); + } + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError("option domain is invalid"); + } + str += "; Domain=" + opt.domain; + } + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError("option path is invalid"); + } + str += "; Path=" + opt.path; + } + if (opt.expires) { + var expires = opt.expires; + if (!isDate(expires) || isNaN(expires.valueOf())) { + throw new TypeError("option expires is invalid"); + } + str += "; Expires=" + expires.toUTCString(); + } + if (opt.httpOnly) { + str += "; HttpOnly"; + } + if (opt.secure) { + str += "; Secure"; + } + if (opt.priority) { + var priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority; + switch (priority) { + case "low": + str += "; Priority=Low"; + break; + case "medium": + str += "; Priority=Medium"; + break; + case "high": + str += "; Priority=High"; + break; + default: + throw new TypeError("option priority is invalid"); + } + } + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite; + switch (sameSite) { + case true: + str += "; SameSite=Strict"; + break; + case "lax": + str += "; SameSite=Lax"; + break; + case "strict": + str += "; SameSite=Strict"; + break; + case "none": + str += "; SameSite=None"; + break; + default: + throw new TypeError("option sameSite is invalid"); + } + } + return str; + } + function decode(str) { + return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str; + } + function encode(val) { + return encodeURIComponent(val); + } + function isDate(val) { + return __toString.call(val) === "[object Date]" || val instanceof Date; + } + function tryDecode(str, decode2) { + try { + return decode2(str); + } catch (e) { + return str; + } + } + } +}); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + BrowserCookieAuthStorageAdapter: () => BrowserCookieAuthStorageAdapter, + CookieAuthStorageAdapter: () => CookieAuthStorageAdapter, + DEFAULT_COOKIE_OPTIONS: () => DEFAULT_COOKIE_OPTIONS, + createSupabaseClient: () => createSupabaseClient, + isBrowser: () => isBrowser, + parseCookies: () => import_cookie.parse, + parseSupabaseCookie: () => parseSupabaseCookie, + serializeCookie: () => import_cookie.serialize, + stringifySupabaseSession: () => stringifySupabaseSession +}); +module.exports = __toCommonJS(src_exports); + +// src/browserCookieStorage.ts +var import_cookie2 = __toESM(require_cookie()); + +// src/utils/cookies.ts +var import_cookie = __toESM(require_cookie()); +var import_jose = require("jose"); +function parseSupabaseCookie(str) { + if (!str) { + return null; + } + try { + const session = JSON.parse(str); + if (!session) { + return null; + } + if (session.constructor.name === "Object") { + return session; + } + if (session.constructor.name !== "Array") { + throw new Error(`Unexpected format: ${session.constructor.name}`); + } + const [_header, payloadStr, _signature] = session[0].split("."); + const payload = import_jose.base64url.decode(payloadStr); + const decoder = new TextDecoder(); + const { exp, sub, ...user } = JSON.parse(decoder.decode(payload)); + return { + expires_at: exp, + expires_in: exp - Math.round(Date.now() / 1e3), + token_type: "bearer", + access_token: session[0], + refresh_token: session[1], + provider_token: session[2], + provider_refresh_token: session[3], + user: { + id: sub, + factors: session[4], + ...user + } + }; + } catch (err) { + console.warn("Failed to parse cookie string:", err); + return null; + } +} +function stringifySupabaseSession(session) { + var _a; + return JSON.stringify([ + session.access_token, + session.refresh_token, + session.provider_token, + session.provider_refresh_token, + ((_a = session.user) == null ? void 0 : _a.factors) ?? null + ]); +} + +// src/utils/helpers.ts +function isBrowser() { + return typeof window !== "undefined" && typeof window.document !== "undefined"; +} + +// src/utils/constants.ts +var DEFAULT_COOKIE_OPTIONS = { + path: "/", + maxAge: 60 * 60 * 24 * 365 * 1e3 +}; + +// src/cookieAuthStorageAdapter.ts +var CookieAuthStorageAdapter = class { + constructor(cookieOptions) { + this.cookieOptions = { + ...DEFAULT_COOKIE_OPTIONS, + ...cookieOptions + }; + } + getItem(key) { + const value = this.getCookie(key); + if (!value) + return null; + if (key.endsWith("-code-verifier")) { + return value; + } + return JSON.stringify(parseSupabaseCookie(value)); + } + setItem(key, value) { + if (key.endsWith("-code-verifier")) { + this.setCookie(key, value); + return; + } + let session = JSON.parse(value); + const sessionStr = stringifySupabaseSession(session); + this.setCookie(key, sessionStr); + } + removeItem(key) { + this.deleteCookie(key); + } +}; + +// src/browserCookieStorage.ts +var BrowserCookieAuthStorageAdapter = class extends CookieAuthStorageAdapter { + constructor(cookieOptions) { + super(cookieOptions); + } + getCookie(name) { + if (!isBrowser()) + return null; + const cookies = (0, import_cookie2.parse)(document.cookie); + return cookies[name]; + } + setCookie(name, value) { + if (!isBrowser()) + return null; + document.cookie = (0, import_cookie2.serialize)(name, value, { + ...this.cookieOptions, + httpOnly: false + }); + } + deleteCookie(name) { + if (!isBrowser()) + return null; + document.cookie = (0, import_cookie2.serialize)(name, "", { + ...this.cookieOptions, + maxAge: 0, + httpOnly: false + }); + } +}; + +// src/createClient.ts +var import_supabase_js = require("@supabase/supabase-js"); +function createSupabaseClient(supabaseUrl, supabaseKey, options) { + var _a; + const bowser = isBrowser(); + return (0, import_supabase_js.createClient)(supabaseUrl, supabaseKey, { + ...options, + auth: { + flowType: "pkce", + autoRefreshToken: bowser, + detectSessionInUrl: bowser, + persistSession: true, + storage: options.auth.storage, + ...((_a = options.auth) == null ? void 0 : _a.storageKey) ? { + storageKey: options.auth.storageKey + } : {} + } + }); +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + BrowserCookieAuthStorageAdapter, + CookieAuthStorageAdapter, + DEFAULT_COOKIE_OPTIONS, + createSupabaseClient, + isBrowser, + parseCookies, + parseSupabaseCookie, + serializeCookie, + stringifySupabaseSession +}); +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@supabase/auth-helpers-shared/dist/index.js.map b/node_modules/@supabase/auth-helpers-shared/dist/index.js.map new file mode 100644 index 0000000..8d1a9c5 --- /dev/null +++ b/node_modules/@supabase/auth-helpers-shared/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../node_modules/.pnpm/cookie@0.5.0/node_modules/cookie/index.js","../src/index.ts","../src/browserCookieStorage.ts","../src/utils/cookies.ts","../src/utils/helpers.ts","../src/utils/constants.ts","../src/cookieAuthStorageAdapter.ts","../src/createClient.ts"],"sourcesContent":["/*!\n * cookie\n * Copyright(c) 2012-2014 Roman Shtylman\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict';\n\n/**\n * Module exports.\n * @public\n */\n\nexports.parse = parse;\nexports.serialize = serialize;\n\n/**\n * Module variables.\n * @private\n */\n\nvar __toString = Object.prototype.toString\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\n\nvar fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\n/**\n * Parse a cookie header.\n *\n * Parse the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n *\n * @param {string} str\n * @param {object} [options]\n * @return {object}\n * @public\n */\n\nfunction parse(str, options) {\n if (typeof str !== 'string') {\n throw new TypeError('argument str must be a string');\n }\n\n var obj = {}\n var opt = options || {};\n var dec = opt.decode || decode;\n\n var index = 0\n while (index < str.length) {\n var eqIdx = str.indexOf('=', index)\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break\n }\n\n var endIdx = str.indexOf(';', index)\n\n if (endIdx === -1) {\n endIdx = str.length\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(';', eqIdx - 1) + 1\n continue\n }\n\n var key = str.slice(index, eqIdx).trim()\n\n // only assign once\n if (undefined === obj[key]) {\n var val = str.slice(eqIdx + 1, endIdx).trim()\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1)\n }\n\n obj[key] = tryDecode(val, dec);\n }\n\n index = endIdx + 1\n }\n\n return obj;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * serialize('foo', 'bar', { httpOnly: true })\n * => \"foo=bar; httpOnly\"\n *\n * @param {string} name\n * @param {string} val\n * @param {object} [options]\n * @return {string}\n * @public\n */\n\nfunction serialize(name, val, options) {\n var opt = options || {};\n var enc = opt.encode || encode;\n\n if (typeof enc !== 'function') {\n throw new TypeError('option encode is invalid');\n }\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError('argument name is invalid');\n }\n\n var value = enc(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError('argument val is invalid');\n }\n\n var str = name + '=' + value;\n\n if (null != opt.maxAge) {\n var maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError('option maxAge is invalid')\n }\n\n str += '; Max-Age=' + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError('option domain is invalid');\n }\n\n str += '; Domain=' + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError('option path is invalid');\n }\n\n str += '; Path=' + opt.path;\n }\n\n if (opt.expires) {\n var expires = opt.expires\n\n if (!isDate(expires) || isNaN(expires.valueOf())) {\n throw new TypeError('option expires is invalid');\n }\n\n str += '; Expires=' + expires.toUTCString()\n }\n\n if (opt.httpOnly) {\n str += '; HttpOnly';\n }\n\n if (opt.secure) {\n str += '; Secure';\n }\n\n if (opt.priority) {\n var priority = typeof opt.priority === 'string'\n ? opt.priority.toLowerCase()\n : opt.priority\n\n switch (priority) {\n case 'low':\n str += '; Priority=Low'\n break\n case 'medium':\n str += '; Priority=Medium'\n break\n case 'high':\n str += '; Priority=High'\n break\n default:\n throw new TypeError('option priority is invalid')\n }\n }\n\n if (opt.sameSite) {\n var sameSite = typeof opt.sameSite === 'string'\n ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n str += '; SameSite=Strict';\n break;\n case 'lax':\n str += '; SameSite=Lax';\n break;\n case 'strict':\n str += '; SameSite=Strict';\n break;\n case 'none':\n str += '; SameSite=None';\n break;\n default:\n throw new TypeError('option sameSite is invalid');\n }\n }\n\n return str;\n}\n\n/**\n * URL-decode string value. Optimized to skip native call when no %.\n *\n * @param {string} str\n * @returns {string}\n */\n\nfunction decode (str) {\n return str.indexOf('%') !== -1\n ? decodeURIComponent(str)\n : str\n}\n\n/**\n * URL-encode value.\n *\n * @param {string} str\n * @returns {string}\n */\n\nfunction encode (val) {\n return encodeURIComponent(val)\n}\n\n/**\n * Determine if value is a Date.\n *\n * @param {*} val\n * @private\n */\n\nfunction isDate (val) {\n return __toString.call(val) === '[object Date]' ||\n val instanceof Date\n}\n\n/**\n * Try decoding a string using a decoding function.\n *\n * @param {string} str\n * @param {function} decode\n * @private\n */\n\nfunction tryDecode(str, decode) {\n try {\n return decode(str);\n } catch (e) {\n return str;\n }\n}\n","export * from './browserCookieStorage';\nexport * from './cookieAuthStorageAdapter';\nexport * from './createClient';\nexport * from './types';\n\nexport {\n\tparseCookies,\n\tserializeCookie,\n\tparseSupabaseCookie,\n\tstringifySupabaseSession,\n\tisBrowser,\n\tDEFAULT_COOKIE_OPTIONS\n} from './utils';\n","import { parse, serialize } from 'cookie';\nimport { CookieAuthStorageAdapter } from './cookieAuthStorageAdapter';\nimport { CookieOptions } from './types';\nimport { isBrowser } from './utils';\n\nexport class BrowserCookieAuthStorageAdapter extends CookieAuthStorageAdapter {\n\tconstructor(cookieOptions?: CookieOptions) {\n\t\tsuper(cookieOptions);\n\t}\n\n\tprotected getCookie(name: string) {\n\t\tif (!isBrowser()) return null;\n\n\t\tconst cookies = parse(document.cookie);\n\t\treturn cookies[name];\n\t}\n\n\tprotected setCookie(name: string, value: string) {\n\t\tif (!isBrowser()) return null;\n\n\t\tdocument.cookie = serialize(name, value, {\n\t\t\t...this.cookieOptions,\n\t\t\thttpOnly: false\n\t\t});\n\t}\n\n\tprotected deleteCookie(name: string) {\n\t\tif (!isBrowser()) return null;\n\n\t\tdocument.cookie = serialize(name, '', {\n\t\t\t...this.cookieOptions,\n\t\t\tmaxAge: 0,\n\t\t\thttpOnly: false\n\t\t});\n\t}\n}\n","import { Session } from '@supabase/supabase-js';\nimport { parse, serialize } from 'cookie';\nimport { base64url } from 'jose';\n\nexport { parse as parseCookies, serialize as serializeCookie };\n\n/**\n * Based on the environment and the request we know if a secure cookie can be set.\n */\nexport function isSecureEnvironment(headerHost?: string | string[]) {\n\tif (!headerHost) {\n\t\tthrow new Error('The \"host\" request header is not available');\n\t}\n\n\tconst headerHostStr = Array.isArray(headerHost) ? headerHost[0] : headerHost;\n\n\tconst host = (headerHostStr.indexOf(':') > -1 && headerHostStr.split(':')[0]) || headerHostStr;\n\tif (['localhost', '127.0.0.1'].indexOf(host) > -1 || host.endsWith('.local')) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nexport function parseSupabaseCookie(str: string | null | undefined): Partial | null {\n\tif (!str) {\n\t\treturn null;\n\t}\n\n\ttry {\n\t\tconst session = JSON.parse(str);\n\t\tif (!session) {\n\t\t\treturn null;\n\t\t}\n\t\t// Support previous cookie which was a stringified session object.\n\t\tif (session.constructor.name === 'Object') {\n\t\t\treturn session;\n\t\t}\n\t\tif (session.constructor.name !== 'Array') {\n\t\t\tthrow new Error(`Unexpected format: ${session.constructor.name}`);\n\t\t}\n\n\t\tconst [_header, payloadStr, _signature] = session[0].split('.');\n\t\tconst payload = base64url.decode(payloadStr);\n\t\tconst decoder = new TextDecoder();\n\n\t\tconst { exp, sub, ...user } = JSON.parse(decoder.decode(payload));\n\n\t\treturn {\n\t\t\texpires_at: exp,\n\t\t\texpires_in: exp - Math.round(Date.now() / 1000),\n\t\t\ttoken_type: 'bearer',\n\t\t\taccess_token: session[0],\n\t\t\trefresh_token: session[1],\n\t\t\tprovider_token: session[2],\n\t\t\tprovider_refresh_token: session[3],\n\t\t\tuser: {\n\t\t\t\tid: sub,\n\t\t\t\tfactors: session[4],\n\t\t\t\t...user\n\t\t\t}\n\t\t};\n\t} catch (err) {\n\t\tconsole.warn('Failed to parse cookie string:', err);\n\t\treturn null;\n\t}\n}\n\nexport function stringifySupabaseSession(session: Session): string {\n\treturn JSON.stringify([\n\t\tsession.access_token,\n\t\tsession.refresh_token,\n\t\tsession.provider_token,\n\t\tsession.provider_refresh_token,\n\t\tsession.user?.factors ?? null\n\t]);\n}\n","export function isBrowser() {\n\treturn typeof window !== 'undefined' && typeof window.document !== 'undefined';\n}\n","import { CookieOptions } from '../types';\n\nexport const DEFAULT_COOKIE_OPTIONS: CookieOptions = {\n\tpath: '/',\n\tmaxAge: 60 * 60 * 24 * 365 * 1000\n};\n","import { GoTrueClientOptions, Session } from '@supabase/supabase-js';\nimport { DEFAULT_COOKIE_OPTIONS, parseSupabaseCookie, stringifySupabaseSession } from './utils';\nimport { CookieOptions } from './types';\n\nexport interface StorageAdapter extends Exclude {}\n\nexport abstract class CookieAuthStorageAdapter implements StorageAdapter {\n\tprotected readonly cookieOptions: CookieOptions;\n\n\tconstructor(cookieOptions?: CookieOptions) {\n\t\tthis.cookieOptions = {\n\t\t\t...DEFAULT_COOKIE_OPTIONS,\n\t\t\t...cookieOptions\n\t\t};\n\t}\n\n\tprotected abstract getCookie(name: string): string | undefined | null;\n\tprotected abstract setCookie(name: string, value: string): void;\n\tprotected abstract deleteCookie(name: string): void;\n\n\tgetItem(key: string): string | Promise | null {\n\t\tconst value = this.getCookie(key);\n\n\t\tif (!value) return null;\n\n\t\t// pkce code verifier\n\t\tif (key.endsWith('-code-verifier')) {\n\t\t\treturn value;\n\t\t}\n\n\t\treturn JSON.stringify(parseSupabaseCookie(value));\n\t}\n\n\tsetItem(key: string, value: string): void | Promise {\n\t\t// pkce code verifier\n\t\tif (key.endsWith('-code-verifier')) {\n\t\t\tthis.setCookie(key, value);\n\t\t\treturn;\n\t\t}\n\n\t\tlet session: Session = JSON.parse(value);\n\t\tconst sessionStr = stringifySupabaseSession(session);\n\n\t\tthis.setCookie(key, sessionStr);\n\t}\n\n\tremoveItem(key: string): void | Promise {\n\t\tthis.deleteCookie(key);\n\t}\n}\n","import { createClient } from '@supabase/supabase-js';\nimport { SupabaseClientOptionsWithoutAuth } from './types';\nimport { isBrowser } from './utils';\nimport { StorageAdapter } from './cookieAuthStorageAdapter';\nimport { GenericSchema } from '@supabase/supabase-js/dist/module/lib/types';\n\nexport function createSupabaseClient<\n\tDatabase = any,\n\tSchemaName extends string & keyof Database = 'public' extends keyof Database\n\t\t? 'public'\n\t\t: string & keyof Database,\n\tSchema extends GenericSchema = Database[SchemaName] extends GenericSchema\n\t\t? Database[SchemaName]\n\t\t: any\n>(\n\tsupabaseUrl: string,\n\tsupabaseKey: string,\n\toptions: SupabaseClientOptionsWithoutAuth & {\n\t\tauth: {\n\t\t\tstorage: StorageAdapter;\n\t\t\tstorageKey?: string;\n\t\t};\n\t}\n) {\n\tconst bowser = isBrowser();\n\n\treturn createClient(supabaseUrl, supabaseKey, {\n\t\t...options,\n\t\tauth: {\n\t\t\tflowType: 'pkce',\n\t\t\tautoRefreshToken: bowser,\n\t\t\tdetectSessionInUrl: bowser,\n\t\t\tpersistSession: true,\n\t\t\tstorage: options.auth.storage,\n\n\t\t\t// fix this in supabase-js\n\t\t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AAM,SAAS,UAAU;AAEzB,aAAO,iCAA2C,aAAa,aAAa;AAAA,IAC3E,GAAG;AAAA,IACH,MAAM;AAAA,MACL,UAAU;AAAA,MACV,kBAAkB;AAAA,MAClB,oBAAoB;AAAA,MACpB,gBAAgB;AAAA,MAChB,SAAS,QAAQ,KAAK;AAAA,MAGtB,KAAI,aAAQ,SAAR,mBAAc,cACf;AAAA,QACA,YAAY,QAAQ,KAAK;AAAA,MACzB,IACA,CAAC;AAAA,IACL;AAAA,EACD,CAAC;AACF;","names":["parse","serialize","decode","import_cookie"]} \ No newline at end of file diff --git a/node_modules/@supabase/auth-helpers-shared/dist/index.mjs b/node_modules/@supabase/auth-helpers-shared/dist/index.mjs new file mode 100644 index 0000000..a57e220 --- /dev/null +++ b/node_modules/@supabase/auth-helpers-shared/dist/index.mjs @@ -0,0 +1,330 @@ +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 __commonJS = (cb, mod) => function __require() { + 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)) + 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( + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// ../../node_modules/.pnpm/cookie@0.5.0/node_modules/cookie/index.js +var require_cookie = __commonJS({ + "../../node_modules/.pnpm/cookie@0.5.0/node_modules/cookie/index.js"(exports) { + "use strict"; + exports.parse = parse3; + exports.serialize = serialize3; + var __toString = Object.prototype.toString; + var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + function parse3(str, options) { + if (typeof str !== "string") { + throw new TypeError("argument str must be a string"); + } + var obj = {}; + var opt = options || {}; + var dec = opt.decode || decode; + var index = 0; + while (index < str.length) { + var eqIdx = str.indexOf("=", index); + if (eqIdx === -1) { + break; + } + var endIdx = str.indexOf(";", index); + if (endIdx === -1) { + endIdx = str.length; + } else if (endIdx < eqIdx) { + index = str.lastIndexOf(";", eqIdx - 1) + 1; + continue; + } + var key = str.slice(index, eqIdx).trim(); + if (void 0 === obj[key]) { + var val = str.slice(eqIdx + 1, endIdx).trim(); + if (val.charCodeAt(0) === 34) { + val = val.slice(1, -1); + } + obj[key] = tryDecode(val, dec); + } + index = endIdx + 1; + } + return obj; + } + function serialize3(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + if (typeof enc !== "function") { + throw new TypeError("option encode is invalid"); + } + if (!fieldContentRegExp.test(name)) { + throw new TypeError("argument name is invalid"); + } + var value = enc(val); + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError("argument val is invalid"); + } + var str = name + "=" + value; + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + if (isNaN(maxAge) || !isFinite(maxAge)) { + throw new TypeError("option maxAge is invalid"); + } + str += "; Max-Age=" + Math.floor(maxAge); + } + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError("option domain is invalid"); + } + str += "; Domain=" + opt.domain; + } + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError("option path is invalid"); + } + str += "; Path=" + opt.path; + } + if (opt.expires) { + var expires = opt.expires; + if (!isDate(expires) || isNaN(expires.valueOf())) { + throw new TypeError("option expires is invalid"); + } + str += "; Expires=" + expires.toUTCString(); + } + if (opt.httpOnly) { + str += "; HttpOnly"; + } + if (opt.secure) { + str += "; Secure"; + } + if (opt.priority) { + var priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority; + switch (priority) { + case "low": + str += "; Priority=Low"; + break; + case "medium": + str += "; Priority=Medium"; + break; + case "high": + str += "; Priority=High"; + break; + default: + throw new TypeError("option priority is invalid"); + } + } + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite; + switch (sameSite) { + case true: + str += "; SameSite=Strict"; + break; + case "lax": + str += "; SameSite=Lax"; + break; + case "strict": + str += "; SameSite=Strict"; + break; + case "none": + str += "; SameSite=None"; + break; + default: + throw new TypeError("option sameSite is invalid"); + } + } + return str; + } + function decode(str) { + return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str; + } + function encode(val) { + return encodeURIComponent(val); + } + function isDate(val) { + return __toString.call(val) === "[object Date]" || val instanceof Date; + } + function tryDecode(str, decode2) { + try { + return decode2(str); + } catch (e) { + return str; + } + } + } +}); + +// src/browserCookieStorage.ts +var import_cookie2 = __toESM(require_cookie()); + +// src/utils/cookies.ts +var import_cookie = __toESM(require_cookie()); +import { base64url } from "jose"; +function parseSupabaseCookie(str) { + if (!str) { + return null; + } + try { + const session = JSON.parse(str); + if (!session) { + return null; + } + if (session.constructor.name === "Object") { + return session; + } + if (session.constructor.name !== "Array") { + throw new Error(`Unexpected format: ${session.constructor.name}`); + } + const [_header, payloadStr, _signature] = session[0].split("."); + const payload = base64url.decode(payloadStr); + const decoder = new TextDecoder(); + const { exp, sub, ...user } = JSON.parse(decoder.decode(payload)); + return { + expires_at: exp, + expires_in: exp - Math.round(Date.now() / 1e3), + token_type: "bearer", + access_token: session[0], + refresh_token: session[1], + provider_token: session[2], + provider_refresh_token: session[3], + user: { + id: sub, + factors: session[4], + ...user + } + }; + } catch (err) { + console.warn("Failed to parse cookie string:", err); + return null; + } +} +function stringifySupabaseSession(session) { + var _a; + return JSON.stringify([ + session.access_token, + session.refresh_token, + session.provider_token, + session.provider_refresh_token, + ((_a = session.user) == null ? void 0 : _a.factors) ?? null + ]); +} + +// src/utils/helpers.ts +function isBrowser() { + return typeof window !== "undefined" && typeof window.document !== "undefined"; +} + +// src/utils/constants.ts +var DEFAULT_COOKIE_OPTIONS = { + path: "/", + maxAge: 60 * 60 * 24 * 365 * 1e3 +}; + +// src/cookieAuthStorageAdapter.ts +var CookieAuthStorageAdapter = class { + constructor(cookieOptions) { + this.cookieOptions = { + ...DEFAULT_COOKIE_OPTIONS, + ...cookieOptions + }; + } + getItem(key) { + const value = this.getCookie(key); + if (!value) + return null; + if (key.endsWith("-code-verifier")) { + return value; + } + return JSON.stringify(parseSupabaseCookie(value)); + } + setItem(key, value) { + if (key.endsWith("-code-verifier")) { + this.setCookie(key, value); + return; + } + let session = JSON.parse(value); + const sessionStr = stringifySupabaseSession(session); + this.setCookie(key, sessionStr); + } + removeItem(key) { + this.deleteCookie(key); + } +}; + +// src/browserCookieStorage.ts +var BrowserCookieAuthStorageAdapter = class extends CookieAuthStorageAdapter { + constructor(cookieOptions) { + super(cookieOptions); + } + getCookie(name) { + if (!isBrowser()) + return null; + const cookies = (0, import_cookie2.parse)(document.cookie); + return cookies[name]; + } + setCookie(name, value) { + if (!isBrowser()) + return null; + document.cookie = (0, import_cookie2.serialize)(name, value, { + ...this.cookieOptions, + httpOnly: false + }); + } + deleteCookie(name) { + if (!isBrowser()) + return null; + document.cookie = (0, import_cookie2.serialize)(name, "", { + ...this.cookieOptions, + maxAge: 0, + httpOnly: false + }); + } +}; + +// src/createClient.ts +import { createClient } from "@supabase/supabase-js"; +function createSupabaseClient(supabaseUrl, supabaseKey, options) { + var _a; + const bowser = isBrowser(); + return createClient(supabaseUrl, supabaseKey, { + ...options, + auth: { + flowType: "pkce", + autoRefreshToken: bowser, + detectSessionInUrl: bowser, + persistSession: true, + storage: options.auth.storage, + ...((_a = options.auth) == null ? void 0 : _a.storageKey) ? { + storageKey: options.auth.storageKey + } : {} + } + }); +} +var export_parseCookies = import_cookie.parse; +var export_serializeCookie = import_cookie.serialize; +export { + BrowserCookieAuthStorageAdapter, + CookieAuthStorageAdapter, + DEFAULT_COOKIE_OPTIONS, + createSupabaseClient, + isBrowser, + export_parseCookies as parseCookies, + parseSupabaseCookie, + export_serializeCookie as serializeCookie, + stringifySupabaseSession +}; +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@supabase/auth-helpers-shared/dist/index.mjs.map b/node_modules/@supabase/auth-helpers-shared/dist/index.mjs.map new file mode 100644 index 0000000..6f62218 --- /dev/null +++ b/node_modules/@supabase/auth-helpers-shared/dist/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../node_modules/.pnpm/cookie@0.5.0/node_modules/cookie/index.js","../src/browserCookieStorage.ts","../src/utils/cookies.ts","../src/utils/helpers.ts","../src/utils/constants.ts","../src/cookieAuthStorageAdapter.ts","../src/createClient.ts"],"sourcesContent":["/*!\n * cookie\n * Copyright(c) 2012-2014 Roman Shtylman\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict';\n\n/**\n * Module exports.\n * @public\n */\n\nexports.parse = parse;\nexports.serialize = serialize;\n\n/**\n * Module variables.\n * @private\n */\n\nvar __toString = Object.prototype.toString\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\n\nvar fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\n/**\n * Parse a cookie header.\n *\n * Parse the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n *\n * @param {string} str\n * @param {object} [options]\n * @return {object}\n * @public\n */\n\nfunction parse(str, options) {\n if (typeof str !== 'string') {\n throw new TypeError('argument str must be a string');\n }\n\n var obj = {}\n var opt = options || {};\n var dec = opt.decode || decode;\n\n var index = 0\n while (index < str.length) {\n var eqIdx = str.indexOf('=', index)\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break\n }\n\n var endIdx = str.indexOf(';', index)\n\n if (endIdx === -1) {\n endIdx = str.length\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(';', eqIdx - 1) + 1\n continue\n }\n\n var key = str.slice(index, eqIdx).trim()\n\n // only assign once\n if (undefined === obj[key]) {\n var val = str.slice(eqIdx + 1, endIdx).trim()\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1)\n }\n\n obj[key] = tryDecode(val, dec);\n }\n\n index = endIdx + 1\n }\n\n return obj;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * serialize('foo', 'bar', { httpOnly: true })\n * => \"foo=bar; httpOnly\"\n *\n * @param {string} name\n * @param {string} val\n * @param {object} [options]\n * @return {string}\n * @public\n */\n\nfunction serialize(name, val, options) {\n var opt = options || {};\n var enc = opt.encode || encode;\n\n if (typeof enc !== 'function') {\n throw new TypeError('option encode is invalid');\n }\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError('argument name is invalid');\n }\n\n var value = enc(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError('argument val is invalid');\n }\n\n var str = name + '=' + value;\n\n if (null != opt.maxAge) {\n var maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError('option maxAge is invalid')\n }\n\n str += '; Max-Age=' + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError('option domain is invalid');\n }\n\n str += '; Domain=' + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError('option path is invalid');\n }\n\n str += '; Path=' + opt.path;\n }\n\n if (opt.expires) {\n var expires = opt.expires\n\n if (!isDate(expires) || isNaN(expires.valueOf())) {\n throw new TypeError('option expires is invalid');\n }\n\n str += '; Expires=' + expires.toUTCString()\n }\n\n if (opt.httpOnly) {\n str += '; HttpOnly';\n }\n\n if (opt.secure) {\n str += '; Secure';\n }\n\n if (opt.priority) {\n var priority = typeof opt.priority === 'string'\n ? opt.priority.toLowerCase()\n : opt.priority\n\n switch (priority) {\n case 'low':\n str += '; Priority=Low'\n break\n case 'medium':\n str += '; Priority=Medium'\n break\n case 'high':\n str += '; Priority=High'\n break\n default:\n throw new TypeError('option priority is invalid')\n }\n }\n\n if (opt.sameSite) {\n var sameSite = typeof opt.sameSite === 'string'\n ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n str += '; SameSite=Strict';\n break;\n case 'lax':\n str += '; SameSite=Lax';\n break;\n case 'strict':\n str += '; SameSite=Strict';\n break;\n case 'none':\n str += '; SameSite=None';\n break;\n default:\n throw new TypeError('option sameSite is invalid');\n }\n }\n\n return str;\n}\n\n/**\n * URL-decode string value. Optimized to skip native call when no %.\n *\n * @param {string} str\n * @returns {string}\n */\n\nfunction decode (str) {\n return str.indexOf('%') !== -1\n ? decodeURIComponent(str)\n : str\n}\n\n/**\n * URL-encode value.\n *\n * @param {string} str\n * @returns {string}\n */\n\nfunction encode (val) {\n return encodeURIComponent(val)\n}\n\n/**\n * Determine if value is a Date.\n *\n * @param {*} val\n * @private\n */\n\nfunction isDate (val) {\n return __toString.call(val) === '[object Date]' ||\n val instanceof Date\n}\n\n/**\n * Try decoding a string using a decoding function.\n *\n * @param {string} str\n * @param {function} decode\n * @private\n */\n\nfunction tryDecode(str, decode) {\n try {\n return decode(str);\n } catch (e) {\n return str;\n }\n}\n","import { parse, serialize } from 'cookie';\nimport { CookieAuthStorageAdapter } from './cookieAuthStorageAdapter';\nimport { CookieOptions } from './types';\nimport { isBrowser } from './utils';\n\nexport class BrowserCookieAuthStorageAdapter extends CookieAuthStorageAdapter {\n\tconstructor(cookieOptions?: CookieOptions) {\n\t\tsuper(cookieOptions);\n\t}\n\n\tprotected getCookie(name: string) {\n\t\tif (!isBrowser()) return null;\n\n\t\tconst cookies = parse(document.cookie);\n\t\treturn cookies[name];\n\t}\n\n\tprotected setCookie(name: string, value: string) {\n\t\tif (!isBrowser()) return null;\n\n\t\tdocument.cookie = serialize(name, value, {\n\t\t\t...this.cookieOptions,\n\t\t\thttpOnly: false\n\t\t});\n\t}\n\n\tprotected deleteCookie(name: string) {\n\t\tif (!isBrowser()) return null;\n\n\t\tdocument.cookie = serialize(name, '', {\n\t\t\t...this.cookieOptions,\n\t\t\tmaxAge: 0,\n\t\t\thttpOnly: false\n\t\t});\n\t}\n}\n","import { Session } from '@supabase/supabase-js';\nimport { parse, serialize } from 'cookie';\nimport { base64url } from 'jose';\n\nexport { parse as parseCookies, serialize as serializeCookie };\n\n/**\n * Based on the environment and the request we know if a secure cookie can be set.\n */\nexport function isSecureEnvironment(headerHost?: string | string[]) {\n\tif (!headerHost) {\n\t\tthrow new Error('The \"host\" request header is not available');\n\t}\n\n\tconst headerHostStr = Array.isArray(headerHost) ? headerHost[0] : headerHost;\n\n\tconst host = (headerHostStr.indexOf(':') > -1 && headerHostStr.split(':')[0]) || headerHostStr;\n\tif (['localhost', '127.0.0.1'].indexOf(host) > -1 || host.endsWith('.local')) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nexport function parseSupabaseCookie(str: string | null | undefined): Partial | null {\n\tif (!str) {\n\t\treturn null;\n\t}\n\n\ttry {\n\t\tconst session = JSON.parse(str);\n\t\tif (!session) {\n\t\t\treturn null;\n\t\t}\n\t\t// Support previous cookie which was a stringified session object.\n\t\tif (session.constructor.name === 'Object') {\n\t\t\treturn session;\n\t\t}\n\t\tif (session.constructor.name !== 'Array') {\n\t\t\tthrow new Error(`Unexpected format: ${session.constructor.name}`);\n\t\t}\n\n\t\tconst [_header, payloadStr, _signature] = session[0].split('.');\n\t\tconst payload = base64url.decode(payloadStr);\n\t\tconst decoder = new TextDecoder();\n\n\t\tconst { exp, sub, ...user } = JSON.parse(decoder.decode(payload));\n\n\t\treturn {\n\t\t\texpires_at: exp,\n\t\t\texpires_in: exp - Math.round(Date.now() / 1000),\n\t\t\ttoken_type: 'bearer',\n\t\t\taccess_token: session[0],\n\t\t\trefresh_token: session[1],\n\t\t\tprovider_token: session[2],\n\t\t\tprovider_refresh_token: session[3],\n\t\t\tuser: {\n\t\t\t\tid: sub,\n\t\t\t\tfactors: session[4],\n\t\t\t\t...user\n\t\t\t}\n\t\t};\n\t} catch (err) {\n\t\tconsole.warn('Failed to parse cookie string:', err);\n\t\treturn null;\n\t}\n}\n\nexport function stringifySupabaseSession(session: Session): string {\n\treturn JSON.stringify([\n\t\tsession.access_token,\n\t\tsession.refresh_token,\n\t\tsession.provider_token,\n\t\tsession.provider_refresh_token,\n\t\tsession.user?.factors ?? null\n\t]);\n}\n","export function isBrowser() {\n\treturn typeof window !== 'undefined' && typeof window.document !== 'undefined';\n}\n","import { CookieOptions } from '../types';\n\nexport const DEFAULT_COOKIE_OPTIONS: CookieOptions = {\n\tpath: '/',\n\tmaxAge: 60 * 60 * 24 * 365 * 1000\n};\n","import { GoTrueClientOptions, Session } from '@supabase/supabase-js';\nimport { DEFAULT_COOKIE_OPTIONS, parseSupabaseCookie, stringifySupabaseSession } from './utils';\nimport { CookieOptions } from './types';\n\nexport interface StorageAdapter extends Exclude {}\n\nexport abstract class CookieAuthStorageAdapter implements StorageAdapter {\n\tprotected readonly cookieOptions: CookieOptions;\n\n\tconstructor(cookieOptions?: CookieOptions) {\n\t\tthis.cookieOptions = {\n\t\t\t...DEFAULT_COOKIE_OPTIONS,\n\t\t\t...cookieOptions\n\t\t};\n\t}\n\n\tprotected abstract getCookie(name: string): string | undefined | null;\n\tprotected abstract setCookie(name: string, value: string): void;\n\tprotected abstract deleteCookie(name: string): void;\n\n\tgetItem(key: string): string | Promise | null {\n\t\tconst value = this.getCookie(key);\n\n\t\tif (!value) return null;\n\n\t\t// pkce code verifier\n\t\tif (key.endsWith('-code-verifier')) {\n\t\t\treturn value;\n\t\t}\n\n\t\treturn JSON.stringify(parseSupabaseCookie(value));\n\t}\n\n\tsetItem(key: string, value: string): void | Promise {\n\t\t// pkce code verifier\n\t\tif (key.endsWith('-code-verifier')) {\n\t\t\tthis.setCookie(key, value);\n\t\t\treturn;\n\t\t}\n\n\t\tlet session: Session = JSON.parse(value);\n\t\tconst sessionStr = stringifySupabaseSession(session);\n\n\t\tthis.setCookie(key, sessionStr);\n\t}\n\n\tremoveItem(key: string): void | Promise {\n\t\tthis.deleteCookie(key);\n\t}\n}\n","import { createClient } from '@supabase/supabase-js';\nimport { SupabaseClientOptionsWithoutAuth } from './types';\nimport { isBrowser } from './utils';\nimport { StorageAdapter } from './cookieAuthStorageAdapter';\nimport { GenericSchema } from '@supabase/supabase-js/dist/module/lib/types';\n\nexport function createSupabaseClient<\n\tDatabase = any,\n\tSchemaName extends string & keyof Database = 'public' extends keyof Database\n\t\t? 'public'\n\t\t: string & keyof Database,\n\tSchema extends GenericSchema = Database[SchemaName] extends GenericSchema\n\t\t? Database[SchemaName]\n\t\t: any\n>(\n\tsupabaseUrl: string,\n\tsupabaseKey: string,\n\toptions: SupabaseClientOptionsWithoutAuth & {\n\t\tauth: {\n\t\t\tstorage: StorageAdapter;\n\t\t\tstorageKey?: string;\n\t\t};\n\t}\n) {\n\tconst bowser = isBrowser();\n\n\treturn createClient(supabaseUrl, supabaseKey, {\n\t\t...options,\n\t\tauth: {\n\t\t\tflowType: 'pkce',\n\t\t\tautoRefreshToken: bowser,\n\t\t\tdetectSessionInUrl: bowser,\n\t\t\tpersistSession: true,\n\t\t\tstorage: options.auth.storage,\n\n\t\t\t// fix this in supabase-js\n\t\t\t...(options.auth?.storageKey\n\t\t\t\t? {\n\t\t\t\t\t\tstorageKey: options.auth.storageKey\n\t\t\t\t }\n\t\t\t\t: {})\n\t\t}\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAcA,YAAQ,Q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,KAAK;AAAA,MACzB,IACA,CAAC;AAAA,IACL;AAAA,EACD,CAAC;AACF;","names":["parse","serialize","decode","import_cookie"]} \ No newline at end of file diff --git a/node_modules/@supabase/auth-helpers-shared/package.json b/node_modules/@supabase/auth-helpers-shared/package.json new file mode 100644 index 0000000..6f0f0a9 --- /dev/null +++ b/node_modules/@supabase/auth-helpers-shared/package.json @@ -0,0 +1,49 @@ +{ + "name": "@supabase/auth-helpers-shared", + "version": "0.4.1", + "main": "dist/index.js", + "module": "dist/index.mjs", + "types": "dist/index.d.ts", + "publishConfig": { + "access": "public" + }, + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/supabase/auth-helpers.git" + }, + "keywords": [ + "Supabase", + "Auth", + "Svelte Kit", + "Svelte" + ], + "author": "Supabase", + "license": "MIT", + "bugs": { + "url": "https://github.com/supabase/auth-helpers/issues" + }, + "homepage": "https://github.com/supabase/auth-helpers#readme", + "devDependencies": { + "@supabase/supabase-js": "2.19.0", + "@types/cookie": "^0.5.1", + "cookie": "^0.5.0", + "next": "^12.1.5", + "react": ">=17.0.2 <18.0.0 || >=18.0.0-0 <19.0.0", + "react-dom": "^17.0.2 || ^18.0.0-0", + "tsup": "^6.5.0", + "tsconfig": "0.1.1" + }, + "dependencies": { + "jose": "^4.14.3" + }, + "peerDependencies": { + "@supabase/supabase-js": "^2.19.0" + }, + "scripts": { + "lint": "tsc", + "build": "tsup" + } +} \ No newline at end of file diff --git a/node_modules/@supabase/auth-helpers-sveltekit/LICENSE b/node_modules/@supabase/auth-helpers-sveltekit/LICENSE new file mode 100644 index 0000000..8433b09 --- /dev/null +++ b/node_modules/@supabase/auth-helpers-sveltekit/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Supabase + +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/@supabase/auth-helpers-sveltekit/README.md b/node_modules/@supabase/auth-helpers-sveltekit/README.md new file mode 100644 index 0000000..183c12a --- /dev/null +++ b/node_modules/@supabase/auth-helpers-sveltekit/README.md @@ -0,0 +1,386 @@ +# @supabase/auth-helpers-sveltekit (BETA) + +This submodule provides convenience helpers for implementing user authentication in [SvelteKit](https://kit.svelte.dev/) applications. + +## Installation + +Using [npm](https://npmjs.org): + +```sh +npm install @supabase/auth-helpers-sveltekit +``` + +This library supports the following tooling versions: + +- Node.js: `^16.15.0` + +## Getting Started + +### Configuration + +Set up the fillowing env vars. For local development you can set them in a `.env` file. See an example [here](../../examples/sveltekit/.env.example). + +```bash +# Find these in your Supabase project settings > API +PUBLIC_SUPABASE_URL=https://your-project.supabase.co +PUBLIC_SUPABASE_ANON_KEY=your-anon-key +``` + +### SupabaseClient setup + +Create a server supabase client in a handle hook: + +```ts +// src/hooks.server.ts +import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public'; +import { createSupabaseServerClient } from '@supabase/auth-helpers-sveltekit'; +import type { Handle } from '@sveltejs/kit'; + +export const handle: Handle = async ({ event, resolve }) => { + event.locals.supabase = createSupabaseServerClient({ + supabaseUrl: PUBLIC_SUPABASE_URL, + supabaseKey: PUBLIC_SUPABASE_ANON_KEY, + event + }); + + /** + * a little helper that is written for convenience so that instead + * of calling `const { data: { session } } = await supabase.auth.getSession()` + * you just call this `await getSession()` + */ + event.locals.getSession = async () => { + const { + data: { session } + } = await event.locals.supabase.auth.getSession(); + return session; + }; + + return resolve(event, { + /** + * There´s an issue with `filterSerializedResponseHeaders` not working when using `sequence` + * + * https://github.com/sveltejs/kit/issues/8061 + */ + filterSerializedResponseHeaders(name) { + return name === 'content-range'; + } + }); +}; +``` + +> Note that we are specifying `filterSerializedResponseHeaders` here. We need to tell SvelteKit that supabase needs the `content-range` header. + +### Send session to client + +In order to make the session available to the UI (pages, layouts) we need to pass the session in the root layout server load function: + +```ts +// src/routes/+layout.server.ts +import type { LayoutServerLoad } from './$types'; + +export const load: LayoutServerLoad = async ({ locals: { getSession } }) => { + return { + session: getSession() + }; +}; +``` + +### Shared Load functions and pages + +To be able to use Supabase in shared load functions and inside pages you need to create a Supabase client in the root layout load: + +```ts +// src/routes/+layout.ts +import { PUBLIC_SUPABASE_ANON_KEY, PUBLIC_SUPABASE_URL } from '$env/static/public'; +import { createSupabaseLoadClient } from '@supabase/auth-helpers-sveltekit'; +import type { LayoutLoad } from './$types'; +import type { Database } from '../DatabaseDefinitions'; + +export const load: LayoutLoad = async ({ fetch, data, depends }) => { + depends('supabase:auth'); + + const supabase = createSupabaseLoadClient({ + supabaseUrl: PUBLIC_SUPABASE_URL, + supabaseKey: PUBLIC_SUPABASE_ANON_KEY, + event: { fetch }, + serverSession: data.session + }); + + const { + data: { session } + } = await supabase.auth.getSession(); + + return { supabase, session }; +}; +``` + +The client can be accessed inside pages by `$page.data.supabase` or `data.supabase` when using `export let data: PageData`. + +The usage of `depends` tells sveltekit that this load function should be executed whenever `invalidate` is called to keep the page store in sync. + +`createSupabaseLoadClient` caches the client when running in a browser environment and therefore does not create a new client for every time the load function runs. + +### Setting up the event listener on the client side + +We need to create an event listener in the root `+layout.svelte` file in order catch supabase events being triggered. + +```svelte + + + + +``` + +The usage of `invalidate` tells sveltekit that the root `+layout.ts` load function should be executed whenever the session updates to keep the page store in sync. + +### Generate types from your database + +In order to get the most out of TypeScript and it´s intellisense, you should import the generated Database types into the `app.d.ts` type definition file that comes with your SvelteKit project, where `import('./DatabaseDefinitions')` points to the generated types file outlined in [v2 docs here](https://supabase.com/docs/reference/javascript/release-notes#typescript-support) after you have logged in, linked, and generated types through the Supabase CLI. + +```ts +// src/app.d.ts + +import { SupabaseClient, Session } from '@supabase/supabase-js'; +import { Database } from './DatabaseDefinitions'; + +declare global { + namespace App { + interface Locals { + supabase: SupabaseClient; + getSession(): Promise; + } + interface PageData { + session: Session | null; + } + // interface Error {} + // interface Platform {} + } +} +``` + +## Client-side data fetching with RLS + +For [row level security](https://supabase.com/docs/guides/auth/row-level-security) to work properly when fetching data client-side, you need to use supabaseClient from `PageData` and only run your query once the session is defined client-side: + +```html + + + +{#if session} +

client-side data fetching with RLS

+
{JSON.stringify(loadedData, null, 2)}
+{/if} +``` + +## Server-side data fetching with RLS + +```html + + + +
Protected content for {user.email}
+
{JSON.stringify(tableData, null, 2)}
+
{JSON.stringify(user, null, 2)}
+``` + +```ts +// src/routes/profile/+page.ts +import type { PageLoad } from './$types'; +import { redirect } from '@sveltejs/kit'; + +export const load: PageLoad = async ({ parent }) => { + const { supabase, session } = await parent(); + if (!session) { + throw redirect(303, '/'); + } + const { data: tableData } = await supabase.from('test').select('*'); + + return { + user: session.user, + tableData + }; +}; +``` + +## Protecting API routes + +Wrap an API Route to check that the user has a valid session. If they're not logged in the session is `null`. + +```ts +// src/routes/api/protected-route/+server.ts +import type { RequestHandler } from './$types'; +import { json, error } from '@sveltejs/kit'; + +export const GET: RequestHandler = async ({ locals: { supabase, getSession } }) => { + const session = await getSession(); + if (!session) { + // the user is not signed in + throw error(401, { message: 'Unauthorized' }); + } + const { data } = await supabase.from('test').select('*'); + + return json({ data }); +}; +``` + +If you visit `/api/protected-route` without a valid session cookie, you will get a 401 response. + +## Protecting Actions + +Wrap an Action to check that the user has a valid session. If they're not logged in the session is `null`. + +```ts +// src/routes/posts/+page.server.ts +import type { Actions } from './$types'; +import { error, fail } from '@sveltejs/kit'; + +export const actions: Actions = { + createPost: async ({ request, locals: { supabase, getSession } }) => { + const session = await getSession(); + + if (!session) { + // the user is not signed in + throw error(401, { message: 'Unauthorized' }); + } + // we are save, let the user create the post + const formData = await request.formData(); + const content = formData.get('content'); + + const { error: createPostError, data: newPost } = await supabase + .from('posts') + .insert({ content }); + + if (createPostError) { + return fail(500, { + supabaseErrorMessage: createPostError.message + }); + } + return { + newPost + }; + } +}; +``` + +If you try to submit a form with the action `?/createPost` without a valid session cookie, you will get a 401 error response. + +## Saving and deleting the session + +```ts +import type { Actions } from './$types'; +import { fail, redirect } from '@sveltejs/kit'; +import { AuthApiError } from '@supabase/supabase-js'; + +export const actions: Actions = { + signin: async ({ request, locals: { supabase } }) => { + const formData = await request.formData(); + + const email = formData.get('email') as string; + const password = formData.get('password') as string; + + const { error } = await supabase.auth.signInWithPassword({ + email, + password + }); + + if (error) { + if (error instanceof AuthApiError && error.status === 400) { + return fail(400, { + error: 'Invalid credentials.', + values: { + email + } + }); + } + return fail(500, { + error: 'Server error. Try again later.', + values: { + email + } + }); + } + + throw redirect(303, '/dashboard'); + }, + + signout: async ({ locals: { supabase } }) => { + await supabase.auth.signOut(); + throw redirect(303, '/'); + } +}; +``` + +## Protecting multiple routes + +To avoid writing the same auth logic in every single route you can use the handle hook to +protect multiple routes at once. + +```ts +// src/hooks.server.ts +import type { RequestHandler } from './$types'; +import { getSupabase } from '@supabase/auth-helpers-sveltekit'; +import { redirect, error } from '@sveltejs/kit'; + +export const handle: Handle = async ({ event, resolve }) => { + // protect requests to all routes that start with /protected-routes + if (event.url.pathname.startsWith('/protected-routes')) { + const session = await event.locals.getSession(); + if (!session) { + // the user is not signed in + throw redirect(303, '/'); + } + } + + // protect POST requests to all routes that start with /protected-posts + if (event.url.pathname.startsWith('/protected-posts') && event.request.method === 'POST') { + const session = await event.locals.getSession(); + if (!session) { + // the user is not signed in + throw error(303, '/'); + } + } + + return resolve(event); +}; +``` diff --git a/node_modules/@supabase/auth-helpers-sveltekit/dist/index.d.ts b/node_modules/@supabase/auth-helpers-sveltekit/dist/index.d.ts new file mode 100644 index 0000000..e75b230 --- /dev/null +++ b/node_modules/@supabase/auth-helpers-sveltekit/dist/index.d.ts @@ -0,0 +1,119 @@ +import { SupabaseClientOptionsWithoutAuth, CookieOptionsWithName } from '@supabase/auth-helpers-shared'; +import { Session, SupabaseClient } from '@supabase/supabase-js'; +import { LoadEvent, RequestEvent } from '@sveltejs/kit'; +import { GenericSchema } from '@supabase/supabase-js/dist/module/lib/types'; + +/** + * ## Authenticated Supabase client + * + * Returns a new authenticated Supabase client. + * + * When running in the browser it will create a single instance + * that is returned for subsequent runs. + * + * ### Example: + * + * ```ts + * import { invalidate } from '$app/navigation'; + * import { PUBLIC_SUPABASE_ANON_KEY, PUBLIC_SUPABASE_URL } from '$env/static/public'; + * import { createSupabaseLoadClient } from '@supabase/auth-helpers-sveltekit'; + * import type { LayoutLoad } from './$types'; + * + * export const load: LayoutLoad = async ({ fetch, data, depends }) => { + * depends('supabase:auth'); + * + * const supabase = createSupabaseLoadClient({ + * supabaseUrl: PUBLIC_SUPABASE_URL, + * supabaseKey: PUBLIC_SUPABASE_ANON_KEY, + * event: { fetch }, + * serverSession: data.session, + * onAuthStateChange() { + * invalidate('supabase:auth'); + * } + * }); + * + * const { + * data: { session } + * } = await supabase.auth.getSession(); + * + * return { supabase, session }; + * }; + * + * ``` + */ +declare function createSupabaseLoadClient({ supabaseUrl, supabaseKey, event, serverSession, options, cookieOptions }: { + supabaseUrl: string; + /** + * The supabase key. Make sure you **always** use the ANON_KEY. + */ + supabaseKey: string; + event: Pick; + /** + * The initial session from the server. + */ + serverSession: Session | null; + options?: SupabaseClientOptionsWithoutAuth; + cookieOptions?: CookieOptionsWithName; +}): SupabaseClient; + +/** + * ## Authenticated Supabase client + * ### Handle + * + * ```ts + * import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public'; + * import { createSupabaseServerClient } from '@supabase/auth-helpers-sveltekit'; + * import type { Handle } from '@sveltejs/kit'; + * + * export const handle: Handle = async ({ event, resolve }) => { + * event.locals.supabase = createSupabaseServerClient({ + * supabaseUrl: PUBLIC_SUPABASE_URL, + * supabaseKey: PUBLIC_SUPABASE_ANON_KEY, + * event + * }); + * + * event.locals.getSession = async () => { + * const { + * data: { session } + * } = await event.locals.supabase.auth.getSession(); + * return session; + * }; + * + * return resolve(event, { + * filterSerializedResponseHeaders(name) { + * return name === 'content-range'; + * } + * }); + * }; + * ``` + * + * ### Types + * + * ```ts + * import { SupabaseClient, Session } from '@supabase/supabase-js'; + * + * declare global { + * namespace App { + * interface Locals { + * supabase: SupabaseClient; + * getSession(): Promise; + * } + * // interface PageData {} + * // interface Error {} + * // interface Platform {} + * } + * } + * + * export {}; + * ``` + */ +declare function createSupabaseServerClient({ supabaseUrl, supabaseKey, event, options, cookieOptions, expiryMargin }: { + supabaseUrl: string; + supabaseKey: string; + event: Pick; + options?: SupabaseClientOptionsWithoutAuth; + cookieOptions?: CookieOptionsWithName; + expiryMargin?: number; +}): SupabaseClient; + +export { createSupabaseLoadClient, createSupabaseServerClient }; diff --git a/node_modules/@supabase/auth-helpers-sveltekit/dist/index.js b/node_modules/@supabase/auth-helpers-sveltekit/dist/index.js new file mode 100644 index 0000000..cff651e --- /dev/null +++ b/node_modules/@supabase/auth-helpers-sveltekit/dist/index.js @@ -0,0 +1,147 @@ +// src/supabaseLoadClient.ts +import { + createSupabaseClient, + isBrowser as isBrowser2 +} from "@supabase/auth-helpers-shared"; + +// src/loadStorageAdapter.ts +import { + BrowserCookieAuthStorageAdapter, + isBrowser +} from "@supabase/auth-helpers-shared"; +var SvelteKitLoadAuthStorageAdapter = class extends BrowserCookieAuthStorageAdapter { + constructor(serverSession = null, cookieOptions) { + super(cookieOptions); + this.serverSession = serverSession; + } + getItem(key) { + if (!isBrowser()) { + return JSON.stringify(this.serverSession); + } + return super.getItem(key); + } +}; + +// src/supabaseLoadClient.ts +var cachedBrowserClient; +function createSupabaseLoadClient({ + supabaseUrl, + supabaseKey, + event, + serverSession, + options, + cookieOptions +}) { + var _a; + const browser = isBrowser2(); + if (browser && cachedBrowserClient) { + return cachedBrowserClient; + } + const client = createSupabaseClient(supabaseUrl, supabaseKey, { + ...options, + global: { + fetch: event.fetch, + ...options == null ? void 0 : options.global, + headers: { + ...(_a = options == null ? void 0 : options.global) == null ? void 0 : _a.headers, + "X-Client-Info": `${"@supabase/auth-helpers-sveltekit"}@${"0.10.1"}` + } + }, + auth: { + storageKey: cookieOptions == null ? void 0 : cookieOptions.name, + storage: new SvelteKitLoadAuthStorageAdapter(serverSession, cookieOptions) + } + }); + if (browser) { + cachedBrowserClient = client; + } + return client; +} + +// src/supabaseServerClient.ts +import { + createSupabaseClient as createSupabaseClient2 +} from "@supabase/auth-helpers-shared"; + +// src/serverStorageAdapter.ts +import { CookieAuthStorageAdapter } from "@supabase/auth-helpers-shared"; +var SvelteKitServerAuthStorageAdapter = class extends CookieAuthStorageAdapter { + constructor(event, cookieOptions, expiryMargin = 60) { + super(cookieOptions); + this.event = event; + this.expiryMargin = expiryMargin; + this.isInitialDelete = true; + this.currentSession = null; + } + getCookie(name) { + return this.event.cookies.get(name); + } + setCookie(name, value) { + this.event.cookies.set(name, value, { + httpOnly: false, + ...this.cookieOptions + }); + } + deleteCookie(name) { + this.event.cookies.delete(name, { + httpOnly: false, + ...this.cookieOptions + }); + } + async getItem(key) { + const sessionStr = await super.getItem(key); + if (!sessionStr) { + this.currentSession = null; + return null; + } + const session = JSON.parse(sessionStr); + this.currentSession = session; + if (session == null ? void 0 : session.expires_at) { + session.expires_at -= this.expiryMargin; + } + return JSON.stringify(session); + } + removeItem(key) { + var _a; + if (this.isInitialDelete && ((_a = this.currentSession) == null ? void 0 : _a.expires_at)) { + const now = Math.round(Date.now() / 1e3); + if (this.currentSession.expires_at < now + 10) { + this.isInitialDelete = false; + return; + } + } + super.removeItem(key); + } +}; + +// src/supabaseServerClient.ts +function createSupabaseServerClient({ + supabaseUrl, + supabaseKey, + event, + options, + cookieOptions, + expiryMargin +}) { + var _a; + const client = createSupabaseClient2(supabaseUrl, supabaseKey, { + ...options, + global: { + ...options == null ? void 0 : options.global, + headers: { + ...(_a = options == null ? void 0 : options.global) == null ? void 0 : _a.headers, + "X-Client-Info": `${"@supabase/auth-helpers-sveltekit"}@${"0.10.1"}` + } + }, + auth: { + storageKey: cookieOptions == null ? void 0 : cookieOptions.name, + storage: new SvelteKitServerAuthStorageAdapter(event, cookieOptions, expiryMargin) + } + }); + return client; +} +export { + createSupabaseLoadClient, + createSupabaseServerClient +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@supabase/auth-helpers-sveltekit/dist/index.js.map b/node_modules/@supabase/auth-helpers-sveltekit/dist/index.js.map new file mode 100644 index 0000000..7d993a1 --- /dev/null +++ b/node_modules/@supabase/auth-helpers-sveltekit/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/supabaseLoadClient.ts","../src/loadStorageAdapter.ts","../src/supabaseServerClient.ts","../src/serverStorageAdapter.ts"],"sourcesContent":["import {\n\tCookieOptionsWithName,\n\tcreateSupabaseClient,\n\tisBrowser,\n\tSupabaseClientOptionsWithoutAuth\n} from '@supabase/auth-helpers-shared';\nimport { Session, SupabaseClient } from '@supabase/supabase-js';\nimport { LoadEvent } from '@sveltejs/kit';\nimport { SvelteKitLoadAuthStorageAdapter } from './loadStorageAdapter';\nimport { GenericSchema } from '@supabase/supabase-js/dist/module/lib/types';\n\nlet cachedBrowserClient: SupabaseClient | undefined;\n\n/**\n * ## Authenticated Supabase client\n *\n * Returns a new authenticated Supabase client.\n *\n * When running in the browser it will create a single instance\n * that is returned for subsequent runs.\n *\n * ### Example:\n *\n * ```ts\n * import { invalidate } from '$app/navigation';\n * import { PUBLIC_SUPABASE_ANON_KEY, PUBLIC_SUPABASE_URL } from '$env/static/public';\n * import { createSupabaseLoadClient } from '@supabase/auth-helpers-sveltekit';\n * import type { LayoutLoad } from './$types';\n *\n * export const load: LayoutLoad = async ({ fetch, data, depends }) => {\n * depends('supabase:auth');\n *\n * const supabase = createSupabaseLoadClient({\n * supabaseUrl: PUBLIC_SUPABASE_URL,\n * supabaseKey: PUBLIC_SUPABASE_ANON_KEY,\n * event: { fetch },\n * serverSession: data.session,\n * onAuthStateChange() {\n * invalidate('supabase:auth');\n * }\n * });\n *\n * const {\n * data: { session }\n * \t} = await supabase.auth.getSession();\n *\n * return { supabase, session };\n * };\n *\n * ```\n */\nexport function createSupabaseLoadClient<\n\tDatabase = any,\n\tSchemaName extends string & keyof Database = 'public' extends keyof Database\n\t\t? 'public'\n\t\t: string & keyof Database,\n\tSchema extends GenericSchema = Database[SchemaName] extends GenericSchema\n\t\t? Database[SchemaName]\n\t\t: any\n>({\n\tsupabaseUrl,\n\tsupabaseKey,\n\tevent,\n\tserverSession,\n\toptions,\n\tcookieOptions\n}: {\n\tsupabaseUrl: string;\n\t/**\n\t * The supabase key. Make sure you **always** use the ANON_KEY.\n\t */\n\tsupabaseKey: string;\n\tevent: Pick;\n\t/**\n\t * The initial session from the server.\n\t */\n\tserverSession: Session | null;\n\toptions?: SupabaseClientOptionsWithoutAuth;\n\tcookieOptions?: CookieOptionsWithName;\n}): SupabaseClient {\n\tconst browser = isBrowser();\n\tif (browser && cachedBrowserClient) {\n\t\treturn cachedBrowserClient as SupabaseClient;\n\t}\n\n\tconst client = createSupabaseClient(supabaseUrl, supabaseKey, {\n\t\t...options,\n\t\tglobal: {\n\t\t\tfetch: event.fetch,\n\t\t\t...options?.global,\n\t\t\theaders: {\n\t\t\t\t...options?.global?.headers,\n\t\t\t\t'X-Client-Info': `${PACKAGE_NAME}@${PACKAGE_VERSION}`\n\t\t\t}\n\t\t},\n\t\tauth: {\n\t\t\tstorageKey: cookieOptions?.name,\n\t\t\tstorage: new SvelteKitLoadAuthStorageAdapter(serverSession, cookieOptions)\n\t\t}\n\t});\n\n\tif (browser) {\n\t\tcachedBrowserClient = client;\n\t}\n\n\treturn client;\n}\n","import {\n\tBrowserCookieAuthStorageAdapter,\n\tCookieOptions,\n\tisBrowser\n} from '@supabase/auth-helpers-shared';\nimport { Session } from '@supabase/supabase-js';\n\nexport class SvelteKitLoadAuthStorageAdapter extends BrowserCookieAuthStorageAdapter {\n\tconstructor(\n\t\tprivate readonly serverSession: Session | null = null,\n\t\tcookieOptions?: CookieOptions\n\t) {\n\t\tsuper(cookieOptions);\n\t}\n\n\tgetItem(key: string) {\n\t\tif (!isBrowser()) {\n\t\t\treturn JSON.stringify(this.serverSession);\n\t\t}\n\t\treturn super.getItem(key);\n\t}\n}\n","import {\n\tCookieOptionsWithName,\n\tSupabaseClientOptionsWithoutAuth,\n\tcreateSupabaseClient\n} from '@supabase/auth-helpers-shared';\nimport { RequestEvent } from '@sveltejs/kit';\nimport { SvelteKitServerAuthStorageAdapter } from './serverStorageAdapter';\nimport { GenericSchema } from '@supabase/supabase-js/dist/module/lib/types';\nimport { SupabaseClient } from '@supabase/supabase-js';\n\n/**\n * ## Authenticated Supabase client\n * ### Handle\n *\n * ```ts\n * import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public';\n * import { createSupabaseServerClient } from '@supabase/auth-helpers-sveltekit';\n * import type { Handle } from '@sveltejs/kit';\n *\n * export const handle: Handle = async ({ event, resolve }) => {\n * event.locals.supabase = createSupabaseServerClient({\n * supabaseUrl: PUBLIC_SUPABASE_URL,\n * supabaseKey: PUBLIC_SUPABASE_ANON_KEY,\n * event\n * });\n *\n * event.locals.getSession = async () => {\n * const {\n * data: { session }\n * } = await event.locals.supabase.auth.getSession();\n * return session;\n * };\n *\n * return resolve(event, {\n * filterSerializedResponseHeaders(name) {\n * return name === 'content-range';\n * }\n * });\n * };\n * ```\n *\n * ### Types\n *\n * ```ts\n * import { SupabaseClient, Session } from '@supabase/supabase-js';\n *\n * declare global {\n * namespace App {\n * interface Locals {\n * supabase: SupabaseClient;\n * getSession(): Promise;\n * }\n * // interface PageData {}\n * // interface Error {}\n * // interface Platform {}\n * }\n * }\n *\n * export {};\n * ```\n */\nexport function createSupabaseServerClient<\n\tDatabase = any,\n\tSchemaName extends string & keyof Database = 'public' extends keyof Database\n\t\t? 'public'\n\t\t: string & keyof Database,\n\tSchema extends GenericSchema = Database[SchemaName] extends GenericSchema\n\t\t? Database[SchemaName]\n\t\t: any\n>({\n\tsupabaseUrl,\n\tsupabaseKey,\n\tevent,\n\toptions,\n\tcookieOptions,\n\texpiryMargin\n}: {\n\tsupabaseUrl: string;\n\tsupabaseKey: string;\n\tevent: Pick;\n\toptions?: SupabaseClientOptionsWithoutAuth;\n\tcookieOptions?: CookieOptionsWithName;\n\texpiryMargin?: number;\n}): SupabaseClient {\n\tconst client = createSupabaseClient(supabaseUrl, supabaseKey, {\n\t\t...options,\n\t\tglobal: {\n\t\t\t...options?.global,\n\t\t\theaders: {\n\t\t\t\t...options?.global?.headers,\n\t\t\t\t'X-Client-Info': `${PACKAGE_NAME}@${PACKAGE_VERSION}`\n\t\t\t}\n\t\t},\n\t\tauth: {\n\t\t\tstorageKey: cookieOptions?.name,\n\t\t\tstorage: new SvelteKitServerAuthStorageAdapter(event, cookieOptions, expiryMargin)\n\t\t}\n\t});\n\n\treturn client;\n}\n","import { CookieAuthStorageAdapter, CookieOptions } from '@supabase/auth-helpers-shared';\nimport { Session } from '@supabase/supabase-js';\nimport { RequestEvent } from '@sveltejs/kit';\n\nexport class SvelteKitServerAuthStorageAdapter extends CookieAuthStorageAdapter {\n\tprivate isInitialDelete = true;\n\tprivate currentSession: Partial | null = null;\n\n\tconstructor(\n\t\tprivate readonly event: Pick,\n\t\tcookieOptions?: CookieOptions,\n\t\tprivate readonly expiryMargin: number = 60\n\t) {\n\t\tsuper(cookieOptions);\n\t}\n\n\tprotected getCookie(name: string) {\n\t\treturn this.event.cookies.get(name);\n\t}\n\n\tprotected setCookie(name: string, value: string) {\n\t\tthis.event.cookies.set(name, value, {\n\t\t\thttpOnly: false,\n\t\t\t...this.cookieOptions\n\t\t});\n\t}\n\n\tprotected deleteCookie(name: string) {\n\t\tthis.event.cookies.delete(name, {\n\t\t\thttpOnly: false,\n\t\t\t...this.cookieOptions\n\t\t});\n\t}\n\n\tasync getItem(key: string) {\n\t\tconst sessionStr = await super.getItem(key);\n\t\tif (!sessionStr) {\n\t\t\tthis.currentSession = null;\n\t\t\treturn null;\n\t\t}\n\n\t\tconst session: Session | null = JSON.parse(sessionStr);\n\t\tthis.currentSession = session;\n\n\t\tif (session?.expires_at) {\n\t\t\t// shorten the session lifetime so it does not expire on the server\n\t\t\tsession.expires_at -= this.expiryMargin;\n\t\t}\n\t\treturn JSON.stringify(session);\n\t}\n\n\tremoveItem(key: string) {\n\t\tif (this.isInitialDelete && this.currentSession?.expires_at) {\n\t\t\tconst now = Math.round(Date.now() / 1000);\n\t\t\tif (this.currentSession.expires_at < now + 10) {\n\t\t\t\tthis.isInitialDelete = false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tsuper.removeItem(key);\n\t}\n}\n"],"mappings":";AAAA;AAAA,EAEC;AAAA,EACA,aAAAA;AAAA,OAEM;;;ACLP;AAAA,EACC;AAAA,EAEA;AAAA,OACM;AAGA,IAAM,kCAAN,cAA8C,gCAAgC;AAAA,EACpF,YACkB,gBAAgC,MACjD,eACC;AACD,UAAM,aAAa;AAHF;AAAA,EAIlB;AAAA,EAEA,QAAQ,KAAa;AACpB,QAAI,CAAC,UAAU,GAAG;AACjB,aAAO,KAAK,UAAU,KAAK,aAAa;AAAA,IACzC;AACA,WAAO,MAAM,QAAQ,GAAG;AAAA,EACzB;AACD;;;ADVA,IAAI;AAwCG,SAAS,yBAQd;AAAA,EACD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,GAaiD;AA/EjD;AAgF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,KAAK,MAAM,UAAU;AACrD,SAAK,iBAAiB;AAEtB,QAAI,mCAAS,YAAY;AAExB,cAAQ,cAAc,KAAK;AAAA,IAC5B;AACA,WAAO,KAAK,UAAU,OAAO;AAAA,EAC9B;AAAA,EAEA,WAAW,KAAa;AAnDzB;AAoDE,QAAI,KAAK,qBAAmB,UAAK,mBAAL,mBAAqB,aAAY;AAC5D,YAAM,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AACxC,UAAI,KAAK,eAAe,aAAa,MAAM,IAAI;AAC9C,aAAK,kBAAkB;AACvB;AAAA,MACD;AAAA,IACD;AACA,UAAM,WAAW,GAAG;AAAA,EACrB;AACD;;;ADAO,SAAS,2BAQd;AAAA,EACD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,GAOiD;AAnFjD;AAoFC,QAAM,SAASC,sBAAmD,aAAa,aAAa;AAAA,IAC3F,GAAG;AAAA,IACH,QAAQ;AAAA,MACP,GAAG,mCAAS;AAAA,MACZ,SAAS;AAAA,QACR,IAAG,wCAAS,WAAT,mBAAiB;AAAA,QACpB,iBAAiB,GAAG,sCAAgB;AAAA,MACrC;AAAA,IACD;AAAA,IACA,MAAM;AAAA,MACL,YAAY,+CAAe;AAAA,MAC3B,SAAS,IAAI,kCAAkC,OAAO,eAAe,YAAY;AAAA,IAClF;AAAA,EACD,CAAC;AAED,SAAO;AACR;","names":["isBrowser","isBrowser","createSupabaseClient","createSupabaseClient"]} \ No newline at end of file diff --git a/node_modules/@supabase/auth-helpers-sveltekit/package.json b/node_modules/@supabase/auth-helpers-sveltekit/package.json new file mode 100644 index 0000000..7127d9c --- /dev/null +++ b/node_modules/@supabase/auth-helpers-sveltekit/package.json @@ -0,0 +1,58 @@ +{ + "name": "@supabase/auth-helpers-sveltekit", + "version": "0.10.1", + "description": "A collection of framework specific Auth utilities for working with Supabase.", + "type": "module", + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "publishConfig": { + "access": "public" + }, + "exports": { + "./package.json": "./package.json", + ".": "./dist/index.js" + }, + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/supabase/auth-helpers.git" + }, + "keywords": [ + "Supabase", + "Auth", + "Svelte Kit", + "Svelte" + ], + "author": "Supabase", + "license": "MIT", + "bugs": { + "url": "https://github.com/supabase/auth-helpers/issues" + }, + "homepage": "https://github.com/supabase/auth-helpers/tree/main/packages/sveltekit#readme", + "devDependencies": { + "@supabase/supabase-js": "2.19.0", + "@sveltejs/kit": "1.15.4", + "svelte": "^3.54.0", + "vite": "^4.0.0", + "rimraf": "^4.1.1", + "tslib": "^2.4.0", + "typescript": "^4.7.4", + "tsup": "^6.5.0", + "tsconfig": "0.1.1" + }, + "dependencies": { + "@supabase/auth-helpers-shared": "0.4.1" + }, + "peerDependencies": { + "@sveltejs/kit": "^1.15.4", + "@supabase/supabase-js": "^2.19.0" + }, + "scripts": { + "lint": "tsc", + "build": "tsup", + "clean:all": "rimraf dist node_modules" + } +} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/LICENSE b/node_modules/@supabase/functions-js/LICENSE new file mode 100644 index 0000000..ddeba6a --- /dev/null +++ b/node_modules/@supabase/functions-js/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Supabase + +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/@supabase/functions-js/README.md b/node_modules/@supabase/functions-js/README.md new file mode 100644 index 0000000..600beb1 --- /dev/null +++ b/node_modules/@supabase/functions-js/README.md @@ -0,0 +1,22 @@ +# `functions-js` + +[![Coverage Status](https://coveralls.io/repos/github/supabase/functions-js/badge.svg?branch=main)](https://coveralls.io/github/supabase/functions-js?branch=main) + +JS Client library to interact with Supabase Functions. + +## Docs + + + +## testing + +To run tests you will need Node 18+. + +You are going to need docker daemon running to execute tests. + +To start test run use the following command: + +```sh +npm i +npm run test +``` diff --git a/node_modules/@supabase/functions-js/dist/main/FunctionsClient.d.ts b/node_modules/@supabase/functions-js/dist/main/FunctionsClient.d.ts new file mode 100644 index 0000000..b8a6f17 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/FunctionsClient.d.ts @@ -0,0 +1,22 @@ +import { Fetch, FunctionsResponse, FunctionInvokeOptions } from './types'; +export declare class FunctionsClient { + protected url: string; + protected headers: Record; + protected fetch: Fetch; + constructor(url: string, { headers, customFetch, }?: { + headers?: Record; + customFetch?: Fetch; + }); + /** + * Updates the authorization header + * @param token - the new jwt token sent in the authorisation header + */ + setAuth(token: string): void; + /** + * Invokes a function + * @param functionName - The name of the Function to invoke. + * @param options - Options for invoking the Function. + */ + invoke(functionName: string, options?: FunctionInvokeOptions): Promise>; +} +//# sourceMappingURL=FunctionsClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/FunctionsClient.d.ts.map b/node_modules/@supabase/functions-js/dist/main/FunctionsClient.d.ts.map new file mode 100644 index 0000000..287861c --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/FunctionsClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"FunctionsClient.d.ts","sourceRoot":"","sources":["../../src/FunctionsClient.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,EAIL,iBAAiB,EACjB,qBAAqB,EACtB,MAAM,SAAS,CAAA;AAEhB,qBAAa,eAAe;IAC1B,SAAS,CAAC,GAAG,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IACzC,SAAS,CAAC,KAAK,EAAE,KAAK,CAAA;gBAGpB,GAAG,EAAE,MAAM,EACX,EACE,OAAY,EACZ,WAAW,GACZ,GAAE;QACD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QAChC,WAAW,CAAC,EAAE,KAAK,CAAA;KACf;IAOR;;;OAGG;IACH,OAAO,CAAC,KAAK,EAAE,MAAM;IAIrB;;;;OAIG;IACG,MAAM,CAAC,CAAC,GAAG,GAAG,EAClB,YAAY,EAAE,MAAM,EACpB,OAAO,GAAE,qBAA0B,GAClC,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC;CAwEjC"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/FunctionsClient.js b/node_modules/@supabase/functions-js/dist/main/FunctionsClient.js new file mode 100644 index 0000000..834b25e --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/FunctionsClient.js @@ -0,0 +1,107 @@ +"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 }); +exports.FunctionsClient = void 0; +const helper_1 = require("./helper"); +const types_1 = require("./types"); +class FunctionsClient { + constructor(url, { headers = {}, customFetch, } = {}) { + this.url = url; + this.headers = headers; + this.fetch = (0, helper_1.resolveFetch)(customFetch); + } + /** + * Updates the authorization header + * @param token - the new jwt token sent in the authorisation header + */ + setAuth(token) { + this.headers.Authorization = `Bearer ${token}`; + } + /** + * Invokes a function + * @param functionName - The name of the Function to invoke. + * @param options - Options for invoking the Function. + */ + invoke(functionName, options = {}) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + try { + const { headers, method, body: functionArgs } = options; + let _headers = {}; + let body; + if (functionArgs && + ((headers && !Object.prototype.hasOwnProperty.call(headers, 'Content-Type')) || !headers)) { + if ((typeof Blob !== 'undefined' && functionArgs instanceof Blob) || + functionArgs instanceof ArrayBuffer) { + // will work for File as File inherits Blob + // also works for ArrayBuffer as it is the same underlying structure as a Blob + _headers['Content-Type'] = 'application/octet-stream'; + body = functionArgs; + } + else if (typeof functionArgs === 'string') { + // plain string + _headers['Content-Type'] = 'text/plain'; + body = functionArgs; + } + else if (typeof FormData !== 'undefined' && functionArgs instanceof FormData) { + // don't set content-type headers + // Request will automatically add the right boundary value + body = functionArgs; + } + else { + // default, assume this is JSON + _headers['Content-Type'] = 'application/json'; + body = JSON.stringify(functionArgs); + } + } + const response = yield this.fetch(`${this.url}/${functionName}`, { + method: method || 'POST', + // headers priority is (high to low): + // 1. invoke-level headers + // 2. client-level headers + // 3. default Content-Type header + headers: Object.assign(Object.assign(Object.assign({}, _headers), this.headers), headers), + body, + }).catch((fetchError) => { + throw new types_1.FunctionsFetchError(fetchError); + }); + const isRelayError = response.headers.get('x-relay-error'); + if (isRelayError && isRelayError === 'true') { + throw new types_1.FunctionsRelayError(response); + } + if (!response.ok) { + throw new types_1.FunctionsHttpError(response); + } + let responseType = ((_a = response.headers.get('Content-Type')) !== null && _a !== void 0 ? _a : 'text/plain').split(';')[0].trim(); + let data; + if (responseType === 'application/json') { + data = yield response.json(); + } + else if (responseType === 'application/octet-stream') { + data = yield response.blob(); + } + else if (responseType === 'multipart/form-data') { + data = yield response.formData(); + } + else { + // default to text + data = yield response.text(); + } + return { data, error: null }; + } + catch (error) { + return { data: null, error }; + } + }); + } +} +exports.FunctionsClient = FunctionsClient; +//# sourceMappingURL=FunctionsClient.js.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/FunctionsClient.js.map b/node_modules/@supabase/functions-js/dist/main/FunctionsClient.js.map new file mode 100644 index 0000000..bf4467c --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/FunctionsClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FunctionsClient.js","sourceRoot":"","sources":["../../src/FunctionsClient.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,qCAAuC;AACvC,mCAOgB;AAEhB,MAAa,eAAe;IAK1B,YACE,GAAW,EACX,EACE,OAAO,GAAG,EAAE,EACZ,WAAW,MAIT,EAAE;QAEN,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,KAAK,GAAG,IAAA,qBAAY,EAAC,WAAW,CAAC,CAAA;IACxC,CAAC;IAED;;;OAGG;IACH,OAAO,CAAC,KAAa;QACnB,IAAI,CAAC,OAAO,CAAC,aAAa,GAAG,UAAU,KAAK,EAAE,CAAA;IAChD,CAAC;IAED;;;;OAIG;IACG,MAAM,CACV,YAAoB,EACpB,UAAiC,EAAE;;;YAEnC,IAAI;gBACF,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,EAAE,GAAG,OAAO,CAAA;gBAEvD,IAAI,QAAQ,GAA2B,EAAE,CAAA;gBACzC,IAAI,IAAS,CAAA;gBACb,IACE,YAAY;oBACZ,CAAC,CAAC,OAAO,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC,IAAI,C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MAAM,EAAE;oBAC3C,MAAM,IAAI,2BAAmB,CAAC,QAAQ,CAAC,CAAA;iBACxC;gBAED,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;oBAChB,MAAM,IAAI,0BAAkB,CAAC,QAAQ,CAAC,CAAA;iBACvC;gBAED,IAAI,YAAY,GAAG,CAAC,MAAA,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,mCAAI,YAAY,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;gBAC9F,IAAI,IAAS,CAAA;gBACb,IAAI,YAAY,KAAK,kBAAkB,EAAE;oBACvC,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;iBAC7B;qBAAM,IAAI,YAAY,KAAK,0BAA0B,EAAE;oBACtD,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;iBAC7B;qBAAM,IAAI,YAAY,KAAK,qBAAqB,EAAE;oBACjD,IAAI,GAAG,MAAM,QAAQ,CAAC,QAAQ,EAAE,CAAA;iBACjC;qBAAM;oBACL,kBAAkB;oBAClB,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;iBAC7B;gBAED,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;aAC7B;YAAC,OAAO,KAAK,EAAE;gBACd,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;aAC7B;;KACF;CACF;AA5GD,0CA4GC"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/helper.d.ts b/node_modules/@supabase/functions-js/dist/main/helper.d.ts new file mode 100644 index 0000000..b697a98 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/helper.d.ts @@ -0,0 +1,3 @@ +import { Fetch } from './types'; +export declare const resolveFetch: (customFetch?: Fetch) => Fetch; +//# sourceMappingURL=helper.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/helper.d.ts.map b/node_modules/@supabase/functions-js/dist/main/helper.d.ts.map new file mode 100644 index 0000000..3a09a46 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/helper.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helper.d.ts","sourceRoot":"","sources":["../../src/helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAE/B,eAAO,MAAM,YAAY,iBAAkB,KAAK,KAAG,KAUlD,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/helper.js b/node_modules/@supabase/functions-js/dist/main/helper.js new file mode 100644 index 0000000..3732002 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/helper.js @@ -0,0 +1,50 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +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 }); +exports.resolveFetch = void 0; +const resolveFetch = (customFetch) => { + let _fetch; + if (customFetch) { + _fetch = customFetch; + } + else if (typeof fetch === 'undefined') { + _fetch = (...args) => __awaiter(void 0, void 0, void 0, function* () { return yield (yield Promise.resolve().then(() => __importStar(require('cross-fetch')))).fetch(...args); }); + } + else { + _fetch = fetch; + } + return (...args) => _fetch(...args); +}; +exports.resolveFetch = resolveFetch; +//# sourceMappingURL=helper.js.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/helper.js.map b/node_modules/@supabase/functions-js/dist/main/helper.js.map new file mode 100644 index 0000000..e8cef48 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/helper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helper.js","sourceRoot":"","sources":["../../src/helper.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEO,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAS,EAAE;IACzD,IAAI,MAAa,CAAA;IACjB,IAAI,WAAW,EAAE;QACf,MAAM,GAAG,WAAW,CAAA;KACrB;SAAM,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;QACvC,MAAM,GAAG,CAAO,GAAG,IAAI,EAAE,EAAE,kDAAC,OAAA,MAAM,CAAC,wDAAa,aAAa,GAAC,CAAC,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAA,GAAA,CAAA;KAC/E;SAAM;QACL,MAAM,GAAG,KAAK,CAAA;KACf;IACD,OAAO,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA;AAVY,QAAA,YAAY,gBAUxB"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/index.d.ts b/node_modules/@supabase/functions-js/dist/main/index.d.ts new file mode 100644 index 0000000..9c13b87 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/index.d.ts @@ -0,0 +1,3 @@ +export { FunctionsClient } from './FunctionsClient'; +export { FunctionInvokeOptions, FunctionsError, FunctionsFetchError, FunctionsHttpError, FunctionsRelayError, FunctionsResponse, } from './types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/index.d.ts.map b/node_modules/@supabase/functions-js/dist/main/index.d.ts.map new file mode 100644 index 0000000..4a26c16 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACnD,OAAO,EACL,qBAAqB,EACrB,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,SAAS,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/index.js b/node_modules/@supabase/functions-js/dist/main/index.js new file mode 100644 index 0000000..abf745c --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/index.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FunctionsRelayError = exports.FunctionsHttpError = exports.FunctionsFetchError = exports.FunctionsError = exports.FunctionsClient = void 0; +var FunctionsClient_1 = require("./FunctionsClient"); +Object.defineProperty(exports, "FunctionsClient", { enumerable: true, get: function () { return FunctionsClient_1.FunctionsClient; } }); +var types_1 = require("./types"); +Object.defineProperty(exports, "FunctionsError", { enumerable: true, get: function () { return types_1.FunctionsError; } }); +Object.defineProperty(exports, "FunctionsFetchError", { enumerable: true, get: function () { return types_1.FunctionsFetchError; } }); +Object.defineProperty(exports, "FunctionsHttpError", { enumerable: true, get: function () { return types_1.FunctionsHttpError; } }); +Object.defineProperty(exports, "FunctionsRelayError", { enumerable: true, get: function () { return types_1.FunctionsRelayError; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/index.js.map b/node_modules/@supabase/functions-js/dist/main/index.js.map new file mode 100644 index 0000000..61f2960 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,qDAAmD;AAA1C,kHAAA,eAAe,OAAA;AACxB,iCAOgB;AALd,uGAAA,cAAc,OAAA;AACd,4GAAA,mBAAmB,OAAA;AACnB,2GAAA,kBAAkB,OAAA;AAClB,4GAAA,mBAAmB,OAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/types.d.ts b/node_modules/@supabase/functions-js/dist/main/types.d.ts new file mode 100644 index 0000000..cecb073 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/types.d.ts @@ -0,0 +1,44 @@ +export declare type Fetch = typeof fetch; +/** + * Response format + * + */ +export interface FunctionsResponseSuccess { + data: T; + error: null; +} +export interface FunctionsResponseFailure { + data: null; + error: any; +} +export declare type FunctionsResponse = FunctionsResponseSuccess | FunctionsResponseFailure; +export declare class FunctionsError extends Error { + context: any; + constructor(message: string, name?: string, context?: any); +} +export declare class FunctionsFetchError extends FunctionsError { + constructor(context: any); +} +export declare class FunctionsRelayError extends FunctionsError { + constructor(context: any); +} +export declare class FunctionsHttpError extends FunctionsError { + constructor(context: any); +} +export declare type FunctionInvokeOptions = { + /** + * Object representing the headers to send with the request. + * */ + headers?: { + [key: string]: string; + }; + /** + * The HTTP verb of the request + */ + method?: 'POST' | 'GET' | 'PUT' | 'PATCH' | 'DELETE'; + /** + * The body of the request. + */ + body?: File | Blob | ArrayBuffer | FormData | ReadableStream | Record | string; +}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/types.d.ts.map b/node_modules/@supabase/functions-js/dist/main/types.d.ts.map new file mode 100644 index 0000000..8da417b --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,oBAAY,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC;;;GAGG;AACH,MAAM,WAAW,wBAAwB,CAAC,CAAC;IACzC,IAAI,EAAE,CAAC,CAAA;IACP,KAAK,EAAE,IAAI,CAAA;CACZ;AACD,MAAM,WAAW,wBAAwB;IACvC,IAAI,EAAE,IAAI,CAAA;IACV,KAAK,EAAE,GAAG,CAAA;CACX;AACD,oBAAY,iBAAiB,CAAC,CAAC,IAAI,wBAAwB,CAAC,CAAC,CAAC,GAAG,wBAAwB,CAAA;AAEzF,qBAAa,cAAe,SAAQ,KAAK;IACvC,OAAO,EAAE,GAAG,CAAA;gBACA,OAAO,EAAE,MAAM,EAAE,IAAI,SAAmB,EAAE,OAAO,CAAC,EAAE,GAAG;CAKpE;AAED,qBAAa,mBAAoB,SAAQ,cAAc;gBACzC,OAAO,EAAE,GAAG;CAGzB;AAED,qBAAa,mBAAoB,SAAQ,cAAc;gBACzC,OAAO,EAAE,GAAG;CAGzB;AAED,qBAAa,kBAAmB,SAAQ,cAAc;gBACxC,OAAO,EAAE,GAAG;CAGzB;AAED,oBAAY,qBAAqB,GAAG;IAClC;;SAEK;IACL,OAAO,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAA;IACnC;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,KAAK,GAAG,OAAO,GAAG,QAAQ,CAAA;IACpD;;OAEG;IACH,IAAI,CAAC,EACD,IAAI,GACJ,IAAI,GACJ,WAAW,GACX,QAAQ,GACR,cAAc,CAAC,UAAU,CAAC,GAC1B,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GACnB,MAAM,CAAA;CACX,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/types.js b/node_modules/@supabase/functions-js/dist/main/types.js new file mode 100644 index 0000000..9d3bed4 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/types.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FunctionsHttpError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsError = void 0; +class FunctionsError extends Error { + constructor(message, name = 'FunctionsError', context) { + super(message); + this.name = name; + this.context = context; + } +} +exports.FunctionsError = FunctionsError; +class FunctionsFetchError extends FunctionsError { + constructor(context) { + super('Failed to send a request to the Edge Function', 'FunctionsFetchError', context); + } +} +exports.FunctionsFetchError = FunctionsFetchError; +class FunctionsRelayError extends FunctionsError { + constructor(context) { + super('Relay Error invoking the Edge Function', 'FunctionsRelayError', context); + } +} +exports.FunctionsRelayError = FunctionsRelayError; +class FunctionsHttpError extends FunctionsError { + constructor(context) { + super('Edge Function returned a non-2xx status code', 'FunctionsHttpError', context); + } +} +exports.FunctionsHttpError = FunctionsHttpError; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/types.js.map b/node_modules/@supabase/functions-js/dist/main/types.js.map new file mode 100644 index 0000000..c4bc4d0 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";;;AAgBA,MAAa,cAAe,SAAQ,KAAK;IAEvC,YAAY,OAAe,EAAE,IAAI,GAAG,gBAAgB,EAAE,OAAa;QACjE,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;CACF;AAPD,wCAOC;AAED,MAAa,mBAAoB,SAAQ,cAAc;IACrD,YAAY,OAAY;QACtB,KAAK,CAAC,+CAA+C,EAAE,qBAAqB,EAAE,OAAO,CAAC,CAAA;IACxF,CAAC;CACF;AAJD,kDAIC;AAED,MAAa,mBAAoB,SAAQ,cAAc;IACrD,YAAY,OAAY;QACtB,KAAK,CAAC,wCAAwC,EAAE,qBAAqB,EAAE,OAAO,CAAC,CAAA;IACjF,CAAC;CACF;AAJD,kDAIC;AAED,MAAa,kBAAmB,SAAQ,cAAc;IACpD,YAAY,OAAY;QACtB,KAAK,CAAC,8CAA8C,EAAE,oBAAoB,EAAE,OAAO,CAAC,CAAA;IACtF,CAAC;CACF;AAJD,gDAIC"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/version.d.ts b/node_modules/@supabase/functions-js/dist/main/version.d.ts new file mode 100644 index 0000000..8ea0d47 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.1.2"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/version.d.ts.map b/node_modules/@supabase/functions-js/dist/main/version.d.ts.map new file mode 100644 index 0000000..1f88a46 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,oBAAoB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/version.js b/node_modules/@supabase/functions-js/dist/main/version.js new file mode 100644 index 0000000..771c0db --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/version.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.version = void 0; +exports.version = '2.1.2'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/main/version.js.map b/node_modules/@supabase/functions-js/dist/main/version.js.map new file mode 100644 index 0000000..bf41d70 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/main/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";;;AAAa,QAAA,OAAO,GAAG,iBAAiB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/FunctionsClient.d.ts b/node_modules/@supabase/functions-js/dist/module/FunctionsClient.d.ts new file mode 100644 index 0000000..b8a6f17 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/FunctionsClient.d.ts @@ -0,0 +1,22 @@ +import { Fetch, FunctionsResponse, FunctionInvokeOptions } from './types'; +export declare class FunctionsClient { + protected url: string; + protected headers: Record; + protected fetch: Fetch; + constructor(url: string, { headers, customFetch, }?: { + headers?: Record; + customFetch?: Fetch; + }); + /** + * Updates the authorization header + * @param token - the new jwt token sent in the authorisation header + */ + setAuth(token: string): void; + /** + * Invokes a function + * @param functionName - The name of the Function to invoke. + * @param options - Options for invoking the Function. + */ + invoke(functionName: string, options?: FunctionInvokeOptions): Promise>; +} +//# sourceMappingURL=FunctionsClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/FunctionsClient.d.ts.map b/node_modules/@supabase/functions-js/dist/module/FunctionsClient.d.ts.map new file mode 100644 index 0000000..287861c --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/FunctionsClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"FunctionsClient.d.ts","sourceRoot":"","sources":["../../src/FunctionsClient.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,EAIL,iBAAiB,EACjB,qBAAqB,EACtB,MAAM,SAAS,CAAA;AAEhB,qBAAa,eAAe;IAC1B,SAAS,CAAC,GAAG,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IACzC,SAAS,CAAC,KAAK,EAAE,KAAK,CAAA;gBAGpB,GAAG,EAAE,MAAM,EACX,EACE,OAAY,EACZ,WAAW,GACZ,GAAE;QACD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QAChC,WAAW,CAAC,EAAE,KAAK,CAAA;KACf;IAOR;;;OAGG;IACH,OAAO,CAAC,KAAK,EAAE,MAAM;IAIrB;;;;OAIG;IACG,MAAM,CAAC,CAAC,GAAG,GAAG,EAClB,YAAY,EAAE,MAAM,EACpB,OAAO,GAAE,qBAA0B,GAClC,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC;CAwEjC"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/FunctionsClient.js b/node_modules/@supabase/functions-js/dist/module/FunctionsClient.js new file mode 100644 index 0000000..18f3132 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/FunctionsClient.js @@ -0,0 +1,103 @@ +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 { resolveFetch } from './helper'; +import { FunctionsFetchError, FunctionsHttpError, FunctionsRelayError, } from './types'; +export class FunctionsClient { + constructor(url, { headers = {}, customFetch, } = {}) { + this.url = url; + this.headers = headers; + this.fetch = resolveFetch(customFetch); + } + /** + * Updates the authorization header + * @param token - the new jwt token sent in the authorisation header + */ + setAuth(token) { + this.headers.Authorization = `Bearer ${token}`; + } + /** + * Invokes a function + * @param functionName - The name of the Function to invoke. + * @param options - Options for invoking the Function. + */ + invoke(functionName, options = {}) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + try { + const { headers, method, body: functionArgs } = options; + let _headers = {}; + let body; + if (functionArgs && + ((headers && !Object.prototype.hasOwnProperty.call(headers, 'Content-Type')) || !headers)) { + if ((typeof Blob !== 'undefined' && functionArgs instanceof Blob) || + functionArgs instanceof ArrayBuffer) { + // will work for File as File inherits Blob + // also works for ArrayBuffer as it is the same underlying structure as a Blob + _headers['Content-Type'] = 'application/octet-stream'; + body = functionArgs; + } + else if (typeof functionArgs === 'string') { + // plain string + _headers['Content-Type'] = 'text/plain'; + body = functionArgs; + } + else if (typeof FormData !== 'undefined' && functionArgs instanceof FormData) { + // don't set content-type headers + // Request will automatically add the right boundary value + body = functionArgs; + } + else { + // default, assume this is JSON + _headers['Content-Type'] = 'application/json'; + body = JSON.stringify(functionArgs); + } + } + const response = yield this.fetch(`${this.url}/${functionName}`, { + method: method || 'POST', + // headers priority is (high to low): + // 1. invoke-level headers + // 2. client-level headers + // 3. default Content-Type header + headers: Object.assign(Object.assign(Object.assign({}, _headers), this.headers), headers), + body, + }).catch((fetchError) => { + throw new FunctionsFetchError(fetchError); + }); + const isRelayError = response.headers.get('x-relay-error'); + if (isRelayError && isRelayError === 'true') { + throw new FunctionsRelayError(response); + } + if (!response.ok) { + throw new FunctionsHttpError(response); + } + let responseType = ((_a = response.headers.get('Content-Type')) !== null && _a !== void 0 ? _a : 'text/plain').split(';')[0].trim(); + let data; + if (responseType === 'application/json') { + data = yield response.json(); + } + else if (responseType === 'application/octet-stream') { + data = yield response.blob(); + } + else if (responseType === 'multipart/form-data') { + data = yield response.formData(); + } + else { + // default to text + data = yield response.text(); + } + return { data, error: null }; + } + catch (error) { + return { data: null, error }; + } + }); + } +} +//# sourceMappingURL=FunctionsClient.js.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/FunctionsClient.js.map b/node_modules/@supabase/functions-js/dist/module/FunctionsClient.js.map new file mode 100644 index 0000000..06cb2f6 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/F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AAI,YAAY,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;gBAC9F,IAAI,IAAS,CAAA;gBACb,IAAI,YAAY,KAAK,kBAAkB,EAAE;oBACvC,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;iBAC7B;qBAAM,IAAI,YAAY,KAAK,0BAA0B,EAAE;oBACtD,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;iBAC7B;qBAAM,IAAI,YAAY,KAAK,qBAAqB,EAAE;oBACjD,IAAI,GAAG,MAAM,QAAQ,CAAC,QAAQ,EAAE,CAAA;iBACjC;qBAAM;oBACL,kBAAkB;oBAClB,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;iBAC7B;gBAED,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;aAC7B;YAAC,OAAO,KAAK,EAAE;gBACd,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;aAC7B;;KACF;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/helper.d.ts b/node_modules/@supabase/functions-js/dist/module/helper.d.ts new file mode 100644 index 0000000..b697a98 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/helper.d.ts @@ -0,0 +1,3 @@ +import { Fetch } from './types'; +export declare const resolveFetch: (customFetch?: Fetch) => Fetch; +//# sourceMappingURL=helper.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/helper.d.ts.map b/node_modules/@supabase/functions-js/dist/module/helper.d.ts.map new file mode 100644 index 0000000..3a09a46 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/helper.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helper.d.ts","sourceRoot":"","sources":["../../src/helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAE/B,eAAO,MAAM,YAAY,iBAAkB,KAAK,KAAG,KAUlD,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/helper.js b/node_modules/@supabase/functions-js/dist/module/helper.js new file mode 100644 index 0000000..c408229 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/helper.js @@ -0,0 +1,23 @@ +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()); + }); +}; +export const resolveFetch = (customFetch) => { + let _fetch; + if (customFetch) { + _fetch = customFetch; + } + else if (typeof fetch === 'undefined') { + _fetch = (...args) => __awaiter(void 0, void 0, void 0, function* () { return yield (yield import('cross-fetch')).fetch(...args); }); + } + else { + _fetch = fetch; + } + return (...args) => _fetch(...args); +}; +//# sourceMappingURL=helper.js.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/helper.js.map b/node_modules/@supabase/functions-js/dist/module/helper.js.map new file mode 100644 index 0000000..bcc967a --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/helper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helper.js","sourceRoot":"","sources":["../../src/helper.ts"],"names":[],"mappings":";;;;;;;;;AAEA,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAS,EAAE;IACzD,IAAI,MAAa,CAAA;IACjB,IAAI,WAAW,EAAE;QACf,MAAM,GAAG,WAAW,CAAA;KACrB;SAAM,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;QACvC,MAAM,GAAG,CAAO,GAAG,IAAI,EAAE,EAAE,kDAAC,OAAA,MAAM,CAAC,MAAM,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAA,GAAA,CAAA;KAC/E;SAAM;QACL,MAAM,GAAG,KAAK,CAAA;KACf;IACD,OAAO,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/index.d.ts b/node_modules/@supabase/functions-js/dist/module/index.d.ts new file mode 100644 index 0000000..9c13b87 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/index.d.ts @@ -0,0 +1,3 @@ +export { FunctionsClient } from './FunctionsClient'; +export { FunctionInvokeOptions, FunctionsError, FunctionsFetchError, FunctionsHttpError, FunctionsRelayError, FunctionsResponse, } from './types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/index.d.ts.map b/node_modules/@supabase/functions-js/dist/module/index.d.ts.map new file mode 100644 index 0000000..4a26c16 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACnD,OAAO,EACL,qBAAqB,EACrB,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,SAAS,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/index.js b/node_modules/@supabase/functions-js/dist/module/index.js new file mode 100644 index 0000000..6492e5d --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/index.js @@ -0,0 +1,3 @@ +export { FunctionsClient } from './FunctionsClient'; +export { FunctionsError, FunctionsFetchError, FunctionsHttpError, FunctionsRelayError, } from './types'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/index.js.map b/node_modules/@supabase/functions-js/dist/module/index.js.map new file mode 100644 index 0000000..aef058e --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACnD,OAAO,EAEL,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,GAEpB,MAAM,SAAS,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/types.d.ts b/node_modules/@supabase/functions-js/dist/module/types.d.ts new file mode 100644 index 0000000..cecb073 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/types.d.ts @@ -0,0 +1,44 @@ +export declare type Fetch = typeof fetch; +/** + * Response format + * + */ +export interface FunctionsResponseSuccess { + data: T; + error: null; +} +export interface FunctionsResponseFailure { + data: null; + error: any; +} +export declare type FunctionsResponse = FunctionsResponseSuccess | FunctionsResponseFailure; +export declare class FunctionsError extends Error { + context: any; + constructor(message: string, name?: string, context?: any); +} +export declare class FunctionsFetchError extends FunctionsError { + constructor(context: any); +} +export declare class FunctionsRelayError extends FunctionsError { + constructor(context: any); +} +export declare class FunctionsHttpError extends FunctionsError { + constructor(context: any); +} +export declare type FunctionInvokeOptions = { + /** + * Object representing the headers to send with the request. + * */ + headers?: { + [key: string]: string; + }; + /** + * The HTTP verb of the request + */ + method?: 'POST' | 'GET' | 'PUT' | 'PATCH' | 'DELETE'; + /** + * The body of the request. + */ + body?: File | Blob | ArrayBuffer | FormData | ReadableStream | Record | string; +}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/types.d.ts.map b/node_modules/@supabase/functions-js/dist/module/types.d.ts.map new file mode 100644 index 0000000..8da417b --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,oBAAY,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC;;;GAGG;AACH,MAAM,WAAW,wBAAwB,CAAC,CAAC;IACzC,IAAI,EAAE,CAAC,CAAA;IACP,KAAK,EAAE,IAAI,CAAA;CACZ;AACD,MAAM,WAAW,wBAAwB;IACvC,IAAI,EAAE,IAAI,CAAA;IACV,KAAK,EAAE,GAAG,CAAA;CACX;AACD,oBAAY,iBAAiB,CAAC,CAAC,IAAI,wBAAwB,CAAC,CAAC,CAAC,GAAG,wBAAwB,CAAA;AAEzF,qBAAa,cAAe,SAAQ,KAAK;IACvC,OAAO,EAAE,GAAG,CAAA;gBACA,OAAO,EAAE,MAAM,EAAE,IAAI,SAAmB,EAAE,OAAO,CAAC,EAAE,GAAG;CAKpE;AAED,qBAAa,mBAAoB,SAAQ,cAAc;gBACzC,OAAO,EAAE,GAAG;CAGzB;AAED,qBAAa,mBAAoB,SAAQ,cAAc;gBACzC,OAAO,EAAE,GAAG;CAGzB;AAED,qBAAa,kBAAmB,SAAQ,cAAc;gBACxC,OAAO,EAAE,GAAG;CAGzB;AAED,oBAAY,qBAAqB,GAAG;IAClC;;SAEK;IACL,OAAO,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAA;IACnC;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,KAAK,GAAG,OAAO,GAAG,QAAQ,CAAA;IACpD;;OAEG;IACH,IAAI,CAAC,EACD,IAAI,GACJ,IAAI,GACJ,WAAW,GACX,QAAQ,GACR,cAAc,CAAC,UAAU,CAAC,GAC1B,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GACnB,MAAM,CAAA;CACX,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/types.js b/node_modules/@supabase/functions-js/dist/module/types.js new file mode 100644 index 0000000..f13e8d9 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/types.js @@ -0,0 +1,23 @@ +export class FunctionsError extends Error { + constructor(message, name = 'FunctionsError', context) { + super(message); + this.name = name; + this.context = context; + } +} +export class FunctionsFetchError extends FunctionsError { + constructor(context) { + super('Failed to send a request to the Edge Function', 'FunctionsFetchError', context); + } +} +export class FunctionsRelayError extends FunctionsError { + constructor(context) { + super('Relay Error invoking the Edge Function', 'FunctionsRelayError', context); + } +} +export class FunctionsHttpError extends FunctionsError { + constructor(context) { + super('Edge Function returned a non-2xx status code', 'FunctionsHttpError', context); + } +} +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/types.js.map b/node_modules/@supabase/functions-js/dist/module/types.js.map new file mode 100644 index 0000000..3b61afd --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAgBA,MAAM,OAAO,cAAe,SAAQ,KAAK;IAEvC,YAAY,OAAe,EAAE,IAAI,GAAG,gBAAgB,EAAE,OAAa;QACjE,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;CACF;AAED,MAAM,OAAO,mBAAoB,SAAQ,cAAc;IACrD,YAAY,OAAY;QACtB,KAAK,CAAC,+CAA+C,EAAE,qBAAqB,EAAE,OAAO,CAAC,CAAA;IACxF,CAAC;CACF;AAED,MAAM,OAAO,mBAAoB,SAAQ,cAAc;IACrD,YAAY,OAAY;QACtB,KAAK,CAAC,wCAAwC,EAAE,qBAAqB,EAAE,OAAO,CAAC,CAAA;IACjF,CAAC;CACF;AAED,MAAM,OAAO,kBAAmB,SAAQ,cAAc;IACpD,YAAY,OAAY;QACtB,KAAK,CAAC,8CAA8C,EAAE,oBAAoB,EAAE,OAAO,CAAC,CAAA;IACtF,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/version.d.ts b/node_modules/@supabase/functions-js/dist/module/version.d.ts new file mode 100644 index 0000000..8ea0d47 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.1.2"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/version.d.ts.map b/node_modules/@supabase/functions-js/dist/module/version.d.ts.map new file mode 100644 index 0000000..1f88a46 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,oBAAoB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/version.js b/node_modules/@supabase/functions-js/dist/module/version.js new file mode 100644 index 0000000..dc82cf6 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/version.js @@ -0,0 +1,2 @@ +export const version = '2.1.2'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/dist/module/version.js.map b/node_modules/@supabase/functions-js/dist/module/version.js.map new file mode 100644 index 0000000..c32bfe4 --- /dev/null +++ b/node_modules/@supabase/functions-js/dist/module/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,iBAAiB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/functions-js/package.json b/node_modules/@supabase/functions-js/package.json new file mode 100644 index 0000000..3f9f8fa --- /dev/null +++ b/node_modules/@supabase/functions-js/package.json @@ -0,0 +1,64 @@ +{ + "name": "@supabase/functions-js", + "version": "2.1.2", + "description": "JS Client library to interact with Supabase Functions.", + "main": "dist/main/index.js", + "module": "dist/module/index.js", + "types": "dist/module/index.d.ts", + "sideEffects": false, + "scripts": { + "clean": "rimraf dist docs/v2", + "format": "prettier --write \"{src,test}/**/*.ts\"", + "build": "run-s clean format build:*", + "build:main": "tsc -p tsconfig.json", + "build:module": "tsc -p tsconfig.module.json", + "docs": "typedoc src/index.ts --out docs/v2", + "docs:json": "typedoc --json docs/v2/spec.json --excludeExternals src/index.ts", + "test": "jest", + "test:coverage": "jest --coverage" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/supabase/functions-js.git" + }, + "keywords": [ + "functions", + "supabase" + ], + "author": "Supabase", + "files": [ + "dist", + "src" + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/supabase/functions-js/issues" + }, + "homepage": "https://github.com/supabase/functions-js#readme", + "dependencies": { + "cross-fetch": "^3.1.5" + }, + "devDependencies": { + "@types/jest": "^28.1.0", + "@types/jsonwebtoken": "^8.5.8", + "@types/node": "^18.7.0", + "genversion": "^3.0.2", + "jest": "^28.1.0", + "jsonwebtoken": "^9.0.0", + "nanoid": "^3.3.1", + "npm-run-all": "^4.1.5", + "prettier": "^2.6.0", + "rimraf": "^3.0.2", + "semantic-release": "^19.0.2", + "semantic-release-plugin-update-version-in-files": "^1.1.0", + "testcontainers": "^8.5.1", + "ts-jest": "^28.0.0", + "ts-node": "^10.9.0", + "ts-test-decorators": "^0.0.6", + "typedoc": "^0.22.13", + "typescript": "^4.6.2" + }, + "publishConfig": { + "access": "public" + } +} diff --git a/node_modules/@supabase/functions-js/src/FunctionsClient.ts b/node_modules/@supabase/functions-js/src/FunctionsClient.ts new file mode 100644 index 0000000..79968b5 --- /dev/null +++ b/node_modules/@supabase/functions-js/src/FunctionsClient.ts @@ -0,0 +1,119 @@ +import { resolveFetch } from './helper' +import { + Fetch, + FunctionsFetchError, + FunctionsHttpError, + FunctionsRelayError, + FunctionsResponse, + FunctionInvokeOptions, +} from './types' + +export class FunctionsClient { + protected url: string + protected headers: Record + protected fetch: Fetch + + constructor( + url: string, + { + headers = {}, + customFetch, + }: { + headers?: Record + customFetch?: Fetch + } = {} + ) { + this.url = url + this.headers = headers + this.fetch = resolveFetch(customFetch) + } + + /** + * Updates the authorization header + * @param token - the new jwt token sent in the authorisation header + */ + setAuth(token: string) { + this.headers.Authorization = `Bearer ${token}` + } + + /** + * Invokes a function + * @param functionName - The name of the Function to invoke. + * @param options - Options for invoking the Function. + */ + async invoke( + functionName: string, + options: FunctionInvokeOptions = {} + ): Promise> { + try { + const { headers, method, body: functionArgs } = options + + let _headers: Record = {} + let body: any + if ( + functionArgs && + ((headers && !Object.prototype.hasOwnProperty.call(headers, 'Content-Type')) || !headers) + ) { + if ( + (typeof Blob !== 'undefined' && functionArgs instanceof Blob) || + functionArgs instanceof ArrayBuffer + ) { + // will work for File as File inherits Blob + // also works for ArrayBuffer as it is the same underlying structure as a Blob + _headers['Content-Type'] = 'application/octet-stream' + body = functionArgs + } else if (typeof functionArgs === 'string') { + // plain string + _headers['Content-Type'] = 'text/plain' + body = functionArgs + } else if (typeof FormData !== 'undefined' && functionArgs instanceof FormData) { + // don't set content-type headers + // Request will automatically add the right boundary value + body = functionArgs + } else { + // default, assume this is JSON + _headers['Content-Type'] = 'application/json' + body = JSON.stringify(functionArgs) + } + } + + const response = await this.fetch(`${this.url}/${functionName}`, { + method: method || 'POST', + // headers priority is (high to low): + // 1. invoke-level headers + // 2. client-level headers + // 3. default Content-Type header + headers: { ..._headers, ...this.headers, ...headers }, + body, + }).catch((fetchError) => { + throw new FunctionsFetchError(fetchError) + }) + + const isRelayError = response.headers.get('x-relay-error') + if (isRelayError && isRelayError === 'true') { + throw new FunctionsRelayError(response) + } + + if (!response.ok) { + throw new FunctionsHttpError(response) + } + + let responseType = (response.headers.get('Content-Type') ?? 'text/plain').split(';')[0].trim() + let data: any + if (responseType === 'application/json') { + data = await response.json() + } else if (responseType === 'application/octet-stream') { + data = await response.blob() + } else if (responseType === 'multipart/form-data') { + data = await response.formData() + } else { + // default to text + data = await response.text() + } + + return { data, error: null } + } catch (error) { + return { data: null, error } + } + } +} diff --git a/node_modules/@supabase/functions-js/src/helper.ts b/node_modules/@supabase/functions-js/src/helper.ts new file mode 100644 index 0000000..9efc01a --- /dev/null +++ b/node_modules/@supabase/functions-js/src/helper.ts @@ -0,0 +1,13 @@ +import { Fetch } from './types' + +export const resolveFetch = (customFetch?: Fetch): Fetch => { + let _fetch: Fetch + if (customFetch) { + _fetch = customFetch + } else if (typeof fetch === 'undefined') { + _fetch = async (...args) => await (await import('cross-fetch')).fetch(...args) + } else { + _fetch = fetch + } + return (...args) => _fetch(...args) +} diff --git a/node_modules/@supabase/functions-js/src/index.ts b/node_modules/@supabase/functions-js/src/index.ts new file mode 100644 index 0000000..c996867 --- /dev/null +++ b/node_modules/@supabase/functions-js/src/index.ts @@ -0,0 +1,9 @@ +export { FunctionsClient } from './FunctionsClient' +export { + FunctionInvokeOptions, + FunctionsError, + FunctionsFetchError, + FunctionsHttpError, + FunctionsRelayError, + FunctionsResponse, +} from './types' diff --git a/node_modules/@supabase/functions-js/src/types.ts b/node_modules/@supabase/functions-js/src/types.ts new file mode 100644 index 0000000..9e0646b --- /dev/null +++ b/node_modules/@supabase/functions-js/src/types.ts @@ -0,0 +1,64 @@ +export type Fetch = typeof fetch + +/** + * Response format + * + */ +export interface FunctionsResponseSuccess { + data: T + error: null +} +export interface FunctionsResponseFailure { + data: null + error: any +} +export type FunctionsResponse = FunctionsResponseSuccess | FunctionsResponseFailure + +export class FunctionsError extends Error { + context: any + constructor(message: string, name = 'FunctionsError', context?: any) { + super(message) + this.name = name + this.context = context + } +} + +export class FunctionsFetchError extends FunctionsError { + constructor(context: any) { + super('Failed to send a request to the Edge Function', 'FunctionsFetchError', context) + } +} + +export class FunctionsRelayError extends FunctionsError { + constructor(context: any) { + super('Relay Error invoking the Edge Function', 'FunctionsRelayError', context) + } +} + +export class FunctionsHttpError extends FunctionsError { + constructor(context: any) { + super('Edge Function returned a non-2xx status code', 'FunctionsHttpError', context) + } +} + +export type FunctionInvokeOptions = { + /** + * Object representing the headers to send with the request. + * */ + headers?: { [key: string]: string } + /** + * The HTTP verb of the request + */ + method?: 'POST' | 'GET' | 'PUT' | 'PATCH' | 'DELETE' + /** + * The body of the request. + */ + body?: + | File + | Blob + | ArrayBuffer + | FormData + | ReadableStream + | Record + | string +} diff --git a/node_modules/@supabase/functions-js/src/version.ts b/node_modules/@supabase/functions-js/src/version.ts new file mode 100644 index 0000000..0360bf2 --- /dev/null +++ b/node_modules/@supabase/functions-js/src/version.ts @@ -0,0 +1 @@ +export const version = '2.1.2' diff --git a/node_modules/@supabase/gotrue-js/LICENSE b/node_modules/@supabase/gotrue-js/LICENSE new file mode 100644 index 0000000..ddeba6a --- /dev/null +++ b/node_modules/@supabase/gotrue-js/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Supabase + +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/@supabase/gotrue-js/README.md b/node_modules/@supabase/gotrue-js/README.md new file mode 100644 index 0000000..f921ec5 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/README.md @@ -0,0 +1,50 @@ +# `gotrue-js` + +An isomorphic JavaScript client library for the [GoTrue](https://github.com/supabase/gotrue) API. + +## Docs + +- Using `gotrue-js`: https://supabase.com/docs/reference/javascript/auth-signup +- TypeDoc: https://supabase.github.io/gotrue-js/v2 + +## Quick start + +Install + +```bash +npm install --save @supabase/gotrue-js +``` + +Usage + +```js +import { GoTrueClient } from '@supabase/gotrue-js' + +const GOTRUE_URL = 'http://localhost:9999' + +const auth = new GoTrueClient({ url: GOTRUE_URL }) +``` + +- `signUp()`: https://supabase.io/docs/reference/javascript/auth-signup +- `signIn()`: https://supabase.io/docs/reference/javascript/auth-signin +- `signOut()`: https://supabase.io/docs/reference/javascript/auth-signout + +### Custom `fetch` implementation + +`gotrue-js` uses the [`cross-fetch`](https://www.npmjs.com/package/cross-fetch) library to make HTTP requests, but an alternative `fetch` implementation can be provided as an option. This is most useful in environments where `cross-fetch` is not compatible, for instance Cloudflare Workers: + +```js +import { GoTrueClient } from '@supabase/gotrue-js' + +const GOTRUE_URL = 'http://localhost:9999' + +const auth = new GoTrueClient({ url: GOTRUE_URL, fetch: fetch }) +``` + +## Sponsors + +We are building the features of Firebase using enterprise-grade, open source products. We support existing communities wherever possible, and if the products don’t exist we build them and open source them ourselves. + +[![New Sponsor](https://user-images.githubusercontent.com/10214025/90518111-e74bbb00-e198-11ea-8f88-c9e3c1aa4b5b.png)](https://github.com/sponsors/supabase) + +![Watch this repo](https://gitcdn.xyz/repo/supabase/monorepo/master/web/static/watch-repo.gif 'Watch this repo') diff --git a/node_modules/@supabase/gotrue-js/dist/main/GoTrueAdminApi.d.ts b/node_modules/@supabase/gotrue-js/dist/main/GoTrueAdminApi.d.ts new file mode 100644 index 0000000..7c747ef --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/GoTrueAdminApi.d.ts @@ -0,0 +1,99 @@ +import { Fetch } from './lib/fetch'; +import { AdminUserAttributes, GenerateLinkParams, GenerateLinkResponse, Pagination, User, UserResponse, GoTrueAdminMFAApi, PageParams } from './lib/types'; +import { AuthError } from './lib/errors'; +export default class GoTrueAdminApi { + /** Contains all MFA administration methods. */ + mfa: GoTrueAdminMFAApi; + protected url: string; + protected headers: { + [key: string]: string; + }; + protected fetch: Fetch; + constructor({ url, headers, fetch, }: { + url: string; + headers?: { + [key: string]: string; + }; + fetch?: Fetch; + }); + /** + * Removes a logged-in session. + * @param jwt A valid, logged-in JWT. + * @param scope The logout sope. + */ + signOut(jwt: string, scope?: 'global' | 'local' | 'others'): Promise<{ + data: null; + error: AuthError | null; + }>; + /** + * Sends an invite link to an email address. + * @param email The email address of the user. + * @param options Additional options to be included when inviting. + */ + inviteUserByEmail(email: string, options?: { + /** A custom data object to store additional metadata about the user. This maps to the `auth.users.user_metadata` column. */ + data?: object; + /** The URL which will be appended to the email link sent to the user's email address. Once clicked the user will end up on this URL. */ + redirectTo?: string; + }): Promise; + /** + * Generates email links and OTPs to be sent via a custom email provider. + * @param email The user's email. + * @param options.password User password. For signup only. + * @param options.data Optional user metadata. For signup only. + * @param options.redirectTo The redirect url which should be appended to the generated link + */ + generateLink(params: GenerateLinkParams): Promise; + /** + * Creates a new user. + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + createUser(attributes: AdminUserAttributes): Promise; + /** + * Get a list of users. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. + */ + listUsers(params?: PageParams): Promise<{ + data: { + users: User[]; + aud: string; + } & Pagination; + error: null; + } | { + data: { + users: []; + }; + error: AuthError; + }>; + /** + * Get user by id. + * + * @param uid The user's unique identifier + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + getUserById(uid: string): Promise; + /** + * Updates the user data. + * + * @param attributes The data you want to update. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + updateUserById(uid: string, attributes: AdminUserAttributes): Promise; + /** + * Delete a user. Requires a `service_role` key. + * + * @param id The user id you want to remove. + * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. + * Defaults to false for backward compatibility. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + deleteUser(id: string, shouldSoftDelete?: boolean): Promise; + private _listFactors; + private _deleteFactor; +} +//# sourceMappingURL=GoTrueAdminApi.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/GoTrueAdminApi.d.ts.map b/node_modules/@supabase/gotrue-js/dist/main/GoTrueAdminApi.d.ts.map new file mode 100644 index 0000000..7e8ef35 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/GoTrueAdminApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"GoTrueAdminApi.d.ts","sourceRoot":"","sources":["../../src/GoTrueAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EAKN,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,oBAAoB,EACpB,UAAU,EACV,IAAI,EACJ,YAAY,EACZ,iBAAiB,EAKjB,UAAU,EACX,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,SAAS,EAAe,MAAM,cAAc,CAAA;AAErD,MAAM,CAAC,OAAO,OAAO,cAAc;IACjC,+CAA+C;IAC/C,GAAG,EAAE,iBAAiB,CAAA;IAEtB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,OAAO,EAAE;QACjB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KACtB,CAAA;IACD,SAAS,CAAC,KAAK,EAAE,KAAK,CAAA;gBAEV,EACV,GAAQ,EACR,OAAY,EACZ,KAAK,GACN,EAAE;QACD,GAAG,EAAE,MAAM,CAAA;QACX,OAAO,CAAC,EAAE;YACR,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;SACtB,CAAA;QACD,KAAK,CAAC,EAAE,KAAK,CAAA;KACd;IAUD;;;;OAIG;IACG,OAAO,CACX,GAAG,EAAE,MA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/@supabase/gotrue-js/dist/main/GoTrueAdminApi.js b/node_modules/@supabase/gotrue-js/dist/main/GoTrueAdminApi.js new file mode 100644 index 0000000..f18fa65 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/GoTrueAdminApi.js @@ -0,0 +1,268 @@ +"use strict"; +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const fetch_1 = require("./lib/fetch"); +const helpers_1 = require("./lib/helpers"); +const errors_1 = require("./lib/errors"); +class GoTrueAdminApi { + constructor({ url = '', headers = {}, fetch, }) { + this.url = url; + this.headers = headers; + this.fetch = (0, helpers_1.resolveFetch)(fetch); + this.mfa = { + listFactors: this._listFactors.bind(this), + deleteFactor: this._deleteFactor.bind(this), + }; + } + /** + * Removes a logged-in session. + * @param jwt A valid, logged-in JWT. + * @param scope The logout sope. + */ + async signOut(jwt, scope = 'global') { + try { + await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, { + headers: this.headers, + jwt, + noResolveJson: true, + }); + return { data: null, error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Sends an invite link to an email address. + * @param email The email address of the user. + * @param options Additional options to be included when inviting. + */ + async inviteUserByEmail(email, options = {}) { + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/invite`, { + body: { email, data: options.data }, + headers: this.headers, + redirectTo: options.redirectTo, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Generates email links and OTPs to be sent via a custom email provider. + * @param email The user's email. + * @param options.password User password. For signup only. + * @param options.data Optional user metadata. For signup only. + * @param options.redirectTo The redirect url which should be appended to the generated link + */ + async generateLink(params) { + try { + const { options } = params, rest = __rest(params, ["options"]); + const body = Object.assign(Object.assign({}, rest), options); + if ('newEmail' in rest) { + // replace newEmail with new_email in request body + body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail; + delete body['newEmail']; + } + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/generate_link`, { + body: body, + headers: this.headers, + xform: fetch_1._generateLinkResponse, + redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { + data: { + properties: null, + user: null, + }, + error, + }; + } + throw error; + } + } + // User Admin API + /** + * Creates a new user. + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async createUser(attributes) { + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/users`, { + body: attributes, + headers: this.headers, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Get a list of users. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. + */ + async listUsers(params) { + var _a, _b, _c, _d, _e, _f, _g; + try { + const pagination = { nextPage: null, lastPage: 0, total: 0 }; + const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users`, { + headers: this.headers, + noResolveJson: true, + query: { + page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '', + per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '', + }, + xform: fetch_1._noResolveJsonResponse, + }); + if (response.error) + throw response.error; + const users = await response.json(); + const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0; + const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : []; + if (links.length > 0) { + links.forEach((link) => { + const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)); + const rel = JSON.parse(link.split(';')[1].split('=')[1]); + pagination[`${rel}Page`] = page; + }); + pagination.total = parseInt(total); + } + return { data: Object.assign(Object.assign({}, users), pagination), error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { users: [] }, error }; + } + throw error; + } + } + /** + * Get user by id. + * + * @param uid The user's unique identifier + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async getUserById(uid) { + try { + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, { + headers: this.headers, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Updates the user data. + * + * @param attributes The data you want to update. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async updateUserById(uid, attributes) { + try { + return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, { + body: attributes, + headers: this.headers, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Delete a user. Requires a `service_role` key. + * + * @param id The user id you want to remove. + * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. + * Defaults to false for backward compatibility. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async deleteUser(id, shouldSoftDelete = false) { + try { + return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, { + headers: this.headers, + body: { + should_soft_delete: shouldSoftDelete, + }, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + async _listFactors(params) { + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/factors`, { + headers: this.headers, + xform: (factors) => { + return { data: { factors }, error: null }; + }, + }); + return { data, error }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + async _deleteFactor(params) { + try { + const data = await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/factors/${params.id}`, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } +} +exports.default = GoTrueAdminApi; +//# sourceMappingURL=GoTrueAdminApi.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/GoTrueAdminApi.js.map b/node_modules/@supabase/gotrue-js/dist/main/GoTrueAdminApi.js.map new file mode 100644 index 0000000..079cbd3 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/GoTrueAdminApi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GoTrueAdminApi.js","sourceRoot":"","sources":["../../src/GoTrueAdminApi.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,uCAMoB;AACpB,2CAA4C;AAe5C,yCAAqD;AAErD,MAAqB,cAAc;IAUjC,YAAY,EACV,GAAG,GAAG,EAAE,EACR,OAAO,GAAG,EAAE,EACZ,KAAK,GAON;QACC,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,KAAK,GAAG,IAAA,sBAAY,EAAC,KAAK,CAAC,CAAA;QAChC,IAAI,CAAC,GAAG,GAAG;YACT,WAAW,EAAE,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC;YACzC,YAAY,EAAE,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC;SAC5C,CAAA;IACH,CAAC;IAED;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Q,EACpC,IAAI,CAAC,KAAK,EACV,KAAK,EACL,GAAG,IAAI,CAAC,GAAG,gBAAgB,MAAM,CAAC,MAAM,UAAU,EAClD;gBACE,OAAO,EAAE,IAAI,CAAC,OAAO;gBACrB,KAAK,EAAE,CAAC,OAAY,EAAE,EAAE;oBACtB,OAAO,EAAE,IAAI,EAAE,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;gBAC3C,CAAC;aACF,CACF,CAAA;YACD,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;SACvB;QAAC,OAAO,KAAK,EAAE;YACd,IAAI,IAAA,oBAAW,EAAC,KAAK,CAAC,EAAE;gBACtB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;aAC7B;YAED,MAAM,KAAK,CAAA;SACZ;IACH,CAAC;IAEO,KAAK,CAAC,aAAa,CACzB,MAAsC;QAEtC,IAAI;YACF,MAAM,IAAI,GAAG,MAAM,IAAA,gBAAQ,EACzB,IAAI,CAAC,KAAK,EACV,QAAQ,EACR,GAAG,IAAI,CAAC,GAAG,gBAAgB,MAAM,CAAC,MAAM,YAAY,MAAM,CAAC,EAAE,EAAE,EAC/D;gBACE,OAAO,EAAE,IAAI,CAAC,OAAO;aACtB,CACF,CAAA;YAED,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;SAC7B;QAAC,OAAO,KAAK,EAAE;YACd,IAAI,IAAA,oBAAW,EAAC,KAAK,CAAC,EAAE;gBACtB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;aAC7B;YAED,MAAM,KAAK,CAAA;SACZ;IACH,CAAC;CACF;AApTD,iCAoTC"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/GoTrueClient.d.ts b/node_modules/@supabase/gotrue-js/dist/main/GoTrueClient.d.ts new file mode 100644 index 0000000..ef891af --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/GoTrueClient.d.ts @@ -0,0 +1,390 @@ +import GoTrueAdminApi from './GoTrueAdminApi'; +import { AuthError } from './lib/errors'; +import { Fetch } from './lib/fetch'; +import { Deferred } from './lib/helpers'; +import type { AuthChangeEvent, AuthResponse, AuthTokenResponse, AuthOtpResponse, CallRefreshTokenResult, GoTrueClientOptions, InitializeResult, OAuthResponse, SSOResponse, Session, SignInWithIdTokenCredentials, SignInWithOAuthCredentials, SignInWithPasswordCredentials, SignInWithPasswordlessCredentials, SignUpWithPasswordCredentials, SignInWithSSO, SignOut, Subscription, SupportedStorage, UserAttributes, UserResponse, VerifyOtpParams, GoTrueMFAApi, ResendParams, AuthFlowType, LockFunc } from './lib/types'; +export default class GoTrueClient { + private static nextInstanceID; + private instanceID; + /** + * Namespace for the GoTrue admin methods. + * These methods should only be used in a trusted server-side environment. + */ + admin: GoTrueAdminApi; + /** + * Namespace for the MFA methods. + */ + mfa: GoTrueMFAApi; + /** + * The storage key used to identify the values saved in localStorage + */ + protected storageKey: string; + /** + * The session object for the currently logged in user. If null, it means there isn't a logged-in user. + * Only used if persistSession is false. + */ + protected inMemorySession: Session | null; + protected flowType: AuthFlowType; + protected autoRefreshToken: boolean; + protected persistSession: boolean; + protected storage: SupportedStorage; + protected stateChangeEmitters: Map; + protected autoRefreshTicker: ReturnType | null; + protected visibilityChangedCallback: (() => Promise) | null; + protected refreshingDeferred: Deferred | null; + /** + * Keeps track of the async client initialization. + * When null or not yet resolved the auth state is `unknown` + * Once resolved the the auth state is known and it's save to call any further client methods. + * Keep extra care to never reject or throw uncaught errors + */ + protected initializePromise: Promise | null; + protected detectSessionInUrl: boolean; + protected url: string; + protected headers: { + [key: string]: string; + }; + protected fetch: Fetch; + protected lock: LockFunc; + /** + * Used to broadcast state change events to other tabs listening. + */ + protected broadcastChannel: BroadcastChannel | null; + protected logDebugMessages: boolean; + /** + * Create a new client for use in the browser. + */ + constructor(options: GoTrueClientOptions); + private _debug; + /** + * Initializes the client session either from the url or from storage. + * This method is automatically called when instantiating the client, but should also be called + * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). + */ + initialize(): Promise; + /** + * IMPORTANT: + * 1. Never throw in this method, as it is called from the constructor + * 2. Never return a session from this method as it would be cached over + * the whole lifetime of the client + */ + private _initialize; + /** + * Creates a new user. + * + * Be aware that if a user account exists in the system you may get back an + * error message that attempts to hide this information from the user. + * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. + * + * @returns A logged-in session if the server has "autoconfirm" ON + * @returns A user if the server has "autoconfirm" OFF + */ + signUp(credentials: SignUpWithPasswordCredentials): Promise; + /** + * Log in an existing user with an email and password or phone and password. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or that the + * email/phone and password combination is wrong or that the account can only + * be accessed via social login. + */ + signInWithPassword(credentials: SignInWithPasswordCredentials): Promise; + /** + * Log in an existing user via a third-party provider. + * This method supports the PKCE flow. + */ + signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise; + /** + * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. + */ + exchangeCodeForSession(authCode: string): Promise; + /** + * Allows signing in with an OIDC ID token. The authentication provider used + * should be enabled and configured. + */ + signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise; + /** + * Log in a user using magiclink or a one-time password (OTP). + * + * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. + * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. + * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or, that the account + * can only be accessed via social login. + * + * Do note that you will need to configure a Whatsapp sender on Twilio + * if you are using phone sign in with the 'whatsapp' channel. The whatsapp + * channel is not supported on other providers + * at this time. + * This method supports PKCE when an email is passed. + */ + signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise; + /** + * Log in a user given a User supplied OTP received via mobile. + */ + verifyOtp(params: VerifyOtpParams): Promise; + /** + * Attempts a single-sign on using an enterprise Identity Provider. A + * successful SSO attempt will redirect the current page to the identity + * provider authorization page. The redirect URL is implementation and SSO + * protocol specific. + * + * You can use it by providing a SSO domain. Typically you can extract this + * domain by asking users for their email address. If this domain is + * registered on the Auth instance the redirect will use that organization's + * currently active SSO Identity Provider for the login. + * + * If you have built an organization-specific login page, you can use the + * organization's SSO Identity Provider UUID directly instead. + */ + signInWithSSO(params: SignInWithSSO): Promise; + /** + * Sends a reauthentication OTP to the user's email or phone number. + * Requires the user to be signed-in. + */ + reauthenticate(): Promise; + /** + * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. + */ + resend(credentials: ResendParams): Promise; + /** + * Returns the session, refreshing it if necessary. + * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. + */ + getSession(): Promise<{ + data: { + session: Session; + }; + error: null; + } | { + data: { + session: null; + }; + error: AuthError; + } | { + data: { + session: null; + }; + error: null; + }>; + /** + * Acquires a global lock based on the storage key. + */ + private _acquireLock; + /** + * Use instead of {@link #getSession} inside the library. It is + * semantically usually what you want, as getting a session involves some + * processing afterwards that requires only one client operating on the + * session at once across multiple tabs or processes. + */ + private _useSession; + /** + * NEVER USE DIRECTLY! + * + * Always use {@link #_useSession}. + */ + private __loadSession; + /** + * Gets the current user details if there is an existing session. + * @param jwt Takes in an optional access token jwt. If no jwt is provided, getUser() will attempt to get the jwt from the current session. + */ + getUser(jwt?: string): Promise; + /** + * Updates user data for a logged in user. + */ + updateUser(attributes: UserAttributes, options?: { + emailRedirectTo?: string | undefined; + }): Promise; + /** + * Decodes a JWT (without performing any validation). + */ + private _decodeJWT; + /** + * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. + * If the refresh token or access token in the current session is invalid, an error will be thrown. + * @param currentSession The current session that minimally contains an access token and refresh token. + */ + setSession(currentSession: { + access_token: string; + refresh_token: string; + }): Promise; + /** + * Returns a new session, regardless of expiry status. + * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). + * If the current session's refresh token is invalid, an error will be thrown. + * @param currentSession The current session. If passed in, it must contain a refresh token. + */ + refreshSession(currentSession?: { + refresh_token: string; + }): Promise; + /** + * Gets the session data from a URL string + */ + private _getSessionFromURL; + /** + * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) + */ + private _isImplicitGrantFlow; + /** + * Checks if the current URL and backing storage contain parameters given by a PKCE flow + */ + private _isPKCEFlow; + /** + * Inside a browser context, `signOut()` will remove the logged in user from the browser session + * and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. + * + * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. + * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. + * + * If using others scope, no `SIGNED_OUT` event is fired! + */ + signOut({ scope }?: SignOut): Promise<{ + error: AuthError | null; + }>; + /** + * Receive a notification every time an auth event happens. + * @param callback A callback function to be invoked when an auth event happens. + */ + onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => void | Promise): { + data: { + subscription: Subscription; + }; + }; + private _emitInitialSession; + /** + * Sends a password reset request to an email address. + * This method supports the PKCE flow. + * @param email The email address of the user. + * @param options.redirectTo The URL to send the user to after they click the password reset link. + * @param options.captchaToken Verification token received when the user completes the captcha on the site. + */ + resetPasswordForEmail(email: string, options?: { + redirectTo?: string; + captchaToken?: string; + }): Promise<{ + data: {}; + error: null; + } | { + data: null; + error: AuthError; + }>; + /** + * Generates a new JWT. + * @param refreshToken A valid refresh token that was returned on login. + */ + private _refreshAccessToken; + private _isValidSession; + private _handleProviderSignIn; + /** + * Recovers the session from LocalStorage and refreshes + * Note: this method is async to accommodate for AsyncStorage e.g. in React native. + */ + private _recoverAndRefresh; + private _callRefreshToken; + private _notifyAllSubscribers; + /** + * set currentSession and currentUser + * process to _startAutoRefreshToken if possible + */ + private _saveSession; + private _persistSession; + private _removeSession; + /** + * Removes any registered visibilitychange callback. + * + * {@see #startAutoRefresh} + * {@see #stopAutoRefresh} + */ + private _removeVisibilityChangedCallback; + /** + * This is the private implementation of {@link #startAutoRefresh}. Use this + * within the library. + */ + private _startAutoRefresh; + /** + * This is the private implementation of {@link #stopAutoRefresh}. Use this + * within the library. + */ + private _stopAutoRefresh; + /** + * Starts an auto-refresh process in the background. The session is checked + * every few seconds. Close to the time of expiration a process is started to + * refresh the session. If refreshing fails it will be retried for as long as + * necessary. + * + * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need + * to call this function, it will be called for you. + * + * On browsers the refresh process works only when the tab/window is in the + * foreground to conserve resources as well as prevent race conditions and + * flooding auth with requests. If you call this method any managed + * visibility change callback will be removed and you must manage visibility + * changes on your own. + * + * On non-browser platforms the refresh process works *continuously* in the + * background, which may not be desirable. You should hook into your + * platform's foreground indication mechanism and call these methods + * appropriately to conserve resources. + * + * {@see #stopAutoRefresh} + */ + startAutoRefresh(): Promise; + /** + * Stops an active auto refresh process running in the background (if any). + * + * If you call this method any managed visibility change callback will be + * removed and you must manage visibility changes on your own. + * + * See {@link #startAutoRefresh} for more details. + */ + stopAutoRefresh(): Promise; + /** + * Runs the auto refresh token tick. + */ + private _autoRefreshTokenTick; + /** + * Registers callbacks on the browser / platform, which in-turn run + * algorithms when the browser window/tab are in foreground. On non-browser + * platforms it assumes always foreground. + */ + private _handleVisibilityChange; + /** + * Callback registered with `window.addEventListener('visibilitychange')`. + */ + private _onVisibilityChanged; + /** + * Generates the relevant login URL for a third-party provider. + * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. + * @param options.scopes A space-separated list of scopes granted to the OAuth application. + * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. + */ + private _getUrlForProvider; + private _unenroll; + /** + * {@see GoTrueMFAApi#enroll} + */ + private _enroll; + /** + * {@see GoTrueMFAApi#verify} + */ + private _verify; + /** + * {@see GoTrueMFAApi#challenge} + */ + private _challenge; + /** + * {@see GoTrueMFAApi#challengeAndVerify} + */ + private _challengeAndVerify; + /** + * {@see GoTrueMFAApi#listFactors} + */ + private _listFactors; + /** + * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} + */ + private _getAuthenticatorAssuranceLevel; +} +//# sourceMappingURL=GoTrueClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/GoTrueClient.d.ts.map b/node_modules/@supabase/gotrue-js/dist/main/GoTrueClient.d.ts.map new file mode 100644 index 0000000..f96818a --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/GoTrueClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"GoTrueClient.d.ts","sourceRoot":"","sources":["../../src/GoTrueClient.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAE7C,OAAO,EACL,SAAS,EAWV,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,KAAK,EAA2D,MAAM,aAAa,CAAA;AAC5F,OAAO,EAEL,QAAQ,EAgBT,MAAM,eAAe,CAAA;AAKtB,OAAO,KAAK,EACV,eAAe,EACf,YAAY,EACZ,iBAAiB,EACjB,eAAe,EACf,sBAAsB,EACtB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,WAAW,EAEX,OAAO,EACP,4BAA4B,EAC5B,0BAA0B,EAC1B,6BAA6B,EAC7B,iCAAiC,EACjC,6BAA6B,EAC7B,aAAa,EACb,OAAO,EACP,YAAY,EACZ,gBAAgB,EAEhB,cAAc,EACd,YAAY,EACZ,eAAe,EACf,YAAY,EAeZ,YAAY,EACZ,YAAY,EACZ,QAAQ,EACT,MAAM,aAAa,CAAA;AA0BpB,MAAM,CAAC,OAAO,OAAO,YAAY;IAC/B,OAAO,CAAC,MAAM,CAAC,cAAc,CAAI;IAEjC,OAAO,CAAC,UAAU,CAAQ;IAE1B;;;OAGG;IACH,KAAK,EAAE,cAAc,CAAA;IACrB;;OAEG;IACH,GAAG,EAAE,YAAY,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;;OAGG;YACW,YAAY;IAY1B,OAAO,CAAC,eAAe;YAMT,cAAc;IAU5B;;;;;OAKG;IACH,OAAO,CAAC,gCAAgC;IAexC;;;OAGG;YACW,iBAAiB;IAiC/B;;;OAGG;YACW,gBAAgB;IAW9B;;;;;;;;;;;;;;;;;;;;;OAqBG;IACG,gBAAgB;IAKtB;;;;;;;OAOG;IACG,eAAe;IAKrB;;OAEG;YACW,qBAAqB;IAuCnC;;;;OAIG;YACW,uBAAuB;IAyBrC;;OAEG;YACW,oBAAoB;IA+BlC;;;;;OAKG;YACW,kBAAkB;YA6ClB,SAAS;IAqBvB;;OAEG;YACW,OAAO;IAoCrB;;OAEG;YACW,OAAO;IAsCrB;;OAEG;YACW,UAAU;IA0BxB;;OAEG;YACW,mBAAmB;IAgBjC;;OAEG;YACW,YAAY;IAuB1B;;OAEG;YACW,+BAA+B;CAsC9C"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/GoTrueClient.js b/node_modules/@supabase/gotrue-js/dist/main/GoTrueClient.js new file mode 100644 index 0000000..45eab4e --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/GoTrueClient.js @@ -0,0 +1,1671 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const GoTrueAdminApi_1 = __importDefault(require("./GoTrueAdminApi")); +const constants_1 = require("./lib/constants"); +const errors_1 = require("./lib/errors"); +const fetch_1 = require("./lib/fetch"); +const helpers_1 = require("./lib/helpers"); +const local_storage_1 = __importDefault(require("./lib/local-storage")); +const polyfills_1 = require("./lib/polyfills"); +const version_1 = require("./lib/version"); +(0, polyfills_1.polyfillGlobalThis)(); // Make "globalThis" available +const DEFAULT_OPTIONS = { + url: constants_1.GOTRUE_URL, + storageKey: constants_1.STORAGE_KEY, + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + headers: constants_1.DEFAULT_HEADERS, + flowType: 'implicit', + debug: false, +}; +/** Current session will be checked for refresh at this interval. */ +const AUTO_REFRESH_TICK_DURATION = 30 * 1000; +/** + * A token refresh will be attempted this many ticks before the current session expires. */ +const AUTO_REFRESH_TICK_THRESHOLD = 3; +async function lockNoOp(name, acquireTimeout, fn) { + return await fn(); +} +class GoTrueClient { + /** + * Create a new client for use in the browser. + */ + constructor(options) { + var _a; + this.stateChangeEmitters = new Map(); + this.autoRefreshTicker = null; + this.visibilityChangedCallback = null; + this.refreshingDeferred = null; + /** + * Keeps track of the async client initialization. + * When null or not yet resolved the auth state is `unknown` + * Once resolved the the auth state is known and it's save to call any further client methods. + * Keep extra care to never reject or throw uncaught errors + */ + this.initializePromise = null; + this.detectSessionInUrl = true; + /** + * Used to broadcast state change events to other tabs listening. + */ + this.broadcastChannel = null; + this.instanceID = GoTrueClient.nextInstanceID; + GoTrueClient.nextInstanceID += 1; + if (this.instanceID > 0 && (0, helpers_1.isBrowser)()) { + console.warn('Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.'); + } + const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options); + this.logDebugMessages = settings.debug; + this.inMemorySession = null; + this.storageKey = settings.storageKey; + this.autoRefreshToken = settings.autoRefreshToken; + this.persistSession = settings.persistSession; + this.storage = settings.storage || local_storage_1.default; + this.admin = new GoTrueAdminApi_1.default({ + url: settings.url, + headers: settings.headers, + fetch: settings.fetch, + }); + this.url = settings.url; + this.headers = settings.headers; + this.fetch = (0, helpers_1.resolveFetch)(settings.fetch); + this.lock = settings.lock || lockNoOp; + this.detectSessionInUrl = settings.detectSessionInUrl; + this.flowType = settings.flowType; + this.mfa = { + verify: this._verify.bind(this), + enroll: this._enroll.bind(this), + unenroll: this._unenroll.bind(this), + challenge: this._challenge.bind(this), + listFactors: this._listFactors.bind(this), + challengeAndVerify: this._challengeAndVerify.bind(this), + getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this), + }; + if (this.persistSession && this.storage === local_storage_1.default && !(0, helpers_1.supportsLocalStorage)()) { + console.warn(`No storage option exists to persist the session, which may result in unexpected behavior when using auth. + If you want to set persistSession to true, please provide a storage option or you may set persistSession to false to disable this warning.`); + } + if ((0, helpers_1.isBrowser)() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) { + try { + this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey); + } + catch (e) { + console.error('Failed to create a new BroadcastChannel, multi-tab state changes will not be available', e); + } + (_a = this.broadcastChannel) === null || _a === void 0 ? void 0 : _a.addEventListener('message', async (event) => { + this._debug('received broadcast notification from other tab or client', event); + await this._notifyAllSubscribers(event.data.event, event.data.session, false); // broadcast = false so we don't get an endless loop of messages + }); + } + this.initialize(); + } + _debug(...args) { + if (this.logDebugMessages) { + console.log(`GoTrueClient@${this.instanceID} (${version_1.version}) ${new Date().toISOString()}`, ...args); + } + return this; + } + /** + * Initializes the client session either from the url or from storage. + * This method is automatically called when instantiating the client, but should also be called + * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). + */ + initialize() { + if (this.initializePromise) { + return this.initializePromise; + } + return this._initialize(); + } + /** + * IMPORTANT: + * 1. Never throw in this method, as it is called from the constructor + * 2. Never return a session from this method as it would be cached over + * the whole lifetime of the client + */ + async _initialize() { + if (this.initializePromise) { + throw new Error('Double call of #_initialize()'); + } + this.initializePromise = this._acquireLock(-1, async () => await (0, helpers_1.stackGuard)('_initialize', async () => { + try { + const isPKCEFlow = (0, helpers_1.isBrowser)() ? await this._isPKCEFlow() : false; + this._debug('#_initialize()', 'begin', 'is PKCE flow', isPKCEFlow); + if (isPKCEFlow || (this.detectSessionInUrl && this._isImplicitGrantFlow())) { + const { data, error } = await this._getSessionFromURL(isPKCEFlow); + if (error) { + this._debug('#_initialize()', 'error detecting session from URL', error); + // failed login attempt via url, + // remove old session as in verifyOtp, signUp and signInWith* + await this._removeSession(); + return { error }; + } + const { session, redirectType } = data; + this._debug('#_initialize()', 'detected session in URL', session, 'redirect type', redirectType); + await this._saveSession(session); + setTimeout(async () => { + if (redirectType === 'recovery') { + await this._notifyAllSubscribers('PASSWORD_RECOVERY', session); + } + else { + await this._notifyAllSubscribers('SIGNED_IN', session); + } + }, 0); + return { error: null }; + } + // no login attempt via callback url try to recover session from storage + await this._recoverAndRefresh(); + return { error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { error }; + } + return { + error: new errors_1.AuthUnknownError('Unexpected error during initialization', error), + }; + } + finally { + await this._handleVisibilityChange(); + this._debug('#_initialize()', 'end'); + } + })); + return await this.initializePromise; + } + /** + * Creates a new user. + * + * Be aware that if a user account exists in the system you may get back an + * error message that attempts to hide this information from the user. + * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. + * + * @returns A logged-in session if the server has "autoconfirm" ON + * @returns A user if the server has "autoconfirm" OFF + */ + async signUp(credentials) { + var _a, _b, _c; + try { + await this._removeSession(); + let res; + if ('email' in credentials) { + const { email, password, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + const codeVerifier = (0, helpers_1.generatePKCEVerifier)(); + await (0, helpers_1.setItemAsync)(this.storage, `${this.storageKey}-code-verifier`, codeVerifier); + codeChallenge = await (0, helpers_1.generatePKCEChallenge)(codeVerifier); + codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'; + } + res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: { + email, + password, + data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + xform: fetch_1._sessionResponse, + }); + } + else if ('phone' in credentials) { + const { phone, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + body: { + phone, + password, + data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {}, + channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : 'sms', + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponse, + }); + } + else { + throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); + } + const { data, error } = res; + if (error || !data) { + return { data: { user: null, session: null }, error: error }; + } + const session = data.session; + const user = data.user; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return { data: { user, session }, error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Log in an existing user with an email and password or phone and password. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or that the + * email/phone and password combination is wrong or that the account can only + * be accessed via social login. + */ + async signInWithPassword(credentials) { + try { + await this._removeSession(); + let res; + if ('email' in credentials) { + const { email, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + email, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponse, + }); + } + else if ('phone' in credentials) { + const { phone, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + phone, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponse, + }); + } + else { + throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); + } + const { data, error } = res; + if (error) { + return { data: { user: null, session: null }, error }; + } + else if (!data || !data.session || !data.user) { + return { data: { user: null, session: null }, error: new errors_1.AuthInvalidTokenResponseError() }; + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return { data: { user: data.user, session: data.session }, error }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Log in an existing user via a third-party provider. + * This method supports the PKCE flow. + */ + async signInWithOAuth(credentials) { + var _a, _b, _c, _d; + await this._removeSession(); + return await this._handleProviderSignIn(credentials.provider, { + redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, + scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, + queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, + skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect, + }); + } + /** + * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. + */ + async exchangeCodeForSession(authCode) { + const codeVerifier = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=pkce`, { + headers: this.headers, + body: { + auth_code: authCode, + code_verifier: codeVerifier, + }, + xform: fetch_1._sessionResponse, + }); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if (error) { + return { data: { user: null, session: null }, error }; + } + else if (!data || !data.session || !data.user) { + return { data: { user: null, session: null }, error: new errors_1.AuthInvalidTokenResponseError() }; + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return { data, error }; + } + /** + * Allows signing in with an OIDC ID token. The authentication provider used + * should be enabled and configured. + */ + async signInWithIdToken(credentials) { + await this._removeSession(); + try { + const { options, provider, token, access_token, nonce } = credentials; + const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + body: { + provider, + id_token: token, + access_token, + nonce, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponse, + }); + const { data, error } = res; + if (error) { + return { data: { user: null, session: null }, error }; + } + else if (!data || !data.session || !data.user) { + return { + data: { user: null, session: null }, + error: new errors_1.AuthInvalidTokenResponseError(), + }; + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return { data, error }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Log in a user using magiclink or a one-time password (OTP). + * + * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. + * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. + * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or, that the account + * can only be accessed via social login. + * + * Do note that you will need to configure a Whatsapp sender on Twilio + * if you are using phone sign in with the 'whatsapp' channel. The whatsapp + * channel is not supported on other providers + * at this time. + * This method supports PKCE when an email is passed. + */ + async signInWithOtp(credentials) { + var _a, _b, _c, _d, _e; + try { + await this._removeSession(); + if ('email' in credentials) { + const { email, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + const codeVerifier = (0, helpers_1.generatePKCEVerifier)(); + await (0, helpers_1.setItemAsync)(this.storage, `${this.storageKey}-code-verifier`, codeVerifier); + codeChallenge = await (0, helpers_1.generatePKCEChallenge)(codeVerifier); + codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'; + } + const { error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + email, + data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, + create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + }); + return { data: { user: null, session: null }, error }; + } + if ('phone' in credentials) { + const { phone, options } = credentials; + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + phone, + data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {}, + create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + channel: (_e = options === null || options === void 0 ? void 0 : options.channel) !== null && _e !== void 0 ? _e : 'sms', + }, + }); + return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error }; + } + throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number.'); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Log in a user given a User supplied OTP received via mobile. + */ + async verifyOtp(params) { + var _a, _b; + try { + if (params.type !== 'email_change' && params.type !== 'phone_change') { + // we don't want to remove the authenticated session if the user is performing an email_change or phone_change verification + await this._removeSession(); + } + let redirectTo = undefined; + let captchaToken = undefined; + if ('options' in params) { + redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo; + captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken; + } + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/verify`, { + headers: this.headers, + body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }), + redirectTo, + xform: fetch_1._sessionResponse, + }); + if (error) { + throw error; + } + if (!data) { + throw new Error('An error occurred on token verification.'); + } + const session = data.session; + const user = data.user; + if (session === null || session === void 0 ? void 0 : session.access_token) { + await this._saveSession(session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return { data: { user, session }, error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Attempts a single-sign on using an enterprise Identity Provider. A + * successful SSO attempt will redirect the current page to the identity + * provider authorization page. The redirect URL is implementation and SSO + * protocol specific. + * + * You can use it by providing a SSO domain. Typically you can extract this + * domain by asking users for their email address. If this domain is + * registered on the Auth instance the redirect will use that organization's + * currently active SSO Identity Provider for the login. + * + * If you have built an organization-specific login page, you can use the + * organization's SSO Identity Provider UUID directly instead. + */ + async signInWithSSO(params) { + var _a, _b, _c; + try { + await this._removeSession(); + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/sso`, { + body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, ('providerId' in params ? { provider_id: params.providerId } : null)), ('domain' in params ? { domain: params.domain } : null)), { redirect_to: (_b = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo) !== null && _b !== void 0 ? _b : undefined }), (((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken) + ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } + : null)), { skip_http_redirect: true }), + headers: this.headers, + xform: fetch_1._ssoResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Sends a reauthentication OTP to the user's email or phone number. + * Requires the user to be signed-in. + */ + async reauthenticate() { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) + throw sessionError; + if (!session) + throw new errors_1.AuthSessionMissingError(); + const { error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/reauthenticate`, { + headers: this.headers, + jwt: session.access_token, + }); + return { data: { user: null, session: null }, error }; + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. + */ + async resend(credentials) { + try { + if (credentials.type != 'email_change' && credentials.type != 'phone_change') { + await this._removeSession(); + } + const endpoint = `${this.url}/resend`; + if ('email' in credentials) { + const { email, type, options } = credentials; + const { error } = await (0, fetch_1._request)(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + email, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + }); + return { data: { user: null, session: null }, error }; + } + else if ('phone' in credentials) { + const { phone, type, options } = credentials; + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + phone, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + }); + return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error }; + } + throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a type'); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Returns the session, refreshing it if necessary. + * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. + */ + async getSession() { + return this._useSession(async (result) => { + return result; + }); + } + /** + * Acquires a global lock based on the storage key. + */ + async _acquireLock(acquireTimeout, fn) { + this._debug('#_acquireLock', 'begin', acquireTimeout); + try { + if (!(await (0, helpers_1.stackGuardsSupported)())) { + this._debug('#_acquireLock', 'Stack guards not supported, so exclusive locking is not performed as it can lead to deadlocks if the lock is attempted to be recursively acquired (as the recursion cannot be detected).'); + return await fn(); + } + if ((0, helpers_1.isInStackGuard)('_acquireLock')) { + this._debug('#_acquireLock', 'recursive call'); + return await fn(); + } + return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => { + this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey); + try { + return await (0, helpers_1.stackGuard)('_acquireLock', async () => { + return await fn(); + }); + } + finally { + this._debug('#_acquireLock', 'lock released for storage key', this.storageKey); + } + }); + } + finally { + this._debug('#_acquireLock', 'end'); + } + } + /** + * Use instead of {@link #getSession} inside the library. It is + * semantically usually what you want, as getting a session involves some + * processing afterwards that requires only one client operating on the + * session at once across multiple tabs or processes. + */ + async _useSession(fn) { + this._debug('#_useSession', 'begin'); + try { + if ((0, helpers_1.isInStackGuard)('_useSession')) { + this._debug('#_useSession', 'recursive call'); + // the use of __loadSession here is the only correct use of the function! + const result = await this.__loadSession(); + return await fn(result); + } + return await this._acquireLock(-1, async () => { + return await (0, helpers_1.stackGuard)('_useSession', async () => { + // the use of __loadSession here is the only correct use of the function! + const result = await this.__loadSession(); + return await fn(result); + }); + }); + } + finally { + this._debug('#_useSession', 'end'); + } + } + /** + * NEVER USE DIRECTLY! + * + * Always use {@link #_useSession}. + */ + async __loadSession() { + this._debug('#__loadSession()', 'begin'); + if (this.logDebugMessages && !(0, helpers_1.isInStackGuard)('_useSession') && (await (0, helpers_1.stackGuardsSupported)())) { + throw new Error('Please use #_useSession()'); + } + if ((0, helpers_1.isInStackGuard)('_initialize')) { + this._debug('#__loadSession', '#_initialize recursion detected', new Error().stack); + } + // always wait for #_initialize() to finish before loading anything from + // storage + await this.initializePromise; + try { + let currentSession = null; + if (this.persistSession) { + const maybeSession = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey); + this._debug('#getSession()', 'session from storage', maybeSession); + if (maybeSession !== null) { + if (this._isValidSession(maybeSession)) { + currentSession = maybeSession; + } + else { + this._debug('#getSession()', 'session from storage is not valid'); + await this._removeSession(); + } + } + } + else { + currentSession = this.inMemorySession; + this._debug('#getSession()', 'session from memory', currentSession); + } + if (!currentSession) { + return { data: { session: null }, error: null }; + } + const hasExpired = currentSession.expires_at + ? currentSession.expires_at <= Date.now() / 1000 + : false; + this._debug('#__loadSession()', `session has${hasExpired ? '' : ' not'} expired`, 'expires_at', currentSession.expires_at); + if (!hasExpired) { + return { data: { session: currentSession }, error: null }; + } + const { session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return { data: { session: null }, error }; + } + return { data: { session }, error: null }; + } + finally { + this._debug('#__loadSession()', 'end'); + } + } + /** + * Gets the current user details if there is an existing session. + * @param jwt Takes in an optional access token jwt. If no jwt is provided, getUser() will attempt to get the jwt from the current session. + */ + async getUser(jwt) { + try { + if (jwt) { + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: jwt, + xform: fetch_1._userResponse, + }); + } + return await this._useSession(async (result) => { + var _a, _b; + const { data, error } = result; + if (error) { + throw error; + } + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : undefined, + xform: fetch_1._userResponse, + }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Updates user data for a logged in user. + */ + async updateUser(attributes, options = {}) { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + throw sessionError; + } + if (!sessionData.session) { + throw new errors_1.AuthSessionMissingError(); + } + const session = sessionData.session; + const { data, error: userError } = await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/user`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: attributes, + jwt: session.access_token, + xform: fetch_1._userResponse, + }); + if (userError) + throw userError; + session.user = data.user; + await this._saveSession(session); + await this._notifyAllSubscribers('USER_UPDATED', session); + return { data: { user: session.user }, error: null }; + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Decodes a JWT (without performing any validation). + */ + _decodeJWT(jwt) { + return (0, helpers_1.decodeJWTPayload)(jwt); + } + /** + * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. + * If the refresh token or access token in the current session is invalid, an error will be thrown. + * @param currentSession The current session that minimally contains an access token and refresh token. + */ + async setSession(currentSession) { + try { + if (!currentSession.access_token || !currentSession.refresh_token) { + throw new errors_1.AuthSessionMissingError(); + } + const timeNow = Date.now() / 1000; + let expiresAt = timeNow; + let hasExpired = true; + let session = null; + const payload = (0, helpers_1.decodeJWTPayload)(currentSession.access_token); + if (payload.exp) { + expiresAt = payload.exp; + hasExpired = expiresAt <= timeNow; + } + if (hasExpired) { + const { session: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return { data: { user: null, session: null }, error: error }; + } + if (!refreshedSession) { + return { data: { user: null, session: null }, error: null }; + } + session = refreshedSession; + } + else { + const { data, error } = await this.getUser(currentSession.access_token); + if (error) { + throw error; + } + session = { + access_token: currentSession.access_token, + refresh_token: currentSession.refresh_token, + user: data.user, + token_type: 'bearer', + expires_in: expiresAt - timeNow, + expires_at: expiresAt, + }; + await this._saveSession(session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return { data: { user: session.user, session }, error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { session: null, user: null }, error }; + } + throw error; + } + } + /** + * Returns a new session, regardless of expiry status. + * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). + * If the current session's refresh token is invalid, an error will be thrown. + * @param currentSession The current session. If passed in, it must contain a refresh token. + */ + async refreshSession(currentSession) { + try { + return await this._useSession(async (result) => { + var _a; + if (!currentSession) { + const { data, error } = result; + if (error) { + throw error; + } + currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : undefined; + } + if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) { + throw new errors_1.AuthSessionMissingError(); + } + const { session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return { data: { user: null, session: null }, error: error }; + } + if (!session) { + return { data: { user: null, session: null }, error: null }; + } + return { data: { user: session.user, session }, error: null }; + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Gets the session data from a URL string + */ + async _getSessionFromURL(isPKCEFlow) { + try { + if (!(0, helpers_1.isBrowser)()) + throw new errors_1.AuthImplicitGrantRedirectError('No browser detected.'); + if (this.flowType === 'implicit' && !this._isImplicitGrantFlow()) { + throw new errors_1.AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.'); + } + else if (this.flowType == 'pkce' && !isPKCEFlow) { + throw new errors_1.AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.'); + } + const params = (0, helpers_1.parseParametersFromURL)(window.location.href); + if (isPKCEFlow) { + if (!params.code) + throw new errors_1.AuthPKCEGrantCodeExchangeError('No code detected.'); + const { data, error } = await this.exchangeCodeForSession(params.code); + if (error) + throw error; + const url = new URL(window.location.href); + url.searchParams.delete('code'); + window.history.replaceState(window.history.state, '', url.toString()); + return { data: { session: data.session, redirectType: null }, error: null }; + } + if (params.error || params.error_description || params.error_code) { + throw new errors_1.AuthImplicitGrantRedirectError(params.error_description || 'Error in URL with unspecified error_description', { + error: params.error || 'unspecified_error', + code: params.error_code || 'unspecified_code', + }); + } + const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, token_type, } = params; + if (!access_token || !expires_in || !refresh_token || !token_type) { + throw new errors_1.AuthImplicitGrantRedirectError('No session defined in URL'); + } + const timeNow = Math.round(Date.now() / 1000); + const expiresIn = parseInt(expires_in); + const expires_at = timeNow + expiresIn; + const { data, error } = await this.getUser(access_token); + if (error) + throw error; + const session = { + provider_token, + provider_refresh_token, + access_token, + expires_in: expiresIn, + expires_at, + refresh_token, + token_type, + user: data.user, + }; + // Remove tokens from URL + window.location.hash = ''; + this._debug('#_getSessionFromURL()', 'clearing window.location.hash'); + return { data: { session, redirectType: params.type }, error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { session: null, redirectType: null }, error }; + } + throw error; + } + } + /** + * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) + */ + _isImplicitGrantFlow() { + const params = (0, helpers_1.parseParametersFromURL)(window.location.href); + return !!((0, helpers_1.isBrowser)() && (params.access_token || params.error_description)); + } + /** + * Checks if the current URL and backing storage contain parameters given by a PKCE flow + */ + async _isPKCEFlow() { + const params = (0, helpers_1.parseParametersFromURL)(window.location.href); + const currentStorageContent = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + return !!(params.code && currentStorageContent); + } + /** + * Inside a browser context, `signOut()` will remove the logged in user from the browser session + * and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. + * + * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. + * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. + * + * If using others scope, no `SIGNED_OUT` event is fired! + */ + async signOut({ scope } = { scope: 'global' }) { + return await this._useSession(async (result) => { + var _a; + const { data, error: sessionError } = result; + if (sessionError) { + return { error: sessionError }; + } + const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token; + if (accessToken) { + const { error } = await this.admin.signOut(accessToken, scope); + if (error) { + // ignore 404s since user might not exist anymore + // ignore 401s since an invalid or expired JWT should sign out the current session + if (!((0, errors_1.isAuthApiError)(error) && (error.status === 404 || error.status === 401))) { + return { error }; + } + } + } + if (scope !== 'others') { + await this._removeSession(); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + await this._notifyAllSubscribers('SIGNED_OUT', null); + } + return { error: null }; + }); + } + /** + * Receive a notification every time an auth event happens. + * @param callback A callback function to be invoked when an auth event happens. + */ + onAuthStateChange(callback) { + const id = (0, helpers_1.uuid)(); + const subscription = { + id, + callback, + unsubscribe: () => { + this._debug('#unsubscribe()', 'state change callback with id removed', id); + this.stateChangeEmitters.delete(id); + }, + }; + this._debug('#onAuthStateChange()', 'registered callback with id', id); + this.stateChangeEmitters.set(id, subscription); + this._emitInitialSession(id); + return { data: { subscription } }; + } + async _emitInitialSession(id) { + return await this._useSession(async (result) => { + var _a, _b; + try { + const { data: { session }, error, } = result; + if (error) + throw error; + await ((_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback('INITIAL_SESSION', session)); + this._debug('INITIAL_SESSION', 'callback id', id, 'session', session); + } + catch (err) { + await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback('INITIAL_SESSION', null)); + this._debug('INITIAL_SESSION', 'callback id', id, 'error', err); + console.error(err); + } + }); + } + /** + * Sends a password reset request to an email address. + * This method supports the PKCE flow. + * @param email The email address of the user. + * @param options.redirectTo The URL to send the user to after they click the password reset link. + * @param options.captchaToken Verification token received when the user completes the captcha on the site. + */ + async resetPasswordForEmail(email, options = {}) { + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + const codeVerifier = (0, helpers_1.generatePKCEVerifier)(); + await (0, helpers_1.setItemAsync)(this.storage, `${this.storageKey}-code-verifier`, codeVerifier); + codeChallenge = await (0, helpers_1.generatePKCEChallenge)(codeVerifier); + codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'; + } + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/recover`, { + body: { + email, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + gotrue_meta_security: { captcha_token: options.captchaToken }, + }, + headers: this.headers, + redirectTo: options.redirectTo, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Generates a new JWT. + * @param refreshToken A valid refresh token that was returned on login. + */ + async _refreshAccessToken(refreshToken) { + const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, 'begin'); + try { + const startedAt = Date.now(); + // will attempt to refresh the token with exponential backoff + return await (0, helpers_1.retryable)(async (attempt) => { + await (0, helpers_1.sleep)(attempt * 200); // 0, 200, 400, 800, ... + this._debug(debugName, 'refreshing attempt', attempt); + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, { + body: { refresh_token: refreshToken }, + headers: this.headers, + xform: fetch_1._sessionResponse, + }); + }, (attempt, _, result) => result && + result.error && + (0, errors_1.isAuthRetryableFetchError)(result.error) && + // retryable only if the request can be sent before the backoff overflows the tick duration + Date.now() + (attempt + 1) * 200 - startedAt < AUTO_REFRESH_TICK_DURATION); + } + catch (error) { + this._debug(debugName, 'error', error); + if ((0, errors_1.isAuthError)(error)) { + return { data: { session: null, user: null }, error }; + } + throw error; + } + finally { + this._debug(debugName, 'end'); + } + } + _isValidSession(maybeSession) { + const isValidSession = typeof maybeSession === 'object' && + maybeSession !== null && + 'access_token' in maybeSession && + 'refresh_token' in maybeSession && + 'expires_at' in maybeSession; + return isValidSession; + } + async _handleProviderSignIn(provider, options) { + const url = await this._getUrlForProvider(provider, { + redirectTo: options.redirectTo, + scopes: options.scopes, + queryParams: options.queryParams, + }); + this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url); + // try to open on the browser + if ((0, helpers_1.isBrowser)() && !options.skipBrowserRedirect) { + window.location.assign(url); + } + return { data: { provider, url }, error: null }; + } + /** + * Recovers the session from LocalStorage and refreshes + * Note: this method is async to accommodate for AsyncStorage e.g. in React native. + */ + async _recoverAndRefresh() { + var _a; + const debugName = '#_recoverAndRefresh()'; + this._debug(debugName, 'begin'); + try { + const currentSession = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey); + this._debug(debugName, 'session from storage', currentSession); + if (!this._isValidSession(currentSession)) { + this._debug(debugName, 'session is not valid'); + if (currentSession !== null) { + await this._removeSession(); + } + return; + } + const timeNow = Math.round(Date.now() / 1000); + const expiresWithMargin = ((_a = currentSession.expires_at) !== null && _a !== void 0 ? _a : Infinity) < timeNow + constants_1.EXPIRY_MARGIN; + this._debug(debugName, `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${constants_1.EXPIRY_MARGIN}s`); + if (expiresWithMargin) { + if (this.autoRefreshToken && currentSession.refresh_token) { + const { error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + console.error(error); + if (!(0, errors_1.isAuthRetryableFetchError)(error)) { + this._debug(debugName, 'refresh failed with a non-retryable error, removing the session', error); + await this._removeSession(); + } + } + } + } + else { + // no need to persist currentSession again, as we just loaded it from + // local storage; persisting it again may overwrite a value saved by + // another client with access to the same local storage + await this._notifyAllSubscribers('SIGNED_IN', currentSession); + } + } + catch (err) { + this._debug(debugName, 'error', err); + console.error(err); + return; + } + finally { + this._debug(debugName, 'end'); + } + } + async _callRefreshToken(refreshToken) { + var _a, _b; + if (!refreshToken) { + throw new errors_1.AuthSessionMissingError(); + } + // refreshing is already in progress + if (this.refreshingDeferred) { + return this.refreshingDeferred.promise; + } + const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, 'begin'); + try { + this.refreshingDeferred = new helpers_1.Deferred(); + const { data, error } = await this._refreshAccessToken(refreshToken); + if (error) + throw error; + if (!data.session) + throw new errors_1.AuthSessionMissingError(); + await this._saveSession(data.session); + await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session); + const result = { session: data.session, error: null }; + this.refreshingDeferred.resolve(result); + return result; + } + catch (error) { + this._debug(debugName, 'error', error); + if ((0, errors_1.isAuthError)(error)) { + const result = { session: null, error }; + (_a = this.refreshingDeferred) === null || _a === void 0 ? void 0 : _a.resolve(result); + return result; + } + (_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error); + throw error; + } + finally { + this.refreshingDeferred = null; + this._debug(debugName, 'end'); + } + } + async _notifyAllSubscribers(event, session, broadcast = true) { + const debugName = `#_notifyAllSubscribers(${event})`; + this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`); + try { + if (this.broadcastChannel && broadcast) { + this.broadcastChannel.postMessage({ event, session }); + } + const errors = []; + const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => { + try { + await x.callback(event, session); + } + catch (e) { + errors.push(e); + } + }); + await Promise.all(promises); + if (errors.length > 0) { + for (let i = 0; i < errors.length; i += 1) { + console.error(errors[i]); + } + throw errors[0]; + } + } + finally { + this._debug(debugName, 'end'); + } + } + /** + * set currentSession and currentUser + * process to _startAutoRefreshToken if possible + */ + async _saveSession(session) { + this._debug('#_saveSession()', session); + if (!this.persistSession) { + this.inMemorySession = session; + } + if (this.persistSession && session.expires_at) { + await this._persistSession(session); + } + } + _persistSession(currentSession) { + this._debug('#_persistSession()', currentSession); + return (0, helpers_1.setItemAsync)(this.storage, this.storageKey, currentSession); + } + async _removeSession() { + this._debug('#_removeSession()'); + if (this.persistSession) { + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey); + } + else { + this.inMemorySession = null; + } + } + /** + * Removes any registered visibilitychange callback. + * + * {@see #startAutoRefresh} + * {@see #stopAutoRefresh} + */ + _removeVisibilityChangedCallback() { + this._debug('#_removeVisibilityChangedCallback()'); + const callback = this.visibilityChangedCallback; + this.visibilityChangedCallback = null; + try { + if (callback && (0, helpers_1.isBrowser)() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) { + window.removeEventListener('visibilitychange', callback); + } + } + catch (e) { + console.error('removing visibilitychange callback failed', e); + } + } + /** + * This is the private implementation of {@link #startAutoRefresh}. Use this + * within the library. + */ + async _startAutoRefresh() { + await this._stopAutoRefresh(); + this._debug('#_startAutoRefresh()'); + const ticker = setInterval(() => this._autoRefreshTokenTick(), AUTO_REFRESH_TICK_DURATION); + this.autoRefreshTicker = ticker; + if (ticker && typeof ticker === 'object' && typeof ticker.unref === 'function') { + // ticker is a NodeJS Timeout object that has an `unref` method + // https://nodejs.org/api/timers.html#timeoutunref + // When auto refresh is used in NodeJS (like for testing) the + // `setInterval` is preventing the process from being marked as + // finished and tests run endlessly. This can be prevented by calling + // `unref()` on the returned object. + ticker.unref(); + // @ts-ignore + } + else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') { + // similar like for NodeJS, but with the Deno API + // https://deno.land/api@latest?unstable&s=Deno.unrefTimer + // @ts-ignore + Deno.unrefTimer(ticker); + } + // run the tick immediately, but in the next pass of the event loop so that + // #_initialize can be allowed to complete without recursively waiting on + // itself + setTimeout(async () => { + await this.initializePromise; + await this._autoRefreshTokenTick(); + }, 0); + } + /** + * This is the private implementation of {@link #stopAutoRefresh}. Use this + * within the library. + */ + async _stopAutoRefresh() { + this._debug('#_stopAutoRefresh()'); + const ticker = this.autoRefreshTicker; + this.autoRefreshTicker = null; + if (ticker) { + clearInterval(ticker); + } + } + /** + * Starts an auto-refresh process in the background. The session is checked + * every few seconds. Close to the time of expiration a process is started to + * refresh the session. If refreshing fails it will be retried for as long as + * necessary. + * + * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need + * to call this function, it will be called for you. + * + * On browsers the refresh process works only when the tab/window is in the + * foreground to conserve resources as well as prevent race conditions and + * flooding auth with requests. If you call this method any managed + * visibility change callback will be removed and you must manage visibility + * changes on your own. + * + * On non-browser platforms the refresh process works *continuously* in the + * background, which may not be desirable. You should hook into your + * platform's foreground indication mechanism and call these methods + * appropriately to conserve resources. + * + * {@see #stopAutoRefresh} + */ + async startAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._startAutoRefresh(); + } + /** + * Stops an active auto refresh process running in the background (if any). + * + * If you call this method any managed visibility change callback will be + * removed and you must manage visibility changes on your own. + * + * See {@link #startAutoRefresh} for more details. + */ + async stopAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._stopAutoRefresh(); + } + /** + * Runs the auto refresh token tick. + */ + async _autoRefreshTokenTick() { + this._debug('#_autoRefreshTokenTick()', 'begin'); + try { + const now = Date.now(); + try { + return await this._useSession(async (result) => { + const { data: { session }, } = result; + if (!session || !session.refresh_token || !session.expires_at) { + this._debug('#_autoRefreshTokenTick()', 'no session'); + return; + } + // session will expire in this many ticks (or has already expired if <= 0) + const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / AUTO_REFRESH_TICK_DURATION); + this._debug('#_autoRefreshTokenTick()', `access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`); + if (expiresInTicks <= AUTO_REFRESH_TICK_THRESHOLD) { + await this._callRefreshToken(session.refresh_token); + } + }); + } + catch (e) { + console.error('Auto refresh tick failed with error. This is likely a transient error.', e); + } + } + finally { + this._debug('#_autoRefreshTokenTick()', 'end'); + } + } + /** + * Registers callbacks on the browser / platform, which in-turn run + * algorithms when the browser window/tab are in foreground. On non-browser + * platforms it assumes always foreground. + */ + async _handleVisibilityChange() { + this._debug('#_handleVisibilityChange()'); + if (!(0, helpers_1.isBrowser)() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) { + if (this.autoRefreshToken) { + // in non-browser environments the refresh token ticker runs always + this.startAutoRefresh(); + } + return false; + } + try { + this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false); + window === null || window === void 0 ? void 0 : window.addEventListener('visibilitychange', this.visibilityChangedCallback); + // now immediately call the visbility changed callback to setup with the + // current visbility state + await this._onVisibilityChanged(true); // initial call + } + catch (error) { + console.error('_handleVisibilityChange', error); + } + } + /** + * Callback registered with `window.addEventListener('visibilitychange')`. + */ + async _onVisibilityChanged(isInitial) { + this._debug(`#_onVisibilityChanged(${isInitial})`, 'visibilityState', document.visibilityState); + if (document.visibilityState === 'visible') { + // to avoid recursively depending on #_initialize(), run the visibility + // changed callback in the next event loop tick + setTimeout(async () => { + if (!isInitial) { + // initial visibility change setup is handled in another flow under #initialize() + await this.initializePromise; + await this._recoverAndRefresh(); + this._debug('#_onVisibilityChanged()', 'finished waiting for initialize, _recoverAndRefresh'); + } + if (this.autoRefreshToken) { + // in browser environments the refresh token ticker runs only on focused tabs + // which prevents race conditions + this._startAutoRefresh(); + } + }, 0); + } + else if (document.visibilityState === 'hidden') { + if (this.autoRefreshToken) { + this._stopAutoRefresh(); + } + } + } + /** + * Generates the relevant login URL for a third-party provider. + * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. + * @param options.scopes A space-separated list of scopes granted to the OAuth application. + * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. + */ + async _getUrlForProvider(provider, options) { + const urlParams = [`provider=${encodeURIComponent(provider)}`]; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`); + } + if (options === null || options === void 0 ? void 0 : options.scopes) { + urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`); + } + if (this.flowType === 'pkce') { + const codeVerifier = (0, helpers_1.generatePKCEVerifier)(); + await (0, helpers_1.setItemAsync)(this.storage, `${this.storageKey}-code-verifier`, codeVerifier); + const codeChallenge = await (0, helpers_1.generatePKCEChallenge)(codeVerifier); + const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'; + this._debug('PKCE', 'code verifier', `${codeVerifier.substring(0, 5)}...`, 'code challenge', codeChallenge, 'method', codeChallengeMethod); + const flowParams = new URLSearchParams({ + code_challenge: `${encodeURIComponent(codeChallenge)}`, + code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`, + }); + urlParams.push(flowParams.toString()); + } + if (options === null || options === void 0 ? void 0 : options.queryParams) { + const query = new URLSearchParams(options.queryParams); + urlParams.push(query.toString()); + } + return `${this.url}/authorize?${urlParams.join('&')}`; + } + async _unenroll(params) { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return { data: null, error: sessionError }; + } + return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, { + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * {@see GoTrueMFAApi#enroll} + */ + async _enroll(params) { + try { + return await this._useSession(async (result) => { + var _a, _b; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return { data: null, error: sessionError }; + } + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors`, { + body: { + friendly_name: params.friendlyName, + factor_type: params.factorType, + issuer: params.issuer, + }, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + if (error) { + return { data: null, error }; + } + if ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code) { + data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`; + } + return { data, error: null }; + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * {@see GoTrueMFAApi#verify} + */ + async _verify(params) { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return { data: null, error: sessionError }; + } + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/verify`, { + body: { code: params.code, challenge_id: params.challengeId }, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + if (error) { + return { data: null, error }; + } + await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1000) + data.expires_in }, data)); + await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data); + return { data, error }; + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * {@see GoTrueMFAApi#challenge} + */ + async _challenge(params) { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return { data: null, error: sessionError }; + } + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/challenge`, { + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * {@see GoTrueMFAApi#challengeAndVerify} + */ + async _challengeAndVerify(params) { + const { data: challengeData, error: challengeError } = await this._challenge({ + factorId: params.factorId, + }); + if (challengeError) { + return { data: null, error: challengeError }; + } + return await this._verify({ + factorId: params.factorId, + challengeId: challengeData.id, + code: params.code, + }); + } + /** + * {@see GoTrueMFAApi#listFactors} + */ + async _listFactors() { + const { data: { user }, error: userError, } = await this.getUser(); + if (userError) { + return { data: null, error: userError }; + } + const factors = (user === null || user === void 0 ? void 0 : user.factors) || []; + const totp = factors.filter((factor) => factor.factor_type === 'totp' && factor.status === 'verified'); + return { + data: { + all: factors, + totp, + }, + error: null, + }; + } + /** + * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} + */ + async _getAuthenticatorAssuranceLevel() { + return await this._useSession(async (result) => { + var _a, _b; + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return { data: null, error: sessionError }; + } + if (!session) { + return { + data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] }, + error: null, + }; + } + const payload = this._decodeJWT(session.access_token); + let currentLevel = null; + if (payload.aal) { + currentLevel = payload.aal; + } + let nextLevel = currentLevel; + const verifiedFactors = (_b = (_a = session.user.factors) === null || _a === void 0 ? void 0 : _a.filter((factor) => factor.status === 'verified')) !== null && _b !== void 0 ? _b : []; + if (verifiedFactors.length > 0) { + nextLevel = 'aal2'; + } + const currentAuthenticationMethods = payload.amr || []; + return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null }; + }); + } +} +exports.default = GoTrueClient; +GoTrueClient.nextInstanceID = 0; +//# sourceMappingURL=GoTrueClient.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/GoTrueClient.js.map b/node_modules/@supabase/gotrue-js/dist/main/GoTrueClient.js.map new file mode 100644 index 0000000..9122bf0 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/GoTrueClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GoTrueClient.js","sourceRoot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ACJ,IAAI,EAAE,EAAE,OAAO,EAAE,EACjB,KAAK,EAAE,YAAY,GACpB,GAAG,MAAM,CAAA;YACV,IAAI,YAAY,EAAE;gBAChB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,YAAY,EAAE,CAAA;aAC3C;YACD,IAAI,CAAC,OAAO,EAAE;gBACZ,OAAO;oBACL,IAAI,EAAE,EAAE,YAAY,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,4BAA4B,EAAE,EAAE,EAAE;oBAC/E,KAAK,EAAE,IAAI;iBACZ,CAAA;aACF;YAED,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,YAAY,CAAC,CAAA;YAErD,IAAI,YAAY,GAAwC,IAAI,CAAA;YAE5D,IAAI,OAAO,CAAC,GAAG,EAAE;gBACf,YAAY,GAAG,OAAO,CAAC,GAAG,CAAA;aAC3B;YAED,IAAI,SAAS,GAAwC,YAAY,CAAA;YAEjE,MAAM,eAAe,GACnB,MAAA,MAAA,OAAO,CAAC,IAAI,CAAC,OAAO,0CAAE,MAAM,CAAC,CAAC,MAAc,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,KAAK,UAAU,CAAC,mCAAI,EAAE,CAAA;YAEtF,IAAI,eAAe,CAAC,MAAM,GAAG,CAAC,EAAE;gBAC9B,SAAS,GAAG,MAAM,CAAA;aACnB;YAED,MAAM,4BAA4B,GAAG,OAAO,CAAC,GAAG,IAAI,EAAE,CAAA;YAEtD,OAAO,EAAE,IAAI,EAAE,EAAE,YAAY,EAAE,SAAS,EAAE,4BAA4B,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;QACzF,CAAC,CAAC,CAAA;IACJ,CAAC;;AAvgEH,+BAwgEC;AAvgEgB,2BAAc,GAAG,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/index.d.ts b/node_modules/@supabase/gotrue-js/dist/main/index.d.ts new file mode 100644 index 0000000..55c6880 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/index.d.ts @@ -0,0 +1,7 @@ +import GoTrueAdminApi from './GoTrueAdminApi'; +import GoTrueClient from './GoTrueClient'; +export { GoTrueAdminApi, GoTrueClient }; +export * from './lib/types'; +export * from './lib/errors'; +export { navigatorLock, NavigatorLockAcquireTimeoutError, internals as lockInternals, } from './lib/locks'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/index.d.ts.map b/node_modules/@supabase/gotrue-js/dist/main/index.d.ts.map new file mode 100644 index 0000000..86d54e5 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAC7C,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,CAAA;AACvC,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,OAAO,EACL,aAAa,EACb,gCAAgC,EAChC,SAAS,IAAI,aAAa,GAC3B,MAAM,aAAa,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/index.js b/node_modules/@supabase/gotrue-js/dist/main/index.js new file mode 100644 index 0000000..87eb589 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/index.js @@ -0,0 +1,31 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.lockInternals = exports.NavigatorLockAcquireTimeoutError = exports.navigatorLock = exports.GoTrueClient = exports.GoTrueAdminApi = void 0; +const GoTrueAdminApi_1 = __importDefault(require("./GoTrueAdminApi")); +exports.GoTrueAdminApi = GoTrueAdminApi_1.default; +const GoTrueClient_1 = __importDefault(require("./GoTrueClient")); +exports.GoTrueClient = GoTrueClient_1.default; +__exportStar(require("./lib/types"), exports); +__exportStar(require("./lib/errors"), exports); +var locks_1 = require("./lib/locks"); +Object.defineProperty(exports, "navigatorLock", { enumerable: true, get: function () { return locks_1.navigatorLock; } }); +Object.defineProperty(exports, "NavigatorLockAcquireTimeoutError", { enumerable: true, get: function () { return locks_1.NavigatorLockAcquireTimeoutError; } }); +Object.defineProperty(exports, "lockInternals", { enumerable: true, get: function () { return locks_1.internals; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/index.js.map b/node_modules/@supabase/gotrue-js/dist/main/index.js.map new file mode 100644 index 0000000..cc0364d --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,sEAA6C;AAEpC,yBAFF,wBAAc,CAEE;AADvB,kEAAyC;AAChB,uBADlB,sBAAY,CACkB;AACrC,8CAA2B;AAC3B,+CAA4B;AAC5B,qCAIoB;AAHlB,sGAAA,aAAa,OAAA;AACb,yHAAA,gCAAgC,OAAA;AAChC,sGAAA,SAAS,OAAiB"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/constants.d.ts b/node_modules/@supabase/gotrue-js/dist/main/lib/constants.d.ts new file mode 100644 index 0000000..234e0cb --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/constants.d.ts @@ -0,0 +1,12 @@ +export declare const GOTRUE_URL = "http://localhost:9999"; +export declare const STORAGE_KEY = "supabase.auth.token"; +export declare const AUDIENCE = ""; +export declare const DEFAULT_HEADERS: { + 'X-Client-Info': string; +}; +export declare const EXPIRY_MARGIN = 10; +export declare const NETWORK_FAILURE: { + MAX_RETRIES: number; + RETRY_INTERVAL: number; +}; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/constants.d.ts.map b/node_modules/@supabase/gotrue-js/dist/main/lib/constants.d.ts.map new file mode 100644 index 0000000..8d3efbe --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,UAAU,0BAA0B,CAAA;AACjD,eAAO,MAAM,WAAW,wBAAwB,CAAA;AAChD,eAAO,MAAM,QAAQ,KAAK,CAAA;AAC1B,eAAO,MAAM,eAAe;;CAA8C,CAAA;AAC1E,eAAO,MAAM,aAAa,KAAK,CAAA;AAC/B,eAAO,MAAM,eAAe;;;CAG3B,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/constants.js b/node_modules/@supabase/gotrue-js/dist/main/lib/constants.js new file mode 100644 index 0000000..be2bd96 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/constants.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NETWORK_FAILURE = exports.EXPIRY_MARGIN = exports.DEFAULT_HEADERS = exports.AUDIENCE = exports.STORAGE_KEY = exports.GOTRUE_URL = void 0; +const version_1 = require("./version"); +exports.GOTRUE_URL = 'http://localhost:9999'; +exports.STORAGE_KEY = 'supabase.auth.token'; +exports.AUDIENCE = ''; +exports.DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version_1.version}` }; +exports.EXPIRY_MARGIN = 10; // in seconds +exports.NETWORK_FAILURE = { + MAX_RETRIES: 10, + RETRY_INTERVAL: 2, // in deciseconds +}; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/constants.js.map b/node_modules/@supabase/gotrue-js/dist/main/lib/constants.js.map new file mode 100644 index 0000000..74e86c6 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":";;;AAAA,uCAAmC;AACtB,QAAA,UAAU,GAAG,uBAAuB,CAAA;AACpC,QAAA,WAAW,GAAG,qBAAqB,CAAA;AACnC,QAAA,QAAQ,GAAG,EAAE,CAAA;AACb,QAAA,eAAe,GAAG,EAAE,eAAe,EAAE,aAAa,iBAAO,EAAE,EAAE,CAAA;AAC7D,QAAA,aAAa,GAAG,EAAE,CAAA,CAAC,aAAa;AAChC,QAAA,eAAe,GAAG;IAC7B,WAAW,EAAE,EAAE;IACf,cAAc,EAAE,CAAC,EAAE,iBAAiB;CACrC,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/errors.d.ts b/node_modules/@supabase/gotrue-js/dist/main/lib/errors.d.ts new file mode 100644 index 0000000..f2fcedd --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/errors.d.ts @@ -0,0 +1,82 @@ +export declare class AuthError extends Error { + status: number | undefined; + protected __isAuthError: boolean; + constructor(message: string, status?: number); +} +export declare function isAuthError(error: unknown): error is AuthError; +export declare class AuthApiError extends AuthError { + status: number; + constructor(message: string, status: number); + toJSON(): { + name: string; + message: string; + status: number; + }; +} +export declare function isAuthApiError(error: unknown): error is AuthApiError; +export declare class AuthUnknownError extends AuthError { + originalError: unknown; + constructor(message: string, originalError: unknown); +} +export declare class CustomAuthError extends AuthError { + name: string; + status: number; + constructor(message: string, name: string, status: number); + toJSON(): { + name: string; + message: string; + status: number; + }; +} +export declare class AuthSessionMissingError extends CustomAuthError { + constructor(); +} +export declare class AuthInvalidTokenResponseError extends CustomAuthError { + constructor(); +} +export declare class AuthInvalidCredentialsError extends CustomAuthError { + constructor(message: string); +} +export declare class AuthImplicitGrantRedirectError extends CustomAuthError { + details: { + error: string; + code: string; + } | null; + constructor(message: string, details?: { + error: string; + code: string; + } | null); + toJSON(): { + name: string; + message: string; + status: number; + details: { + error: string; + code: string; + } | null; + }; +} +export declare class AuthPKCEGrantCodeExchangeError extends CustomAuthError { + details: { + error: string; + code: string; + } | null; + constructor(message: string, details?: { + error: string; + code: string; + } | null); + toJSON(): { + name: string; + message: string; + status: number; + details: { + error: string; + code: string; + } | null; + }; +} +export declare class AuthRetryableFetchError extends CustomAuthError { + constructor(message: string, status: number); +} +export declare function isAuthRetryableFetchError(error: unknown): error is AuthRetryableFetchError; +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/errors.d.ts.map b/node_modules/@supabase/gotrue-js/dist/main/lib/errors.d.ts.map new file mode 100644 index 0000000..5fa1a60 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,SAAU,SAAQ,KAAK;IAClC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;IAC1B,SAAS,CAAC,aAAa,UAAO;gBAElB,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM;CAK7C;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,SAAS,CAE9D;AAED,qBAAa,YA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AAED,qBAAa,uBAAwB,SAAQ,eAAe;gBAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CAG5C;AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,uBAAuB,CAE1F"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/errors.js b/node_modules/@supabase/gotrue-js/dist/main/lib/errors.js new file mode 100644 index 0000000..9f2d35f --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/errors.js @@ -0,0 +1,119 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isAuthRetryableFetchError = exports.AuthRetryableFetchError = exports.AuthPKCEGrantCodeExchangeError = exports.AuthImplicitGrantRedirectError = exports.AuthInvalidCredentialsError = exports.AuthInvalidTokenResponseError = exports.AuthSessionMissingError = exports.CustomAuthError = exports.AuthUnknownError = exports.isAuthApiError = exports.AuthApiError = exports.isAuthError = exports.AuthError = void 0; +class AuthError extends Error { + constructor(message, status) { + super(message); + this.__isAuthError = true; + this.name = 'AuthError'; + this.status = status; + } +} +exports.AuthError = AuthError; +function isAuthError(error) { + return typeof error === 'object' && error !== null && '__isAuthError' in error; +} +exports.isAuthError = isAuthError; +class AuthApiError extends AuthError { + constructor(message, status) { + super(message, status); + this.name = 'AuthApiError'; + this.status = status; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + }; + } +} +exports.AuthApiError = AuthApiError; +function isAuthApiError(error) { + return isAuthError(error) && error.name === 'AuthApiError'; +} +exports.isAuthApiError = isAuthApiError; +class AuthUnknownError extends AuthError { + constructor(message, originalError) { + super(message); + this.name = 'AuthUnknownError'; + this.originalError = originalError; + } +} +exports.AuthUnknownError = AuthUnknownError; +class CustomAuthError extends AuthError { + constructor(message, name, status) { + super(message); + this.name = name; + this.status = status; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + }; + } +} +exports.CustomAuthError = CustomAuthError; +class AuthSessionMissingError extends CustomAuthError { + constructor() { + super('Auth session missing!', 'AuthSessionMissingError', 400); + } +} +exports.AuthSessionMissingError = AuthSessionMissingError; +class AuthInvalidTokenResponseError extends CustomAuthError { + constructor() { + super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500); + } +} +exports.AuthInvalidTokenResponseError = AuthInvalidTokenResponseError; +class AuthInvalidCredentialsError extends CustomAuthError { + constructor(message) { + super(message, 'AuthInvalidCredentialsError', 400); + } +} +exports.AuthInvalidCredentialsError = AuthInvalidCredentialsError; +class AuthImplicitGrantRedirectError extends CustomAuthError { + constructor(message, details = null) { + super(message, 'AuthImplicitGrantRedirectError', 500); + this.details = null; + this.details = details; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + }; + } +} +exports.AuthImplicitGrantRedirectError = AuthImplicitGrantRedirectError; +class AuthPKCEGrantCodeExchangeError extends CustomAuthError { + constructor(message, details = null) { + super(message, 'AuthPKCEGrantCodeExchangeError', 500); + this.details = null; + this.details = details; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + }; + } +} +exports.AuthPKCEGrantCodeExchangeError = AuthPKCEGrantCodeExchangeError; +class AuthRetryableFetchError extends CustomAuthError { + constructor(message, status) { + super(message, 'AuthRetryableFetchError', status); + } +} +exports.AuthRetryableFetchError = AuthRetryableFetchError; +function isAuthRetryableFetchError(error) { + return isAuthError(error) && error.name === 'AuthRetryableFetchError'; +} +exports.isAuthRetryableFetchError = isAuthRetryableFetchError; +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/errors.js.map b/node_modules/@supabase/gotrue-js/dist/main/lib/errors.js.map new file mode 100644 index 0000000..c9eddd8 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":";;;AAAA,MAAa,SAAU,SAAQ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A2C,IAAI,CAAA;QAGpD,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;IAED,MAAM;QACJ,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,OAAO,EAAE,IAAI,CAAC,OAAO;SACtB,CAAA;IACH,CAAC;CACF;AAfD,wEAeC;AAED,MAAa,uBAAwB,SAAQ,eAAe;IAC1D,YAAY,OAAe,EAAE,MAAc;QACzC,KAAK,CAAC,OAAO,EAAE,yBAAyB,EAAE,MAAM,CAAC,CAAA;IACnD,CAAC;CACF;AAJD,0DAIC;AAED,SAAgB,yBAAyB,CAAC,KAAc;IACtD,OAAO,WAAW,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,yBAAyB,CAAA;AACvE,CAAC;AAFD,8DAEC"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.d.ts b/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.d.ts new file mode 100644 index 0000000..40d47c5 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.d.ts @@ -0,0 +1,32 @@ +import { AuthResponse, SSOResponse, GenerateLinkResponse, UserResponse } from './types'; +export declare type Fetch = typeof fetch; +export interface FetchOptions { + headers?: { + [key: string]: string; + }; + noResolveJson?: boolean; +} +export interface FetchParameters { + signal?: AbortSignal; +} +export declare type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'DELETE'; +interface GotrueRequestOptions extends FetchOptions { + jwt?: string; + redirectTo?: string; + body?: object; + query?: { + [key: string]: string; + }; + /** + * Function that transforms api response from gotrue into a desirable / standardised format + */ + xform?: (data: any) => any; +} +export declare function _request(fetcher: Fetch, method: RequestMethodType, url: string, options?: GotrueRequestOptions): Promise; +export declare function _sessionResponse(data: any): AuthResponse; +export declare function _userResponse(data: any): UserResponse; +export declare function _ssoResponse(data: any): SSOResponse; +export declare function _generateLinkResponse(data: any): GenerateLinkResponse; +export declare function _noResolveJsonResponse(data: any): Response; +export {}; +//# sourceMappingURL=fetch.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.d.ts.map b/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.d.ts.map new file mode 100644 index 0000000..a884f38 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AACA,OAAO,EACL,YAAY,EACZ,WAAW,EAEX,oBAAoB,EAEpB,YAAY,EACb,MAAM,SAAS,CAAA;AAGhB,oBAAY,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC,MAAM,WAAW,YAAY;IAC3B,OAAO,CAAC,EAAE;QACR,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KACtB,CAAA;IACD,aAAa,CAAC,EAAE,OAAO,CAAA;CACxB;AAED,MAAM,WAAW,eAAe;IAC9B,MAAM,CAAC,EAAE,WAAW,CAAA;CACrB;AAED,oBAAY,iBAAiB,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAA;AA4CjE,UAAU,oBAAqB,SAAQ,YAAY;IACjD,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAA;IACjC;;OAEG;IACH,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,GAAG,CAAA;CAC3B;AAED,wBAAsB,QAAQ,CAC5B,OAAO,EAAE,KAAK,EACd,MAAM,EAAE,iBAAiB,EACzB,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,oBAAoB,gBAoB/B;AAsCD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,GAAG,GAAG,YAAY,CAQxD;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,GAAG,GAAG,YAAY,CAGrD;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,GAAG,GAAG,WAAW,CAEnD;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,GAAG,GAAG,oBAAoB,CAmBrE;AAED,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,GAAG,GAAG,QAAQ,CAE1D"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.js b/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.js new file mode 100644 index 0000000..43c4d43 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.js @@ -0,0 +1,136 @@ +"use strict"; +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports._noResolveJsonResponse = exports._generateLinkResponse = exports._ssoResponse = exports._userResponse = exports._sessionResponse = exports._request = void 0; +const helpers_1 = require("./helpers"); +const errors_1 = require("./errors"); +const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); +const NETWORK_ERROR_CODES = [502, 503, 504]; +async function handleError(error) { + if (!(0, helpers_1.looksLikeFetchResponse)(error)) { + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), 0); + } + if (NETWORK_ERROR_CODES.includes(error.status)) { + // status in 500...599 range - server had an error, request might be retryed. + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), error.status); + } + let data; + try { + data = await error.json(); + } + catch (e) { + throw new errors_1.AuthUnknownError(_getErrorMessage(e), e); + } + throw new errors_1.AuthApiError(_getErrorMessage(data), error.status || 500); +} +const _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === 'GET') { + return params; + } + params.headers = Object.assign({ 'Content-Type': 'application/json;charset=UTF-8' }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + return Object.assign(Object.assign({}, params), parameters); +}; +async function _request(fetcher, method, url, options) { + var _a; + const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers); + if (options === null || options === void 0 ? void 0 : options.jwt) { + headers['Authorization'] = `Bearer ${options.jwt}`; + } + const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {}; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + qs['redirect_to'] = options.redirectTo; + } + const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : ''; + const data = await _handleRequest(fetcher, method, url + queryString, { headers, noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson }, {}, options === null || options === void 0 ? void 0 : options.body); + return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null }; +} +exports._request = _request; +async function _handleRequest(fetcher, method, url, options, parameters, body) { + const requestParams = _getRequestParams(method, options, parameters, body); + let result; + try { + result = await fetcher(url, requestParams); + } + catch (e) { + console.error(e); + // fetch failed, likely due to a network or CORS error + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(e), 0); + } + if (!result.ok) { + await handleError(result); + } + if (options === null || options === void 0 ? void 0 : options.noResolveJson) { + return result; + } + try { + return await result.json(); + } + catch (e) { + await handleError(e); + } +} +function _sessionResponse(data) { + var _a; + let session = null; + if (hasSession(data)) { + session = Object.assign({}, data); + session.expires_at = (0, helpers_1.expiresAt)(data.expires_in); + } + const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; + return { data: { session, user }, error: null }; +} +exports._sessionResponse = _sessionResponse; +function _userResponse(data) { + var _a; + const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; + return { data: { user }, error: null }; +} +exports._userResponse = _userResponse; +function _ssoResponse(data) { + return { data, error: null }; +} +exports._ssoResponse = _ssoResponse; +function _generateLinkResponse(data) { + const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = __rest(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]); + const properties = { + action_link, + email_otp, + hashed_token, + redirect_to, + verification_type, + }; + const user = Object.assign({}, rest); + return { + data: { + properties, + user, + }, + error: null, + }; +} +exports._generateLinkResponse = _generateLinkResponse; +function _noResolveJsonResponse(data) { + return data; +} +exports._noResolveJsonResponse = _noResolveJsonResponse; +/** + * hasSession checks if the response object contains a valid session + * @param data A response object + * @returns true if a session is in the response + */ +function hasSession(data) { + return data.access_token && data.refresh_token && data.expires_in; +} +//# sourceMappingURL=fetch.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.js.map b/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.js.map new file mode 100644 index 0000000..9582122 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,uCAA6D;AAS7D,qCAAkF;AAiBlF,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAU,EAAE,CAC5C,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,OAAO,IAAI,GAAG,CAAC,iBAAiB,IAAI,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAA;AAErF,MAAM,mBAAmB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;AAE3C,KA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AC,IAAI,mCAAK,IAAa,CAAA;IAC9C,OAAO,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;AACxC,CAAC;AAHD,sCAGC;AAED,SAAgB,YAAY,CAAC,IAAS;IACpC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;AAC9B,CAAC;AAFD,oCAEC;AAED,SAAgB,qBAAqB,CAAC,IAAS;IAC7C,MAAM,EAAE,WAAW,EAAE,SAAS,EAAE,YAAY,EAAE,WAAW,EAAE,iBAAiB,KAAc,IAAI,EAAb,IAAI,UAAK,IAAI,EAAxF,gFAAiF,CAAO,CAAA;IAE9F,MAAM,UAAU,GAA2B;QACzC,WAAW;QACX,SAAS;QACT,YAAY;QACZ,WAAW;QACX,iBAAiB;KAClB,CAAA;IAED,MAAM,IAAI,qBAAc,IAAI,CAAE,CAAA;IAC9B,OAAO;QACL,IAAI,EAAE;YACJ,UAAU;YACV,IAAI;SACL;QACD,KAAK,EAAE,IAAI;KACZ,CAAA;AACH,CAAC;AAnBD,sDAmBC;AAED,SAAgB,sBAAsB,CAAC,IAAS;IAC9C,OAAO,IAAI,CAAA;AACb,CAAC;AAFD,wDAEC;AAED;;;;GAIG;AACH,SAAS,UAAU,CAAC,IAAS;IAC3B,OAAO,IAAI,CAAC,YAAY,IAAI,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,UAAU,CAAA;AACnE,CAAC"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/helpers.d.ts b/node_modules/@supabase/gotrue-js/dist/main/lib/helpers.d.ts new file mode 100644 index 0000000..bf793c5 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/helpers.d.ts @@ -0,0 +1,77 @@ +import { SupportedStorage } from './types'; +export declare function expiresAt(expiresIn: number): number; +export declare function uuid(): string; +export declare const isBrowser: () => boolean; +/** + * Checks whether localStorage is supported on this browser. + */ +export declare const supportsLocalStorage: () => boolean; +/** + * Extracts parameters encoded in the URL both in the query and fragment. + */ +export declare function parseParametersFromURL(href: string): { + [parameter: string]: string; +}; +declare type Fetch = typeof fetch; +export declare const resolveFetch: (customFetch?: Fetch) => Fetch; +export declare const looksLikeFetchResponse: (maybeResponse: unknown) => maybeResponse is Response; +export declare const setItemAsync: (storage: SupportedStorage, key: string, data: any) => Promise; +export declare const getItemAsync: (storage: SupportedStorage, key: string) => Promise; +export declare const removeItemAsync: (storage: SupportedStorage, key: string) => Promise; +export declare function decodeBase64URL(value: string): string; +/** + * A deferred represents some asynchronous work that is not yet finished, which + * may or may not culminate in a value. + * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts + */ +export declare class Deferred { + static promiseConstructor: PromiseConstructor; + readonly promise: PromiseLike; + readonly resolve: (value?: T | PromiseLike) => void; + readonly reject: (reason?: any) => any; + constructor(); +} +export declare function decodeJWTPayload(token: string): any; +/** + * Creates a promise that resolves to null after some time. + */ +export declare function sleep(time: number): Promise; +/** + * Converts the provided async function into a retryable function. Each result + * or thrown error is sent to the isRetryable function which should return true + * if the function should run again. + */ +export declare function retryable(fn: (attempt: number) => Promise, isRetryable: (attempt: number, error: any | null, result?: T) => boolean): Promise; +export declare function generatePKCEVerifier(): string; +export declare function generatePKCEChallenge(verifier: string): Promise; +/** + * Checks if the current caller of the function is in a {@link + * #stackGuard} of the provided `name`. Works by looking through + * the stack trace of an `Error` object for a special function + * name (generated by {@link #stackGuard}). + * + * @param name The name of the stack guard to check for. Must be `[a-zA-Z0-9_-]` only. + */ +export declare function isInStackGuard(name: string): boolean; +/** + * Creates a minification resistant stack guard, i.e. if you + * call {@link #isInStackGuard} from within the `fn` parameter + * function, you will always get `true` otherwise it will be + * `false`. + * + * Works by dynamically defining a function name before calling + * into `fn`, which is then parsed from the stack trace on an + * `Error` object within {@link #isInStackGuard}. + * + * @param name The name of the stack guard. Must be `[a-zA-Z0-9_-]` only. + * @param fn The async/await function to be run within the stack guard. + */ +export declare function stackGuard(name: string, fn: () => Promise): Promise; +/** + * Returns if the JavaScript engine supports stack guards. If it doesn't + * certain features that depend on detecting recursive calls should be disabled + * to prevent deadlocks. + */ +export declare function stackGuardsSupported(): Promise; +export {}; +//# sourceMappingURL=helpers.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/helpers.d.ts.map b/node_modules/@supabase/gotrue-js/dist/main/lib/helpers.d.ts.map new file mode 100644 index 0000000..be8393d --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAC1C,wBAAgB,SAAS,CAAC,SAAS,EAAE,MAAM,UAG1C;AAED,wBAAgB,IAAI,WAMnB;AAED,eAAO,MAAM,SAAS,eAAwC,CAAA;AAO9D;;GAEG;AACH,eAAO,MAAM,oBAAoB,eAmChC,CAAA;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM;;EAsBlD;AAED,aAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,iBAAkB,KAAK,KAAG,KAUlD,CAAA;AAED,eAAO,MAAM,sBAAsB,kBAAmB,OAAO,8BAS5D,CAAA;AAGD,eAAO,MAAM,YAAY,YACd,gBAAgB,OACpB,MAAM,QACL,GAAG,KACR,QAAQ,IAAI,CAEd,CAAA;AAED,eAAO,MAAM,YAAY,YAAmB,gBAAgB,OAAO,MAAM,KAAG,QAAQ,OAAO,CAY1F,CAAA;AAED,eAAO,MAAM,eAAe,YAAmB,gBAAgB,OAAO,MAAM,KAAG,QAAQ,IAAI,CAE1F,CAAA;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CA0BrD;AAED;;;;GAIG;AACH,qBAAa,QAAQ,CAAC,CA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new file mode 100644 index 0000000..76848f5 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/helpers.js @@ -0,0 +1,405 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.stackGuardsSupported = exports.stackGuard = exports.isInStackGuard = exports.generatePKCEChallenge = exports.generatePKCEVerifier = exports.retryable = exports.sleep = exports.decodeJWTPayload = exports.Deferred = exports.decodeBase64URL = exports.removeItemAsync = exports.getItemAsync = exports.setItemAsync = exports.looksLikeFetchResponse = exports.resolveFetch = exports.parseParametersFromURL = exports.supportsLocalStorage = exports.isBrowser = exports.uuid = exports.expiresAt = void 0; +function expiresAt(expiresIn) { + const timeNow = Math.round(Date.now() / 1000); + return timeNow + expiresIn; +} +exports.expiresAt = expiresAt; +function uuid() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +} +exports.uuid = uuid; +const isBrowser = () => typeof document !== 'undefined'; +exports.isBrowser = isBrowser; +const localStorageWriteTests = { + tested: false, + writable: false, +}; +/** + * Checks whether localStorage is supported on this browser. + */ +const supportsLocalStorage = () => { + if (!(0, exports.isBrowser)()) { + return false; + } + try { + if (typeof globalThis.localStorage !== 'object') { + return false; + } + } + catch (e) { + // DOM exception when accessing `localStorage` + return false; + } + if (localStorageWriteTests.tested) { + return localStorageWriteTests.writable; + } + const randomKey = `lswt-${Math.random()}${Math.random()}`; + try { + globalThis.localStorage.setItem(randomKey, randomKey); + globalThis.localStorage.removeItem(randomKey); + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = true; + } + catch (e) { + // localStorage can't be written to + // https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = false; + } + return localStorageWriteTests.writable; +}; +exports.supportsLocalStorage = supportsLocalStorage; +/** + * Extracts parameters encoded in the URL both in the query and fragment. + */ +function parseParametersFromURL(href) { + const result = {}; + const url = new URL(href); + if (url.hash && url.hash[0] === '#') { + try { + const hashSearchParams = new URLSearchParams(url.hash.substring(1)); + hashSearchParams.forEach((value, key) => { + result[key] = value; + }); + } + catch (e) { + // hash is not a query string + } + } + // search parameters take precedence over hash parameters + url.searchParams.forEach((value, key) => { + result[key] = value; + }); + return result; +} +exports.parseParametersFromURL = parseParametersFromURL; +const resolveFetch = (customFetch) => { + let _fetch; + if (customFetch) { + _fetch = customFetch; + } + else if (typeof fetch === 'undefined') { + _fetch = async (...args) => await (await Promise.resolve().then(() => __importStar(require('cross-fetch')))).fetch(...args); + } + else { + _fetch = fetch; + } + return (...args) => _fetch(...args); +}; +exports.resolveFetch = resolveFetch; +const looksLikeFetchResponse = (maybeResponse) => { + return (typeof maybeResponse === 'object' && + maybeResponse !== null && + 'status' in maybeResponse && + 'ok' in maybeResponse && + 'json' in maybeResponse && + typeof maybeResponse.json === 'function'); +}; +exports.looksLikeFetchResponse = looksLikeFetchResponse; +// Storage helpers +const setItemAsync = async (storage, key, data) => { + await storage.setItem(key, JSON.stringify(data)); +}; +exports.setItemAsync = setItemAsync; +const getItemAsync = async (storage, key) => { + const value = await storage.getItem(key); + if (!value) { + return null; + } + try { + return JSON.parse(value); + } + catch (_a) { + return value; + } +}; +exports.getItemAsync = getItemAsync; +const removeItemAsync = async (storage, key) => { + await storage.removeItem(key); +}; +exports.removeItemAsync = removeItemAsync; +function decodeBase64URL(value) { + const key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + let base64 = ''; + let chr1, chr2, chr3; + let enc1, enc2, enc3, enc4; + let i = 0; + value = value.replace('-', '+').replace('_', '/'); + while (i < value.length) { + enc1 = key.indexOf(value.charAt(i++)); + enc2 = key.indexOf(value.charAt(i++)); + enc3 = key.indexOf(value.charAt(i++)); + enc4 = key.indexOf(value.charAt(i++)); + chr1 = (enc1 << 2) | (enc2 >> 4); + chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); + chr3 = ((enc3 & 3) << 6) | enc4; + base64 = base64 + String.fromCharCode(chr1); + if (enc3 != 64 && chr2 != 0) { + base64 = base64 + String.fromCharCode(chr2); + } + if (enc4 != 64 && chr3 != 0) { + base64 = base64 + String.fromCharCode(chr3); + } + } + return base64; +} +exports.decodeBase64URL = decodeBase64URL; +/** + * A deferred represents some asynchronous work that is not yet finished, which + * may or may not culminate in a value. + * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts + */ +class Deferred { + constructor() { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + this.promise = new Deferred.promiseConstructor((res, rej) => { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + this.resolve = res; + this.reject = rej; + }); + } +} +exports.Deferred = Deferred; +Deferred.promiseConstructor = Promise; +// Taken from: https://stackoverflow.com/questions/38552003/how-to-decode-jwt-token-in-javascript-without-using-a-library +function decodeJWTPayload(token) { + // Regex checks for base64url format + const base64UrlRegex = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i; + const parts = token.split('.'); + if (parts.length !== 3) { + throw new Error('JWT is not valid: not a JWT structure'); + } + if (!base64UrlRegex.test(parts[1])) { + throw new Error('JWT is not valid: payload is not in base64url format'); + } + const base64Url = parts[1]; + return JSON.parse(decodeBase64URL(base64Url)); +} +exports.decodeJWTPayload = decodeJWTPayload; +/** + * Creates a promise that resolves to null after some time. + */ +async function sleep(time) { + return await new Promise((accept) => { + setTimeout(() => accept(null), time); + }); +} +exports.sleep = sleep; +/** + * Converts the provided async function into a retryable function. Each result + * or thrown error is sent to the isRetryable function which should return true + * if the function should run again. + */ +function retryable(fn, isRetryable) { + const promise = new Promise((accept, reject) => { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + (async () => { + for (let attempt = 0; attempt < Infinity; attempt++) { + try { + const result = await fn(attempt); + if (!isRetryable(attempt, null, result)) { + accept(result); + return; + } + } + catch (e) { + if (!isRetryable(attempt, e)) { + reject(e); + return; + } + } + } + })(); + }); + return promise; +} +exports.retryable = retryable; +function dec2hex(dec) { + return ('0' + dec.toString(16)).substr(-2); +} +// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs +function generatePKCEVerifier() { + const verifierLength = 56; + const array = new Uint32Array(verifierLength); + if (typeof crypto === 'undefined') { + const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'; + const charSetLen = charSet.length; + let verifier = ''; + for (let i = 0; i < verifierLength; i++) { + verifier += charSet.charAt(Math.floor(Math.random() * charSetLen)); + } + return verifier; + } + crypto.getRandomValues(array); + return Array.from(array, dec2hex).join(''); +} +exports.generatePKCEVerifier = generatePKCEVerifier; +async function sha256(randomString) { + const encoder = new TextEncoder(); + const encodedData = encoder.encode(randomString); + const hash = await crypto.subtle.digest('SHA-256', encodedData); + const bytes = new Uint8Array(hash); + return Array.from(bytes) + .map((c) => String.fromCharCode(c)) + .join(''); +} +function base64urlencode(str) { + return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} +async function generatePKCEChallenge(verifier) { + if (typeof crypto === 'undefined') { + console.warn('WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.'); + return verifier; + } + const hashed = await sha256(verifier); + return base64urlencode(hashed); +} +exports.generatePKCEChallenge = generatePKCEChallenge; +const STACK_GUARD_PREFIX = `__stack_guard__`; +const STACK_GUARD_SUFFIX = `__`; +// Firefox and WebKit based browsers encode the stack entry differently, but +// they all include the function name. So instead of trying to parse the entry, +// we're only looking for the special string `__stack_guard__${guardName}__`. +// Guard names can only be letters with dashes or underscores. +// +// Example Firefox stack trace: +// ``` +// __stack_guard__EXAMPLE__@debugger eval code:1:55 +// @debugger eval code:1:3 +// ``` +// +// Example WebKit/Chrome stack trace: +// ``` +// Error +// at Object.__stack_guard__EXAMPLE__ (:1:55) +// at :1:13 +// ``` +// +const STACK_ENTRY_REGEX = /__stack_guard__([a-zA-Z0-9_-]+)__/; +let STACK_GUARD_CHECKED = false; +let STACK_GUARD_CHECK_FN; // eslint-disable-line prefer-const +let STACK_GUARDS_SUPPORTED = false; +/** + * Checks if the current caller of the function is in a {@link + * #stackGuard} of the provided `name`. Works by looking through + * the stack trace of an `Error` object for a special function + * name (generated by {@link #stackGuard}). + * + * @param name The name of the stack guard to check for. Must be `[a-zA-Z0-9_-]` only. + */ +function isInStackGuard(name) { + var _a, _b; + STACK_GUARD_CHECK_FN(); + let error; + try { + throw new Error(); + } + catch (e) { + error = e; + } + const stack = (_b = (_a = error.stack) === null || _a === void 0 ? void 0 : _a.split('\n')) !== null && _b !== void 0 ? _b : []; + for (let i = 0; i < stack.length; i += 1) { + const entry = stack[i]; + const match = entry.match(STACK_ENTRY_REGEX); + if (match && match[1] === name) { + return true; + } + } + return false; +} +exports.isInStackGuard = isInStackGuard; +/** + * Creates a minification resistant stack guard, i.e. if you + * call {@link #isInStackGuard} from within the `fn` parameter + * function, you will always get `true` otherwise it will be + * `false`. + * + * Works by dynamically defining a function name before calling + * into `fn`, which is then parsed from the stack trace on an + * `Error` object within {@link #isInStackGuard}. + * + * @param name The name of the stack guard. Must be `[a-zA-Z0-9_-]` only. + * @param fn The async/await function to be run within the stack guard. + */ +async function stackGuard(name, fn) { + await STACK_GUARD_CHECK_FN(); + const guardName = `${STACK_GUARD_PREFIX}${name}${STACK_GUARD_SUFFIX}`; + const guardFunc = { + // per ECMAScript rules, this defines a new function with the dynamic name + // contained in the `guardName` variable + // this function name shows up in stack traces and is resistant to mangling + // from minification processes as it is determined at runtime + [guardName]: async () => await fn(), + }; + // Safari does not log the name of a dynamically named function unless you + // explicitly set the displayName + Object.assign(guardFunc[guardName], { displayName: guardName }); + return await guardFunc[guardName](); +} +exports.stackGuard = stackGuard; +/** + * Returns if the JavaScript engine supports stack guards. If it doesn't + * certain features that depend on detecting recursive calls should be disabled + * to prevent deadlocks. + */ +async function stackGuardsSupported() { + if (STACK_GUARD_CHECKED) { + return STACK_GUARDS_SUPPORTED; + } + await STACK_GUARD_CHECK_FN(); + return STACK_GUARDS_SUPPORTED; +} +exports.stackGuardsSupported = stackGuardsSupported; +let STACK_GUARD_WARNING_LOGGED = false; +// In certain cases, if this file is transpiled using an ES2015 target, or is +// running in a JS engine that does not support async/await stack traces, this +// function will log a single warning message. +STACK_GUARD_CHECK_FN = async () => { + if (!STACK_GUARD_CHECKED) { + STACK_GUARD_CHECKED = true; + await stackGuard('ENV_CHECK', async () => { + // sleeping for the next tick as Safari loses track of the async/await + // trace beyond this point + await sleep(0); + const result = isInStackGuard('ENV_CHECK'); + STACK_GUARDS_SUPPORTED = result; + if (!result && !STACK_GUARD_WARNING_LOGGED) { + STACK_GUARD_WARNING_LOGGED = true; + console.warn('@supabase/gotrue-js: Stack guards not supported in this environment. Generally not an issue but may point to a very conservative transpilation environment (use ES2017 or above) that implements async/await with generators, or this is a JavaScript engine that does not support async/await stack traces. Safari is known to not support stack guards.'); + } + return result; + }); + } +}; +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/helpers.js.map b/node_modules/@supabase/gotrue-js/dist/main/lib/helpers.js.map new file mode 100644 index 0000000..10fde18 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAgB,SAAS,CAAC,SAAiB;IACzC,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAA;IAC7C,OAAO,OAAO,GAAG,SAAS,CAAA;AAC5B,CAAC;AAHD,8BAGC;AAED,SAAgB,IAAI;IAClB,OAAO,sCAAsC,CAAC,OAAO,CAAC,OAAO,EAAE,UAAU,CAAC;QACxE,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EAChC,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,GAAG,GAAG,CAAA;QACpC,OAAO,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAA;IACvB,CAAC,CAAC,CAAA;AACJ,CAAC;AAND,oBAMC;AAEM,MAAM,SAAS,GAAG,GAAG,EAAE,CAAC,OAAO,QAAQ,KAAK,WAAW,CAAA;AAAjD,QAAA,SAAS,aAAwC;AAE9D,MAAM,sBAAsB,GAAG;IAC7B,MAAM,EAAE,KAAK;IACb,QAAQ,EAAE,KAAK;CAChB,CAAA;AAED;;GAEG;AACI,MAAM,oBAAoB,GAAG,GAAG,EAAE;IACvC,IAAI,CAAC,IAAA,iBAAS,GAAE,EAAE;QAChB,OAAO,KAAK,CAAA;KACb;IAED,IA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AS,CAAC,EAAE,KAAK,IAAI,EAAE,CAAC,MAAM,EAAE,EAAE;KACpC,CAAA;IAED,0EAA0E;IAC1E,iCAAiC;IACjC,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,EAAE,WAAW,EAAE,SAAS,EAAE,CAAC,CAAA;IAE/D,OAAO,MAAM,SAAS,CAAC,SAAS,CAAC,EAAE,CAAA;AACrC,CAAC;AApBD,gCAoBC;AAED;;;;GAIG;AACI,KAAK,UAAU,oBAAoB;IACxC,IAAI,mBAAmB,EAAE;QACvB,OAAO,sBAAsB,CAAA;KAC9B;IAED,MAAM,oBAAoB,EAAE,CAAA;IAE5B,OAAO,sBAAsB,CAAA;AAC/B,CAAC;AARD,oDAQC;AAED,IAAI,0BAA0B,GAAG,KAAK,CAAA;AAEtC,6EAA6E;AAC7E,8EAA8E;AAC9E,8CAA8C;AAC9C,oBAAoB,GAAG,KAAK,IAAI,EAAE;IAChC,IAAI,CAAC,mBAAmB,EAAE;QACxB,mBAAmB,GAAG,IAAI,CAAA;QAE1B,MAAM,UAAU,CAAC,WAAW,EAAE,KAAK,IAAI,EAAE;YACvC,sEAAsE;YACtE,0BAA0B;YAC1B,MAAM,KAAK,CAAC,CAAC,CAAC,CAAA;YAEd,MAAM,MAAM,GAAG,cAAc,CAAC,WAAW,CAAC,CAAA;YAC1C,sBAAsB,GAAG,MAAM,CAAA;YAE/B,IAAI,CAAC,MAAM,IAAI,CAAC,0BAA0B,EAAE;gBAC1C,0BAA0B,GAAG,IAAI,CAAA;gBACjC,OAAO,CAAC,IAAI,CACV,2VAA2V,CAC5V,CAAA;aACF;YAED,OAAO,MAAM,CAAA;QACf,CAAC,CAAC,CAAA;KACH;AACH,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/local-storage.d.ts b/node_modules/@supabase/gotrue-js/dist/main/lib/local-storage.d.ts new file mode 100644 index 0000000..4e090a2 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/local-storage.d.ts @@ -0,0 +1,4 @@ +import { SupportedStorage } from './types'; +declare const localStorageAdapter: SupportedStorage; +export default localStorageAdapter; +//# sourceMappingURL=local-storage.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/local-storage.d.ts.map b/node_modules/@supabase/gotrue-js/dist/main/lib/local-storage.d.ts.map new file mode 100644 index 0000000..65b92be --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/local-storage.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"local-storage.d.ts","sourceRoot":"","sources":["../../../src/lib/local-storage.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE1C,QAAA,MAAM,mBAAmB,EAAE,gBAsB1B,CAAA;AAED,eAAe,mBAAmB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/local-storage.js b/node_modules/@supabase/gotrue-js/dist/main/lib/local-storage.js new file mode 100644 index 0000000..5b7dc7b --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/local-storage.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const helpers_1 = require("./helpers"); +const localStorageAdapter = { + getItem: (key) => { + if (!(0, helpers_1.supportsLocalStorage)()) { + return null; + } + return globalThis.localStorage.getItem(key); + }, + setItem: (key, value) => { + if (!(0, helpers_1.supportsLocalStorage)()) { + return; + } + globalThis.localStorage.setItem(key, value); + }, + removeItem: (key) => { + if (!(0, helpers_1.supportsLocalStorage)()) { + return; + } + globalThis.localStorage.removeItem(key); + }, +}; +exports.default = localStorageAdapter; +//# sourceMappingURL=local-storage.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/local-storage.js.map b/node_modules/@supabase/gotrue-js/dist/main/lib/local-storage.js.map new file mode 100644 index 0000000..9381676 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/local-storage.js.map @@ -0,0 +1 @@ +{"version":3,"file":"local-storage.js","sourceRoot":"","sources":["../../../src/lib/local-storage.ts"],"names":[],"mappings":";;AAAA,uCAAgD;AAGhD,MAAM,mBAAmB,GAAqB;IAC5C,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;QACf,IAAI,CAAC,IAAA,8BAAoB,GAAE,EAAE;YAC3B,OAAO,IAAI,CAAA;SACZ;QAED,OAAO,UAAU,CAAC,YAAY,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;IAC7C,CAAC;IACD,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE;QACtB,IAAI,CAAC,IAAA,8BAAoB,GAAE,EAAE;YAC3B,OAAM;SACP;QAED,UAAU,CAAC,YAAY,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;IAC7C,CAAC;IACD,UAAU,EAAE,CAAC,GAAG,EAAE,EAAE;QAClB,IAAI,CAAC,IAAA,8BAAoB,GAAE,EAAE;YAC3B,OAAM;SACP;QAED,UAAU,CAAC,YAAY,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;IACzC,CAAC;CACF,CAAA;AAED,kBAAe,mBAAmB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/locks.d.ts b/node_modules/@supabase/gotrue-js/dist/main/lib/locks.d.ts new file mode 100644 index 0000000..6e1178d --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/locks.d.ts @@ -0,0 +1,42 @@ +/** + * @experimental + */ +export declare const internals: { + /** + * @experimental + */ + debug: boolean; +}; +export declare class NavigatorLockAcquireTimeoutError extends Error { + readonly isAcquireTimeout = true; + constructor(message: string); +} +/** + * Implements a global exclusive lock using the Navigator LockManager API. It + * is available on all browsers released after 2022-03-15 with Safari being the + * last one to release support. If the API is not available, this function will + * throw. Make sure you check availablility before configuring {@link + * GoTrueClient}. + * + * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug` + * local storage item to `true`. + * + * Internals: + * + * Since the LockManager API does not preserve stack traces for the async + * function passed in the `request` method, a trick is used where acquiring the + * lock releases a previously started promise to run the operation in the `fn` + * function. The lock waits for that promise to finish (with or without error), + * while the function will finally wait for the result anyway. + * + * @experimental + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + */ +export declare function navigatorLock(name: string, acquireTimeout: number, fn: () => Promise): Promise; +//# sourceMappingURL=locks.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/locks.d.ts.map b/node_modules/@supabase/gotrue-js/dist/main/lib/locks.d.ts.map new file mode 100644 index 0000000..a9a7dbe --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/locks.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"locks.d.ts","sourceRoot":"","sources":["../../../src/lib/locks.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,SAAS;IACpB;;OAEG;;CAMJ,CAAA;AAED,qBAAa,gCAAiC,SAAQ,KAAK;IACzD,SAAgB,gBAAgB,QAAO;gBAE3B,OAAO,EAAE,MAAM;CAG5B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAsB,aAAa,CAAC,CAAC,EACnC,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,EACtB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC,CAAC,CAAC,CA2GZ"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/locks.js b/node_modules/@supabase/gotrue-js/dist/main/lib/locks.js new file mode 100644 index 0000000..7cce4bf --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/locks.js @@ -0,0 +1,135 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.navigatorLock = exports.NavigatorLockAcquireTimeoutError = exports.internals = void 0; +/** + * @experimental + */ +exports.internals = { + /** + * @experimental + */ + debug: !!(globalThis && + globalThis.localStorage && + globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true'), +}; +class NavigatorLockAcquireTimeoutError extends Error { + constructor(message) { + super(message); + this.isAcquireTimeout = true; + } +} +exports.NavigatorLockAcquireTimeoutError = NavigatorLockAcquireTimeoutError; +/** + * Implements a global exclusive lock using the Navigator LockManager API. It + * is available on all browsers released after 2022-03-15 with Safari being the + * last one to release support. If the API is not available, this function will + * throw. Make sure you check availablility before configuring {@link + * GoTrueClient}. + * + * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug` + * local storage item to `true`. + * + * Internals: + * + * Since the LockManager API does not preserve stack traces for the async + * function passed in the `request` method, a trick is used where acquiring the + * lock releases a previously started promise to run the operation in the `fn` + * function. The lock waits for that promise to finish (with or without error), + * while the function will finally wait for the result anyway. + * + * @experimental + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + */ +async function navigatorLock(name, acquireTimeout, fn) { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout); + } + let beginOperation = null; + let rejectOperation = null; + const beginOperationPromise = new Promise((accept, reject) => { + beginOperation = accept; + rejectOperation = reject; + }); + // this lets us preserve stack traces over the operation, which the + // navigator.locks.request function does not preserve well still + const result = (async () => { + await beginOperationPromise; + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: operation start'); + } + try { + return await fn(); + } + finally { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: operation end'); + } + } + })(); + const abortController = new globalThis.AbortController(); + if (acquireTimeout > 0) { + setTimeout(() => { + beginOperation = null; + abortController.abort(); + if (rejectOperation) { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name); + } + if (rejectOperation) { + rejectOperation(new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${name}" timed out after ${acquireTimeout}ms`)); + } + beginOperation = null; + rejectOperation = null; + } + }, acquireTimeout); + } + await globalThis.navigator.locks.request(name, { + mode: 'exclusive', + ifAvailable: acquireTimeout === 0, + signal: abortController.signal, + }, async (lock) => { + if (lock) { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock acquired', name); + } + try { + if (beginOperation) { + beginOperation(); + beginOperation = null; + rejectOperation = null; + await result; + } + } + catch (e) { + // not important to handle the error here + } + finally { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock released', name); + } + } + } + else { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock not immediately available', name); + } + // no lock was available because acquireTimeout === 0 + const timeout = new Error(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`); + timeout.isAcquireTimeout = true; + if (rejectOperation) { + rejectOperation(new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`)); + } + beginOperation = null; + rejectOperation = null; + } + }); + return await result; +} +exports.navigatorLock = navigatorLock; +//# sourceMappingURL=locks.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/locks.js.map b/node_modules/@supabase/gotrue-js/dist/main/lib/locks.js.map new file mode 100644 index 0000000..3043dcd --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/locks.js.map @@ -0,0 +1 @@ +{"version":3,"file":"locks.js","sourceRoot":"","sources":["../../../src/lib/locks.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACU,QAAA,SAAS,GAAG;IACvB;;OAEG;IACH,KAAK,EAAE,CAAC,CAAC,CACP,UAAU;QACV,UAAU,CAAC,YAAY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I,KAAK,CAC5B,sDAAsD,IAAI,sBAAsB,CACjF,CAAA;YACD,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAA;YAE/B,IAAI,eAAe,EAAE;gBACnB,eAAe,CACb,IAAI,gCAAgC,CAClC,sDAAsD,IAAI,sBAAsB,CACjF,CACF,CAAA;aACF;YACD,cAAc,GAAG,IAAI,CAAA;YACrB,eAAe,GAAG,IAAI,CAAA;SACvB;IACH,CAAC,CACF,CAAA;IAED,OAAO,MAAM,MAAM,CAAA;AACrB,CAAC;AA/GD,sCA+GC"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/polyfills.d.ts b/node_modules/@supabase/gotrue-js/dist/main/lib/polyfills.d.ts new file mode 100644 index 0000000..d85562a --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/polyfills.d.ts @@ -0,0 +1,5 @@ +/** + * https://mathiasbynens.be/notes/globalthis + */ +export declare function polyfillGlobalThis(): void; +//# sourceMappingURL=polyfills.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/polyfills.d.ts.map b/node_modules/@supabase/gotrue-js/dist/main/lib/polyfills.d.ts.map new file mode 100644 index 0000000..ee5ea0f --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/polyfills.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfills.d.ts","sourceRoot":"","sources":["../../../src/lib/polyfills.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,wBAAgB,kBAAkB,SAmBjC"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/polyfills.js b/node_modules/@supabase/gotrue-js/dist/main/lib/polyfills.js new file mode 100644 index 0000000..9e146fc --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/polyfills.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.polyfillGlobalThis = void 0; +/** + * https://mathiasbynens.be/notes/globalthis + */ +function polyfillGlobalThis() { + if (typeof globalThis === 'object') + return; + try { + Object.defineProperty(Object.prototype, '__magic__', { + get: function () { + return this; + }, + configurable: true, + }); + // @ts-expect-error 'Allow access to magic' + __magic__.globalThis = __magic__; + // @ts-expect-error 'Allow access to magic' + delete Object.prototype.__magic__; + } + catch (e) { + if (typeof self !== 'undefined') { + // @ts-expect-error 'Allow access to globals' + self.globalThis = self; + } + } +} +exports.polyfillGlobalThis = polyfillGlobalThis; +//# sourceMappingURL=polyfills.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/polyfills.js.map b/node_modules/@supabase/gotrue-js/dist/main/lib/polyfills.js.map new file mode 100644 index 0000000..029a19a --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/polyfills.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfills.js","sourceRoot":"","sources":["../../../src/lib/polyfills.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,SAAgB,kBAAkB;IAChC,IAAI,OAAO,UAAU,KAAK,QAAQ;QAAE,OAAM;IAC1C,IAAI;QACF,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE;YACnD,GAAG,EAAE;gBACH,OAAO,IAAI,CAAA;YACb,CAAC;YACD,YAAY,EAAE,IAAI;SACnB,CAAC,CAAA;QACF,2CAA2C;QAC3C,SAAS,CAAC,UAAU,GAAG,SAAS,CAAA;QAChC,2CAA2C;QAC3C,OAAO,MAAM,CAAC,SAAS,CAAC,SAAS,CAAA;KAClC;IAAC,OAAO,CAAC,EAAE;QACV,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;YAC/B,6CAA6C;YAC7C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;SACvB;KACF;AACH,CAAC;AAnBD,gDAmBC"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/types.d.ts b/node_modules/@supabase/gotrue-js/dist/main/lib/types.d.ts new file mode 100644 index 0000000..9efcd2e --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/types.d.ts @@ -0,0 +1,905 @@ +import { AuthError } from './errors'; +import { Fetch } from './fetch'; +/** One of the providers supported by GoTrue. */ +export declare type Provider = 'apple' | 'azure' | 'bitbucket' | 'discord' | 'facebook' | 'figma' | 'github' | 'gitlab' | 'google' | 'kakao' | 'keycloak' | 'linkedin' | 'notion' | 'slack' | 'spotify' | 'twitch' | 'twitter' | 'workos' | 'zoom'; +export declare type AuthChangeEventMFA = 'MFA_CHALLENGE_VERIFIED'; +export declare type AuthChangeEvent = 'INITIAL_SESSION' | 'PASSWORD_RECOVERY' | 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED' | 'USER_UPDATED' | AuthChangeEventMFA; +/** + * Provide your own global lock implementation instead of the default + * implementation. The function should acquire a lock for the duration of the + * `fn` async function, such that no other client instances will be able to + * hold it at the same time. + * + * @experimental + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout should occur. If positive it + * should throw an Error with an `isAcquireTimeout` + * property set to true if the operation fails to be + * acquired after this much time (ms). + * @param fn The operation to execute when the lock is acquired. + */ +export declare type LockFunc = (name: string, acquireTimeout: number, fn: () => Promise) => Promise; +export declare type GoTrueClientOptions = { + url?: string; + headers?: { + [key: string]: string; + }; + storageKey?: string; + detectSessionInUrl?: boolean; + autoRefreshToken?: boolean; + persistSession?: boolean; + storage?: SupportedStorage; + fetch?: Fetch; + flowType?: AuthFlowType; + debug?: boolean; + /** + * Provide your own locking mechanism based on the environment. By default no locking is done at this time. + * + * @experimental + */ + lock?: LockFunc; +}; +export declare type AuthResponse = { + data: { + user: User | null; + session: Session | null; + }; + error: null; +} | { + data: { + user: null; + session: null; + }; + error: AuthError; +}; +/** + * AuthOtpResponse is returned when OTP is used. + * + * {@see AuthRsponse} + */ +export declare type AuthOtpResponse = { + data: { + user: null; + session: null; + messageId?: string | null; + }; + error: null; +} | { + data: { + user: null; + session: null; + messageId?: string | null; + }; + error: AuthError; +}; +export declare type AuthTokenResponse = { + data: { + user: User; + session: Session; + }; + error: null; +} | { + data: { + user: null; + session: null; + }; + error: AuthError; +}; +export declare type OAuthResponse = { + data: { + provider: Provider; + url: string; + }; + error: null; +} | { + data: { + provider: Provider; + url: null; + }; + error: AuthError; +}; +export declare type SSOResponse = { + data: { + /** + * URL to open in a browser which will complete the sign-in flow by + * taking the user to the identity provider's authentication flow. + * + * On browsers you can set the URL to `window.location.href` to take + * the user to the authentication flow. + */ + url: string; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +export declare type UserResponse = { + data: { + user: User; + }; + error: null; +} | { + data: { + user: null; + }; + error: AuthError; +}; +export interface Session { + /** + * The oauth provider token. If present, this can be used to make external API requests to the oauth provider used. + */ + provider_token?: string | null; + /** + * The oauth provider refresh token. If present, this can be used to refresh the provider_token via the oauth provider's API. + * Not all oauth providers return a provider refresh token. If the provider_refresh_token is missing, please refer to the oauth provider's documentation for information on how to obtain the provider refresh token. + */ + provider_refresh_token?: string | null; + /** + * The access token jwt. It is recommended to set the JWT_EXPIRY to a shorter expiry value. + */ + access_token: string; + /** + * A one-time used refresh token that never expires. + */ + refresh_token: string; + /** + * The number of seconds until the token expires (since it was issued). Returned when a login is confirmed. + */ + expires_in: number; + /** + * A timestamp of when the token will expire. Returned when a login is confirmed. + */ + expires_at?: number; + token_type: string; + user: User; +} +/** + * An authentication methord reference (AMR) entry. + * + * An entry designates what method was used by the user to verify their + * identity and at what time. + * + * @see {@link GoTrueMFAApi#getAuthenticatorAssuranceLevel}. + */ +export interface AMREntry { + /** Authentication method name. */ + method: 'password' | 'otp' | 'oauth' | 'mfa/totp' | string; + /** + * Timestamp when the method was successfully used. Represents number of + * seconds since 1st January 1970 (UNIX epoch) in UTC. + */ + timestamp: number; +} +export interface UserIdentity { + id: string; + user_id: string; + identity_data?: { + [key: string]: any; + }; + provider: string; + created_at?: string; + last_sign_in_at?: string; + updated_at?: string; +} +/** + * A MFA factor. + * + * @see {@link GoTrueMFAApi#enroll} + * @see {@link GoTrueMFAApi#listFactors} + * @see {@link GoTrueMFAAdminApi#listFactors} + */ +export interface Factor { + /** ID of the factor. */ + id: string; + /** Friendly name of the factor, useful to disambiguate between multiple factors. */ + friendly_name?: string; + /** + * Type of factor. Only `totp` supported with this version but may change in + * future versions. + */ + factor_type: 'totp' | string; + /** Factor's status. */ + status: 'verified' | 'unverified'; + created_at: string; + updated_at: string; +} +export interface UserAppMetadata { + provider?: string; + [key: string]: any; +} +export interface UserMetadata { + [key: string]: any; +} +export interface User { + id: string; + app_metadata: UserAppMetadata; + user_metadata: UserMetadata; + aud: string; + confirmation_sent_at?: string; + recovery_sent_at?: string; + email_change_sent_at?: string; + new_email?: string; + new_phone?: string; + invited_at?: string; + action_link?: string; + email?: string; + phone?: string; + created_at: string; + confirmed_at?: string; + email_confirmed_at?: string; + phone_confirmed_at?: string; + last_sign_in_at?: string; + role?: string; + updated_at?: string; + identities?: UserIdentity[]; + factors?: Factor[]; +} +export interface UserAttributes { + /** + * The user's email. + */ + email?: string; + /** + * The user's phone. + */ + phone?: string; + /** + * The user's password. + */ + password?: string; + /** + * The nonce sent for reauthentication if the user's password is to be updated. + * + * Call reauthenticate() to obtain the nonce first. + */ + nonce?: string; + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + * + */ + data?: object; +} +export interface AdminUserAttributes extends Omit { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * + * The `user_metadata` should be a JSON object that includes user-specific info, such as their first and last name. + * + * Note: When using the GoTrueAdminApi and wanting to modify a user's metadata, + * this attribute is used instead of UserAttributes data. + * + */ + user_metadata?: object; + /** + * A custom data object to store the user's application specific metadata. This maps to the `auth.users.app_metadata` column. + * + * Only a service role can modify. + * + * The `app_metadata` should be a JSON object that includes app-specific info, such as identity providers, roles, and other + * access control information. + */ + app_metadata?: object; + /** + * Confirms the user's email address if set to true. + * + * Only a service role can modify. + */ + email_confirm?: boolean; + /** + * Confirms the user's phone number if set to true. + * + * Only a service role can modify. + */ + phone_confirm?: boolean; + /** + * Determines how long a user is banned for. + * + * The format for the ban duration follows a strict sequence of decimal numbers with a unit suffix. + * Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + * + * For example, some possible durations include: '300ms', '2h45m'. + * + * Setting the ban duration to 'none' lifts the ban on the user. + */ + ban_duration?: string | 'none'; +} +export interface Subscription { + /** + * The subscriber UUID. This will be set by the client. + */ + id: string; + /** + * The function to call every time there is an event. eg: (eventName) => {} + */ + callback: (event: AuthChangeEvent, session: Session | null) => void; + /** + * Call this to remove the listener. + */ + unsubscribe: () => void; +} +export interface UpdatableFactorAttributes { + friendlyName: string; +} +export declare type SignUpWithPasswordCredentials = { + /** The user's email address. */ + email: string; + /** The user's password. */ + password: string; + options?: { + /** The redirect url embedded in the email link */ + emailRedirectTo?: string; + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +} | { + /** The user's phone number. */ + phone: string; + /** The user's password. */ + password: string; + options?: { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** Verification token received when the user completes the captcha on the site. Requires a configured WhatsApp sender on Twilio */ + captchaToken?: string; + /** Messaging channel to use (e.g. whatsapp or sms) */ + channel?: 'sms' | 'whatsapp'; + }; +}; +export declare type SignInWithPasswordCredentials = { + /** The user's email address. */ + email: string; + /** The user's password. */ + password: string; + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +} | { + /** The user's phone number. */ + phone: string; + /** The user's password. */ + password: string; + options?: { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export declare type SignInWithPasswordlessCredentials = { + /** The user's email address. */ + email: string; + options?: { + /** The redirect url embedded in the email link */ + emailRedirectTo?: string; + /** If set to false, this method will not create a new user. Defaults to true. */ + shouldCreateUser?: boolean; + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +} | { + /** The user's phone number. */ + phone: string; + options?: { + /** If set to false, this method will not create a new user. Defaults to true. */ + shouldCreateUser?: boolean; + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + /** Messaging channel to use (e.g. whatsapp or sms) */ + channel?: 'sms' | 'whatsapp'; + }; +}; +export declare type AuthFlowType = 'implicit' | 'pkce'; +export declare type SignInWithOAuthCredentials = { + /** One of the providers supported by GoTrue. */ + provider: Provider; + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string; + /** A space-separated list of scopes granted to the OAuth application. */ + scopes?: string; + /** An object of query params */ + queryParams?: { + [key: string]: string; + }; + /** If set to true does not immediately redirect the current browser context to visit the OAuth authorization page for the provider. */ + skipBrowserRedirect?: boolean; + }; +}; +export declare type SignInWithIdTokenCredentials = { + /** Provider name or OIDC `iss` value identifying which provider should be used to verify the provided token. Supported names: `google`, `apple`, `azure`, `facebook`, `keycloak` (deprecated). */ + provider: 'google' | 'apple' | 'azure' | 'facebook' | string; + /** OIDC ID token issued by the specified provider. The `iss` claim in the ID token must match the supplied provider. Some ID tokens contain an `at_hash` which require that you provide an `access_token` value to be accepted properly. If the token contains a `nonce` claim you must supply the nonce used to obtain the ID token. */ + token: string; + /** If the ID token contains an `at_hash` claim, then the hash of this value is compared to the value in the ID token. */ + access_token?: string; + /** If the ID token contains a `nonce` claim, then the hash of this value is compared to the value in the ID token. */ + nonce?: string; + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export declare type VerifyOtpParams = VerifyMobileOtpParams | VerifyEmailOtpParams | VerifyTokenHashParams; +export interface VerifyMobileOtpParams { + /** The user's phone number. */ + phone: string; + /** The otp sent to the user's phone number. */ + token: string; + /** The user's verification type. */ + type: MobileOtpType; + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string; + /** + * Verification token received when the user completes the captcha on the site. + * + * @deprecated + */ + captchaToken?: string; + }; +} +export interface VerifyEmailOtpParams { + /** The user's email address. */ + email: string; + /** The otp sent to the user's email address. */ + token: string; + /** The user's verification type. */ + type: EmailOtpType; + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string; + /** Verification token received when the user completes the captcha on the site. + * + * @deprecated + */ + captchaToken?: string; + }; +} +export interface VerifyTokenHashParams { + /** The token hash used in an email link */ + token_hash: string; + /** The user's verification type. */ + type: EmailOtpType; +} +export declare type MobileOtpType = 'sms' | 'phone_change'; +export declare type EmailOtpType = 'signup' | 'invite' | 'magiclink' | 'recovery' | 'email_change' | 'email'; +export declare type ResendParams = { + type: Extract; + email: string; + options?: { + /** A URL to send the user to after they have signed-in. */ + emailRedirectTo?: string; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +} | { + type: Extract; + phone: string; + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export declare type SignInWithSSO = { + /** UUID of the SSO provider to invoke single-sign on to. */ + providerId: string; + options?: { + /** A URL to send the user to after they have signed-in. */ + redirectTo?: string; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +} | { + /** Domain name of the organization for which to invoke single-sign on. */ + domain: string; + options?: { + /** A URL to send the user to after they have signed-in. */ + redirectTo?: string; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export declare type GenerateSignupLinkParams = { + type: 'signup'; + email: string; + password: string; + options?: Pick; +}; +export declare type GenerateInviteOrMagiclinkParams = { + type: 'invite' | 'magiclink'; + /** The user's email */ + email: string; + options?: Pick; +}; +export declare type GenerateRecoveryLinkParams = { + type: 'recovery'; + /** The user's email */ + email: string; + options?: Pick; +}; +export declare type GenerateEmailChangeLinkParams = { + type: 'email_change_current' | 'email_change_new'; + /** The user's email */ + email: string; + /** + * The user's new email. Only required if type is 'email_change_current' or 'email_change_new'. + */ + newEmail: string; + options?: Pick; +}; +export interface GenerateLinkOptions { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** The URL which will be appended to the email link generated. */ + redirectTo?: string; +} +export declare type GenerateLinkParams = GenerateSignupLinkParams | GenerateInviteOrMagiclinkParams | GenerateRecoveryLinkParams | GenerateEmailChangeLinkParams; +export declare type GenerateLinkResponse = { + data: { + properties: GenerateLinkProperties; + user: User; + }; + error: null; +} | { + data: { + properties: null; + user: null; + }; + error: AuthError; +}; +/** The properties related to the email link generated */ +export declare type GenerateLinkProperties = { + /** + * The email link to send to the user. + * The action_link follows the following format: auth/v1/verify?type={verification_type}&token={hashed_token}&redirect_to={redirect_to} + * */ + action_link: string; + /** + * The raw email OTP. + * You should send this in the email if you want your users to verify using an OTP instead of the action link. + * */ + email_otp: string; + /** + * The hashed token appended to the action link. + * */ + hashed_token: string; + /** The URL appended to the action link. */ + redirect_to: string; + /** The verification type that the email link is associated to. */ + verification_type: GenerateLinkType; +}; +export declare type GenerateLinkType = 'signup' | 'invite' | 'magiclink' | 'recovery' | 'email_change_current' | 'email_change_new'; +export declare type MFAEnrollParams = { + /** The type of factor being enrolled. */ + factorType: 'totp'; + /** Domain which the user is enrolled with. */ + issuer?: string; + /** Human readable name assigned to the factor. */ + friendlyName?: string; +}; +export declare type MFAUnenrollParams = { + /** ID of the factor being unenrolled. */ + factorId: string; +}; +export declare type MFAVerifyParams = { + /** ID of the factor being verified. Returned in enroll(). */ + factorId: string; + /** ID of the challenge being verified. Returned in challenge(). */ + challengeId: string; + /** Verification code provided by the user. */ + code: string; +}; +export declare type MFAChallengeParams = { + /** ID of the factor to be challenged. Returned in enroll(). */ + factorId: string; +}; +export declare type MFAChallengeAndVerifyParams = { + /** ID of the factor being verified. Returned in enroll(). */ + factorId: string; + /** Verification code provided by the user. */ + code: string; +}; +export declare type AuthMFAVerifyResponse = { + data: { + /** New access token (JWT) after successful verification. */ + access_token: string; + /** Type of token, typically `Bearer`. */ + token_type: string; + /** Number of seconds in which the access token will expire. */ + expires_in: number; + /** Refresh token you can use to obtain new access tokens when expired. */ + refresh_token: string; + /** Updated user profile. */ + user: User; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +export declare type AuthMFAEnrollResponse = { + data: { + /** ID of the factor that was just enrolled (in an unverified state). */ + id: string; + /** Type of MFA factor. Only `totp` supported for now. */ + type: 'totp'; + /** TOTP enrollment information. */ + totp: { + /** Contains a QR code encoding the authenticator URI. You can + * convert it to a URL by prepending `data:image/svg+xml;utf-8,` to + * the value. Avoid logging this value to the console. */ + qr_code: string; + /** The TOTP secret (also encoded in the QR code). Show this secret + * in a password-style field to the user, in case they are unable to + * scan the QR code. Avoid logging this value to the console. */ + secret: string; + /** The authenticator URI encoded within the QR code, should you need + * to use it. Avoid loggin this value to the console. */ + uri: string; + }; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +export declare type AuthMFAUnenrollResponse = { + data: { + /** ID of the factor that was successfully unenrolled. */ + id: string; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +export declare type AuthMFAChallengeResponse = { + data: { + /** ID of the newly created challenge. */ + id: string; + /** Timestamp in UNIX seconds when this challenge will no longer be usable. */ + expires_at: number; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +export declare type AuthMFAListFactorsResponse = { + data: { + /** All available factors (verified and unverified). */ + all: Factor[]; + /** Only verified TOTP factors. (A subset of `all`.) */ + totp: Factor[]; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +export declare type AuthenticatorAssuranceLevels = 'aal1' | 'aal2'; +export declare type AuthMFAGetAuthenticatorAssuranceLevelResponse = { + data: { + /** Current AAL level of the session. */ + currentLevel: AuthenticatorAssuranceLevels | null; + /** + * Next possible AAL level for the session. If the next level is higher + * than the current one, the user should go through MFA. + * + * @see {@link GoTrueMFAApi#challenge} + */ + nextLevel: AuthenticatorAssuranceLevels | null; + /** + * A list of all authentication methods attached to this session. Use + * the information here to detect the last time a user verified a + * factor, for example if implementing a step-up scenario. + */ + currentAuthenticationMethods: AMREntry[]; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +/** + * Contains the full multi-factor authentication API. + * + */ +export interface GoTrueMFAApi { + /** + * Starts the enrollment process for a new Multi-Factor Authentication (MFA) + * factor. This method creates a new `unverified` factor. + * To verify a factor, present the QR code or secret to the user and ask them to add it to their + * authenticator app. + * The user has to enter the code from their authenticator app to verify it. + * + * Upon verifying a factor, all other sessions are logged out and the current session's authenticator level is promoted to `aal2`. + * + */ + enroll(params: MFAEnrollParams): Promise; + /** + * Prepares a challenge used to verify that a user has access to a MFA + * factor. + */ + challenge(params: MFAChallengeParams): Promise; + /** + * Verifies a code against a challenge. The verification code is + * provided by the user by entering a code seen in their authenticator app. + */ + verify(params: MFAVerifyParams): Promise; + /** + * Unenroll removes a MFA factor. + * A user has to have an `aal2` authenticator level in order to unenroll a `verified` factor. + */ + unenroll(params: MFAUnenrollParams): Promise; + /** + * Helper method which creates a challenge and immediately uses the given code to verify against it thereafter. The verification code is + * provided by the user by entering a code seen in their authenticator app. + */ + challengeAndVerify(params: MFAChallengeAndVerifyParams): Promise; + /** + * Returns the list of MFA factors enabled for this user. + * + * @see {@link GoTrueMFAApi#enroll} + * @see {@link GoTrueMFAApi#getAuthenticatorAssuranceLevel} + * @see {@link GoTrueClient#getUser} + * + */ + listFactors(): Promise; + /** + * Returns the Authenticator Assurance Level (AAL) for the active session. + * + * - `aal1` (or `null`) means that the user's identity has been verified only + * with a conventional login (email+password, OTP, magic link, social login, + * etc.). + * - `aal2` means that the user's identity has been verified both with a conventional login and at least one MFA factor. + * + * Although this method returns a promise, it's fairly quick (microseconds) + * and rarely uses the network. You can use this to check whether the current + * user needs to be shown a screen to verify their MFA factors. + * + */ + getAuthenticatorAssuranceLevel(): Promise; +} +/** + * @expermental + */ +export declare type AuthMFAAdminDeleteFactorResponse = { + data: { + /** ID of the factor that was successfully deleted. */ + id: string; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +/** + * @expermental + */ +export declare type AuthMFAAdminDeleteFactorParams = { + /** ID of the MFA factor to delete. */ + id: string; + /** ID of the user whose factor is being deleted. */ + userId: string; +}; +/** + * @expermental + */ +export declare type AuthMFAAdminListFactorsResponse = { + data: { + /** All factors attached to the user. */ + factors: Factor[]; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +/** + * @expermental + */ +export declare type AuthMFAAdminListFactorsParams = { + /** ID of the user. */ + userId: string; +}; +/** + * Contains the full multi-factor authentication administration API. + * + * @expermental + */ +export interface GoTrueAdminMFAApi { + /** + * Lists all factors associated to a user. + * + */ + listFactors(params: AuthMFAAdminListFactorsParams): Promise; + /** + * Deletes a factor on a user. This will log the user out of all active + * sessions if the deleted factor was verified. + * + * @see {@link GoTrueMFAApi#unenroll} + * + * @expermental + */ + deleteFactor(params: AuthMFAAdminDeleteFactorParams): Promise; +} +declare type AnyFunction = (...args: any[]) => any; +declare type MaybePromisify = T | Promise; +declare type PromisifyMethods = { + [K in keyof T]: T[K] extends AnyFunction ? (...args: Parameters) => MaybePromisify> : T[K]; +}; +export declare type SupportedStorage = PromisifyMethods>; +export declare type InitializeResult = { + error: AuthError | null; +}; +export declare type CallRefreshTokenResult = { + session: Session; + error: null; +} | { + session: null; + error: AuthError; +}; +export declare type Pagination = { + [key: string]: any; + nextPage: number | null; + lastPage: number; + total: number; +}; +export declare type PageParams = { + /** The page number */ + page?: number; + /** Number of items returned per page */ + perPage?: number; +}; +export declare type SignOut = { + /** + * Determines which sessions should be + * logged out. Global means all + * sessions by this account. Local + * means only this session. Others + * means all other sessions except the + * current one. When using others, + * there is no sign-out event fired on + * the current session! + */ + scope?: 'global' | 'local' | 'others'; +}; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/types.d.ts.map b/node_modules/@supabase/gotrue-js/dist/main/lib/types.d.ts.map new file mode 100644 index 0000000..47b5175 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAE/B,gDAAgD;AAChD,oBAAY,QAAQ,GAChB,OAAO,GACP,OAAO,GACP,WAAW,GACX,SAAS,GACT,UAAU,GACV,OAAO,GACP,QAAQ,GACR,QAAQ,GACR,QAAQ,GACR,OAAO,GACP,UAAU,GACV,UAAU,GACV,QAAQ,GACR,OAAO,GACP,SAAS,GACT,QAAQ,GACR,SAAS,GACT,QAAQ,GACR,MAAM,CAAA;AAEV,oBAAY,kBAAkB,GAAG,wBAAwB,CAAA;AAEzD,oBAAY,eAAe,GACvB,iBAAiB,GACjB,mBAAmB,GACnB,WAAW,GACX,YAAY,GACZ,iBAAiB,GACjB,cAAc,GACd,kBAAkB,CAAA;AAEtB;;;;;;;;;;;;;;GAcG;AACH,oBAAY,QAAQ,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,CAAA;AAEpG,oBAAY,mBAAmB,GAAG;IAEhC,GAAG,CAAC,EAAE,MAAM,CAAA;IAEZ,OAAO,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EAAE,SAAS,GAAG,SAAS,GAAG,YAAY,CAAC,CAAC,CAAA;AAEpG,oBAAY,gBAAgB,GAAG;IAAE,KAAK,EAAE,SAAS,GAAG,IAAI,CAAA;CAAE,CAAA;AAE1D,oBAAY,sBAAsB,GAC9B;IACE,OAAO,EAAE,OAAO,CAAA;IAChB,KAAK,EAAE,IAAI,CAAA;CACZ,GACD;IACE,OAAO,EAAE,IAAI,CAAA;IACb,KAAK,EAAE,SAAS,CAAA;CACjB,CAAA;AAEL,oBAAY,UAAU,GAAG;IACvB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;IAClB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;IACvB,QAAQ,EAAE,MAAM,CAAA;IAChB,KAAK,EAAE,MAAM,CAAA;CACd,CAAA;AAED,oBAAY,UAAU,GAAG;IACvB,sBAAsB;IACtB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,wCAAwC;IACxC,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB,CAAA;AAED,oBAAY,OAAO,GAAG;IACpB;;;;;;;;;OASG;IACH,KAAK,CAAC,EAAE,QAAQ,GAAG,OAAO,GAAG,QAAQ,CAAA;CACtC,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/types.js b/node_modules/@supabase/gotrue-js/dist/main/lib/types.js new file mode 100644 index 0000000..11e638d --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/types.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/types.js.map b/node_modules/@supabase/gotrue-js/dist/main/lib/types.js.map new file mode 100644 index 0000000..5bb5e4d --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/version.d.ts b/node_modules/@supabase/gotrue-js/dist/main/lib/version.d.ts new file mode 100644 index 0000000..177f1a8 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.46.1"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/version.d.ts.map b/node_modules/@supabase/gotrue-js/dist/main/lib/version.d.ts.map new file mode 100644 index 0000000..808651b --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,OAAO,UAAU,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/version.js b/node_modules/@supabase/gotrue-js/dist/main/lib/version.js new file mode 100644 index 0000000..42ec398 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/version.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.version = void 0; +// Generated by genversion. +exports.version = '2.46.1'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/main/lib/version.js.map b/node_modules/@supabase/gotrue-js/dist/main/lib/version.js.map new file mode 100644 index 0000000..6c18375 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/main/lib/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":";;;AAAA,2BAA2B;AACd,QAAA,OAAO,GAAG,OAAO,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/GoTrueAdminApi.d.ts b/node_modules/@supabase/gotrue-js/dist/module/GoTrueAdminApi.d.ts new file mode 100644 index 0000000..7c747ef --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/GoTrueAdminApi.d.ts @@ -0,0 +1,99 @@ +import { Fetch } from './lib/fetch'; +import { AdminUserAttributes, GenerateLinkParams, GenerateLinkResponse, Pagination, User, UserResponse, GoTrueAdminMFAApi, PageParams } from './lib/types'; +import { AuthError } from './lib/errors'; +export default class GoTrueAdminApi { + /** Contains all MFA administration methods. */ + mfa: GoTrueAdminMFAApi; + protected url: string; + protected headers: { + [key: string]: string; + }; + protected fetch: Fetch; + constructor({ url, headers, fetch, }: { + url: string; + headers?: { + [key: string]: string; + }; + fetch?: Fetch; + }); + /** + * Removes a logged-in session. + * @param jwt A valid, logged-in JWT. + * @param scope The logout sope. + */ + signOut(jwt: string, scope?: 'global' | 'local' | 'others'): Promise<{ + data: null; + error: AuthError | null; + }>; + /** + * Sends an invite link to an email address. + * @param email The email address of the user. + * @param options Additional options to be included when inviting. + */ + inviteUserByEmail(email: string, options?: { + /** A custom data object to store additional metadata about the user. This maps to the `auth.users.user_metadata` column. */ + data?: object; + /** The URL which will be appended to the email link sent to the user's email address. Once clicked the user will end up on this URL. */ + redirectTo?: string; + }): Promise; + /** + * Generates email links and OTPs to be sent via a custom email provider. + * @param email The user's email. + * @param options.password User password. For signup only. + * @param options.data Optional user metadata. For signup only. + * @param options.redirectTo The redirect url which should be appended to the generated link + */ + generateLink(params: GenerateLinkParams): Promise; + /** + * Creates a new user. + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + createUser(attributes: AdminUserAttributes): Promise; + /** + * Get a list of users. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. + */ + listUsers(params?: PageParams): Promise<{ + data: { + users: User[]; + aud: string; + } & Pagination; + error: null; + } | { + data: { + users: []; + }; + error: AuthError; + }>; + /** + * Get user by id. + * + * @param uid The user's unique identifier + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + getUserById(uid: string): Promise; + /** + * Updates the user data. + * + * @param attributes The data you want to update. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + updateUserById(uid: string, attributes: AdminUserAttributes): Promise; + /** + * Delete a user. Requires a `service_role` key. + * + * @param id The user id you want to remove. + * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. + * Defaults to false for backward compatibility. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + deleteUser(id: string, shouldSoftDelete?: boolean): Promise; + private _listFactors; + private _deleteFactor; +} +//# sourceMappingURL=GoTrueAdminApi.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/GoTrueAdminApi.d.ts.map b/node_modules/@supabase/gotrue-js/dist/module/GoTrueAdminApi.d.ts.map new file mode 100644 index 0000000..7e8ef35 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/GoTrueAdminApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"GoTrueAdminApi.d.ts","sourceRoot":"","sources":["../../src/GoTrueAdminApi.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EAKN,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,oBAAoB,EACpB,UAAU,EACV,IAAI,EACJ,YAAY,EACZ,iBAAiB,EAKjB,UAAU,EACX,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,SAAS,EAAe,MAAM,cAAc,CAAA;AAErD,MAAM,CAAC,OAAO,OAAO,cAAc;IACjC,+CAA+C;IAC/C,GAAG,EAAE,iBAAiB,CAAA;IAEtB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,OAAO,EAAE;QACjB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KACtB,CAAA;IACD,SAAS,CAAC,KAAK,EAAE,KAAK,CAAA;gBAEV,EACV,GAAQ,EACR,OAAY,EACZ,KAAK,GACN,EAAE;QACD,GAAG,EAAE,MAAM,CAAA;QACX,O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;;;;;;OAQG;IACG,UAAU,CAAC,EAAE,EAAE,MAAM,EAAE,gBAAgB,UAAQ,GAAG,OAAO,CAAC,YAAY,CAAC;YAkB/D,YAAY;YAyBZ,aAAa;CAsB5B"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/GoTrueAdminApi.js b/node_modules/@supabase/gotrue-js/dist/module/GoTrueAdminApi.js new file mode 100644 index 0000000..c8b3886 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/GoTrueAdminApi.js @@ -0,0 +1,265 @@ +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +import { _generateLinkResponse, _noResolveJsonResponse, _request, _userResponse, } from './lib/fetch'; +import { resolveFetch } from './lib/helpers'; +import { isAuthError } from './lib/errors'; +export default class GoTrueAdminApi { + constructor({ url = '', headers = {}, fetch, }) { + this.url = url; + this.headers = headers; + this.fetch = resolveFetch(fetch); + this.mfa = { + listFactors: this._listFactors.bind(this), + deleteFactor: this._deleteFactor.bind(this), + }; + } + /** + * Removes a logged-in session. + * @param jwt A valid, logged-in JWT. + * @param scope The logout sope. + */ + async signOut(jwt, scope = 'global') { + try { + await _request(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, { + headers: this.headers, + jwt, + noResolveJson: true, + }); + return { data: null, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Sends an invite link to an email address. + * @param email The email address of the user. + * @param options Additional options to be included when inviting. + */ + async inviteUserByEmail(email, options = {}) { + try { + return await _request(this.fetch, 'POST', `${this.url}/invite`, { + body: { email, data: options.data }, + headers: this.headers, + redirectTo: options.redirectTo, + xform: _userResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Generates email links and OTPs to be sent via a custom email provider. + * @param email The user's email. + * @param options.password User password. For signup only. + * @param options.data Optional user metadata. For signup only. + * @param options.redirectTo The redirect url which should be appended to the generated link + */ + async generateLink(params) { + try { + const { options } = params, rest = __rest(params, ["options"]); + const body = Object.assign(Object.assign({}, rest), options); + if ('newEmail' in rest) { + // replace newEmail with new_email in request body + body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail; + delete body['newEmail']; + } + return await _request(this.fetch, 'POST', `${this.url}/admin/generate_link`, { + body: body, + headers: this.headers, + xform: _generateLinkResponse, + redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo, + }); + } + catch (error) { + if (isAuthError(error)) { + return { + data: { + properties: null, + user: null, + }, + error, + }; + } + throw error; + } + } + // User Admin API + /** + * Creates a new user. + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async createUser(attributes) { + try { + return await _request(this.fetch, 'POST', `${this.url}/admin/users`, { + body: attributes, + headers: this.headers, + xform: _userResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Get a list of users. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. + */ + async listUsers(params) { + var _a, _b, _c, _d, _e, _f, _g; + try { + const pagination = { nextPage: null, lastPage: 0, total: 0 }; + const response = await _request(this.fetch, 'GET', `${this.url}/admin/users`, { + headers: this.headers, + noResolveJson: true, + query: { + page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '', + per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '', + }, + xform: _noResolveJsonResponse, + }); + if (response.error) + throw response.error; + const users = await response.json(); + const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0; + const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : []; + if (links.length > 0) { + links.forEach((link) => { + const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)); + const rel = JSON.parse(link.split(';')[1].split('=')[1]); + pagination[`${rel}Page`] = page; + }); + pagination.total = parseInt(total); + } + return { data: Object.assign(Object.assign({}, users), pagination), error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { users: [] }, error }; + } + throw error; + } + } + /** + * Get user by id. + * + * @param uid The user's unique identifier + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async getUserById(uid) { + try { + return await _request(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, { + headers: this.headers, + xform: _userResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Updates the user data. + * + * @param attributes The data you want to update. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async updateUserById(uid, attributes) { + try { + return await _request(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, { + body: attributes, + headers: this.headers, + xform: _userResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Delete a user. Requires a `service_role` key. + * + * @param id The user id you want to remove. + * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. + * Defaults to false for backward compatibility. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async deleteUser(id, shouldSoftDelete = false) { + try { + return await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, { + headers: this.headers, + body: { + should_soft_delete: shouldSoftDelete, + }, + xform: _userResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + async _listFactors(params) { + try { + const { data, error } = await _request(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/factors`, { + headers: this.headers, + xform: (factors) => { + return { data: { factors }, error: null }; + }, + }); + return { data, error }; + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + async _deleteFactor(params) { + try { + const data = await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/factors/${params.id}`, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } +} +//# sourceMappingURL=GoTrueAdminApi.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/GoTrueAdminApi.js.map b/node_modules/@supabase/gotrue-js/dist/module/GoTrueAdminApi.js.map new file mode 100644 index 0000000..b27cb4c --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/GoTrueAdminApi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GoTrueAdminApi.js","sourceRoot":"","sources":["../../src/GoTrueAdminApi.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,EAEL,qBAAqB,EACrB,sBAAsB,EACtB,QAAQ,EACR,aAAa,GACd,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AAe5C,OAAO,EAAa,WAAW,EAAE,MAAM,cAAc,CAAA;AAErD,MAAM,CAAC,OAAO,OAAO,cAAc;IAUjC,YAAY,EACV,GAAG,GAAG,EAAE,EACR,OAAO,GAAG,EAAE,EACZ,KAAK,GAON;QACC,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,KAAK,GAAG,YAAY,CAAC,KAAK,CAAC,CAAA;QAChC,IAAI,CAAC,GAAG,GAAG;YACT,WAAW,EAAE,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC;YACzC,YAAY,EAAE,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC;SAC5C,CAAA;IACH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,EAAE,IAAI,CAAC,OAAO;gBACrB,KAAK,EAAE,CAAC,OAAY,EAAE,EAAE;oBACtB,OAAO,EAAE,IAAI,EAAE,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;gBAC3C,CAAC;aACF,CACF,CAAA;YACD,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;SACvB;QAAC,OAAO,KAAK,EAAE;YACd,IAAI,WAAW,CAAC,KAAK,CAAC,EAAE;gBACtB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;aAC7B;YAED,MAAM,KAAK,CAAA;SACZ;IACH,CAAC;IAEO,KAAK,CAAC,aAAa,CACzB,MAAsC;QAEtC,IAAI;YACF,MAAM,IAAI,GAAG,MAAM,QAAQ,CACzB,IAAI,CAAC,KAAK,EACV,QAAQ,EACR,GAAG,IAAI,CAAC,GAAG,gBAAgB,MAAM,CAAC,MAAM,YAAY,MAAM,CAAC,EAAE,EAAE,EAC/D;gBACE,OAAO,EAAE,IAAI,CAAC,OAAO;aACtB,CACF,CAAA;YAED,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;SAC7B;QAAC,OAAO,KAAK,EAAE;YACd,IAAI,WAAW,CAAC,KAAK,CAAC,EAAE;gBACtB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;aAC7B;YAED,MAAM,KAAK,CAAA;SACZ;IACH,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.d.ts b/node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.d.ts new file mode 100644 index 0000000..ef891af --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.d.ts @@ -0,0 +1,390 @@ +import GoTrueAdminApi from './GoTrueAdminApi'; +import { AuthError } from './lib/errors'; +import { Fetch } from './lib/fetch'; +import { Deferred } from './lib/helpers'; +import type { AuthChangeEvent, AuthResponse, AuthTokenResponse, AuthOtpResponse, CallRefreshTokenResult, GoTrueClientOptions, InitializeResult, OAuthResponse, SSOResponse, Session, SignInWithIdTokenCredentials, SignInWithOAuthCredentials, SignInWithPasswordCredentials, SignInWithPasswordlessCredentials, SignUpWithPasswordCredentials, SignInWithSSO, SignOut, Subscription, SupportedStorage, UserAttributes, UserResponse, VerifyOtpParams, GoTrueMFAApi, ResendParams, AuthFlowType, LockFunc } from './lib/types'; +export default class GoTrueClient { + private static nextInstanceID; + private instanceID; + /** + * Namespace for the GoTrue admin methods. + * These methods should only be used in a trusted server-side environment. + */ + admin: GoTrueAdminApi; + /** + * Namespace for the MFA methods. + */ + mfa: GoTrueMFAApi; + /** + * The storage key used to identify the values saved in localStorage + */ + protected storageKey: string; + /** + * The session object for the currently logged in user. If null, it means there isn't a logged-in user. + * Only used if persistSession is false. + */ + protected inMemorySession: Session | null; + protected flowType: AuthFlowType; + protected autoRefreshToken: boolean; + protected persistSession: boolean; + protected storage: SupportedStorage; + protected stateChangeEmitters: Map; + protected autoRefreshTicker: ReturnType | null; + protected visibilityChangedCallback: (() => Promise) | null; + protected refreshingDeferred: Deferred | null; + /** + * Keeps track of the async client initialization. + * When null or not yet resolved the auth state is `unknown` + * Once resolved the the auth state is known and it's save to call any further client methods. + * Keep extra care to never reject or throw uncaught errors + */ + protected initializePromise: Promise | null; + protected detectSessionInUrl: boolean; + protected url: string; + protected headers: { + [key: string]: string; + }; + protected fetch: Fetch; + protected lock: LockFunc; + /** + * Used to broadcast state change events to other tabs listening. + */ + protected broadcastChannel: BroadcastChannel | null; + protected logDebugMessages: boolean; + /** + * Create a new client for use in the browser. + */ + constructor(options: GoTrueClientOptions); + private _debug; + /** + * Initializes the client session either from the url or from storage. + * This method is automatically called when instantiating the client, but should also be called + * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). + */ + initialize(): Promise; + /** + * IMPORTANT: + * 1. Never throw in this method, as it is called from the constructor + * 2. Never return a session from this method as it would be cached over + * the whole lifetime of the client + */ + private _initialize; + /** + * Creates a new user. + * + * Be aware that if a user account exists in the system you may get back an + * error message that attempts to hide this information from the user. + * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. + * + * @returns A logged-in session if the server has "autoconfirm" ON + * @returns A user if the server has "autoconfirm" OFF + */ + signUp(credentials: SignUpWithPasswordCredentials): Promise; + /** + * Log in an existing user with an email and password or phone and password. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or that the + * email/phone and password combination is wrong or that the account can only + * be accessed via social login. + */ + signInWithPassword(credentials: SignInWithPasswordCredentials): Promise; + /** + * Log in an existing user via a third-party provider. + * This method supports the PKCE flow. + */ + signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise; + /** + * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. + */ + exchangeCodeForSession(authCode: string): Promise; + /** + * Allows signing in with an OIDC ID token. The authentication provider used + * should be enabled and configured. + */ + signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise; + /** + * Log in a user using magiclink or a one-time password (OTP). + * + * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. + * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. + * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or, that the account + * can only be accessed via social login. + * + * Do note that you will need to configure a Whatsapp sender on Twilio + * if you are using phone sign in with the 'whatsapp' channel. The whatsapp + * channel is not supported on other providers + * at this time. + * This method supports PKCE when an email is passed. + */ + signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise; + /** + * Log in a user given a User supplied OTP received via mobile. + */ + verifyOtp(params: VerifyOtpParams): Promise; + /** + * Attempts a single-sign on using an enterprise Identity Provider. A + * successful SSO attempt will redirect the current page to the identity + * provider authorization page. The redirect URL is implementation and SSO + * protocol specific. + * + * You can use it by providing a SSO domain. Typically you can extract this + * domain by asking users for their email address. If this domain is + * registered on the Auth instance the redirect will use that organization's + * currently active SSO Identity Provider for the login. + * + * If you have built an organization-specific login page, you can use the + * organization's SSO Identity Provider UUID directly instead. + */ + signInWithSSO(params: SignInWithSSO): Promise; + /** + * Sends a reauthentication OTP to the user's email or phone number. + * Requires the user to be signed-in. + */ + reauthenticate(): Promise; + /** + * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. + */ + resend(credentials: ResendParams): Promise; + /** + * Returns the session, refreshing it if necessary. + * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. + */ + getSession(): Promise<{ + data: { + session: Session; + }; + error: null; + } | { + data: { + session: null; + }; + error: AuthError; + } | { + data: { + session: null; + }; + error: null; + }>; + /** + * Acquires a global lock based on the storage key. + */ + private _acquireLock; + /** + * Use instead of {@link #getSession} inside the library. It is + * semantically usually what you want, as getting a session involves some + * processing afterwards that requires only one client operating on the + * session at once across multiple tabs or processes. + */ + private _useSession; + /** + * NEVER USE DIRECTLY! + * + * Always use {@link #_useSession}. + */ + private __loadSession; + /** + * Gets the current user details if there is an existing session. + * @param jwt Takes in an optional access token jwt. If no jwt is provided, getUser() will attempt to get the jwt from the current session. + */ + getUser(jwt?: string): Promise; + /** + * Updates user data for a logged in user. + */ + updateUser(attributes: UserAttributes, options?: { + emailRedirectTo?: string | undefined; + }): Promise; + /** + * Decodes a JWT (without performing any validation). + */ + private _decodeJWT; + /** + * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. + * If the refresh token or access token in the current session is invalid, an error will be thrown. + * @param currentSession The current session that minimally contains an access token and refresh token. + */ + setSession(currentSession: { + access_token: string; + refresh_token: string; + }): Promise; + /** + * Returns a new session, regardless of expiry status. + * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). + * If the current session's refresh token is invalid, an error will be thrown. + * @param currentSession The current session. If passed in, it must contain a refresh token. + */ + refreshSession(currentSession?: { + refresh_token: string; + }): Promise; + /** + * Gets the session data from a URL string + */ + private _getSessionFromURL; + /** + * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) + */ + private _isImplicitGrantFlow; + /** + * Checks if the current URL and backing storage contain parameters given by a PKCE flow + */ + private _isPKCEFlow; + /** + * Inside a browser context, `signOut()` will remove the logged in user from the browser session + * and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. + * + * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. + * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. + * + * If using others scope, no `SIGNED_OUT` event is fired! + */ + signOut({ scope }?: SignOut): Promise<{ + error: AuthError | null; + }>; + /** + * Receive a notification every time an auth event happens. + * @param callback A callback function to be invoked when an auth event happens. + */ + onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => void | Promise): { + data: { + subscription: Subscription; + }; + }; + private _emitInitialSession; + /** + * Sends a password reset request to an email address. + * This method supports the PKCE flow. + * @param email The email address of the user. + * @param options.redirectTo The URL to send the user to after they click the password reset link. + * @param options.captchaToken Verification token received when the user completes the captcha on the site. + */ + resetPasswordForEmail(email: string, options?: { + redirectTo?: string; + captchaToken?: string; + }): Promise<{ + data: {}; + error: null; + } | { + data: null; + error: AuthError; + }>; + /** + * Generates a new JWT. + * @param refreshToken A valid refresh token that was returned on login. + */ + private _refreshAccessToken; + private _isValidSession; + private _handleProviderSignIn; + /** + * Recovers the session from LocalStorage and refreshes + * Note: this method is async to accommodate for AsyncStorage e.g. in React native. + */ + private _recoverAndRefresh; + private _callRefreshToken; + private _notifyAllSubscribers; + /** + * set currentSession and currentUser + * process to _startAutoRefreshToken if possible + */ + private _saveSession; + private _persistSession; + private _removeSession; + /** + * Removes any registered visibilitychange callback. + * + * {@see #startAutoRefresh} + * {@see #stopAutoRefresh} + */ + private _removeVisibilityChangedCallback; + /** + * This is the private implementation of {@link #startAutoRefresh}. Use this + * within the library. + */ + private _startAutoRefresh; + /** + * This is the private implementation of {@link #stopAutoRefresh}. Use this + * within the library. + */ + private _stopAutoRefresh; + /** + * Starts an auto-refresh process in the background. The session is checked + * every few seconds. Close to the time of expiration a process is started to + * refresh the session. If refreshing fails it will be retried for as long as + * necessary. + * + * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need + * to call this function, it will be called for you. + * + * On browsers the refresh process works only when the tab/window is in the + * foreground to conserve resources as well as prevent race conditions and + * flooding auth with requests. If you call this method any managed + * visibility change callback will be removed and you must manage visibility + * changes on your own. + * + * On non-browser platforms the refresh process works *continuously* in the + * background, which may not be desirable. You should hook into your + * platform's foreground indication mechanism and call these methods + * appropriately to conserve resources. + * + * {@see #stopAutoRefresh} + */ + startAutoRefresh(): Promise; + /** + * Stops an active auto refresh process running in the background (if any). + * + * If you call this method any managed visibility change callback will be + * removed and you must manage visibility changes on your own. + * + * See {@link #startAutoRefresh} for more details. + */ + stopAutoRefresh(): Promise; + /** + * Runs the auto refresh token tick. + */ + private _autoRefreshTokenTick; + /** + * Registers callbacks on the browser / platform, which in-turn run + * algorithms when the browser window/tab are in foreground. On non-browser + * platforms it assumes always foreground. + */ + private _handleVisibilityChange; + /** + * Callback registered with `window.addEventListener('visibilitychange')`. + */ + private _onVisibilityChanged; + /** + * Generates the relevant login URL for a third-party provider. + * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. + * @param options.scopes A space-separated list of scopes granted to the OAuth application. + * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. + */ + private _getUrlForProvider; + private _unenroll; + /** + * {@see GoTrueMFAApi#enroll} + */ + private _enroll; + /** + * {@see GoTrueMFAApi#verify} + */ + private _verify; + /** + * {@see GoTrueMFAApi#challenge} + */ + private _challenge; + /** + * {@see GoTrueMFAApi#challengeAndVerify} + */ + private _challengeAndVerify; + /** + * {@see GoTrueMFAApi#listFactors} + */ + private _listFactors; + /** + * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} + */ + private _getAuthenticatorAssuranceLevel; +} +//# sourceMappingURL=GoTrueClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.d.ts.map b/node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.d.ts.map new file mode 100644 index 0000000..f96818a --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"GoTrueClient.d.ts","sourceRoot":"","sources":["../../src/GoTrueClient.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAE7C,OAAO,EACL,SAAS,EAWV,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,KAAK,EAA2D,MAAM,aAAa,CAAA;AAC5F,OAAO,EAEL,QAAQ,EAgBT,MAAM,eAAe,CAAA;AAKtB,OAAO,KAAK,EACV,eAAe,EACf,YAAY,EACZ,iBAAiB,EACjB,eAAe,EACf,sBAAsB,EACtB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,WAAW,EAEX,OAAO,EACP,4BAA4B,EAC5B,0BAA0B,EAC1B,6BAA6B,EAC7B,iCAAiC,EACjC,6BAA6B,EAC7B,aAAa,EACb,OAAO,EACP,YAAY,EACZ,gBAAgB,EAEhB,cAAc,EACd,YAAY,EACZ,eAAe,EACf,YAAY,EAeZ,YAAY,EACZ,YAAY,EACZ,QAAQ,EACT,MAAM,aAAa,CAAA;AA0BpB,MAAM,CAAC,OAAO,OAAO,YAAY;IAC/B,OAAO,CAAC,MAAM,CAAC,cAAc,CAAI;IAEjC,OAAO,CAAC,UAAU,CAAQ;IAE1B;;;OAGG;IACH,KAAK,EAAE,cAAc,CAAA;IACrB;;OAEG;IACH,GAAG,EAAE,YAAY,CAAA;IACjB;;OAEG;IACH,SAAS,CAAC,UAAU,EAAE,MAAM,CAAA;IAE5B;;;OAGG;IACH,SAAS,CAAC,eAAe,EAAE,OAAO,GAAG,IAAI,CAAA;IAEzC,SAAS,CAAC,QAAQ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AgB;IAW9B;;;;;;;;;;;;;;;;;;;;;OAqBG;IACG,gBAAgB;IAKtB;;;;;;;OAOG;IACG,eAAe;IAKrB;;OAEG;YACW,qBAAqB;IAuCnC;;;;OAIG;YACW,uBAAuB;IAyBrC;;OAEG;YACW,oBAAoB;IA+BlC;;;;;OAKG;YACW,kBAAkB;YA6ClB,SAAS;IAqBvB;;OAEG;YACW,OAAO;IAoCrB;;OAEG;YACW,OAAO;IAsCrB;;OAEG;YACW,UAAU;IA0BxB;;OAEG;YACW,mBAAmB;IAgBjC;;OAEG;YACW,YAAY;IAuB1B;;OAEG;YACW,+BAA+B;CAsC9C"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js b/node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js new file mode 100644 index 0000000..af78b74 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js @@ -0,0 +1,1665 @@ +import GoTrueAdminApi from './GoTrueAdminApi'; +import { DEFAULT_HEADERS, EXPIRY_MARGIN, GOTRUE_URL, STORAGE_KEY } from './lib/constants'; +import { AuthImplicitGrantRedirectError, AuthPKCEGrantCodeExchangeError, AuthInvalidCredentialsError, AuthSessionMissingError, AuthInvalidTokenResponseError, AuthUnknownError, isAuthApiError, isAuthError, isAuthRetryableFetchError, } from './lib/errors'; +import { _request, _sessionResponse, _userResponse, _ssoResponse } from './lib/fetch'; +import { decodeJWTPayload, Deferred, getItemAsync, isBrowser, removeItemAsync, resolveFetch, setItemAsync, uuid, retryable, sleep, generatePKCEVerifier, generatePKCEChallenge, supportsLocalStorage, stackGuard, isInStackGuard, stackGuardsSupported, parseParametersFromURL, } from './lib/helpers'; +import localStorageAdapter from './lib/local-storage'; +import { polyfillGlobalThis } from './lib/polyfills'; +import { version } from './lib/version'; +polyfillGlobalThis(); // Make "globalThis" available +const DEFAULT_OPTIONS = { + url: GOTRUE_URL, + storageKey: STORAGE_KEY, + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + headers: DEFAULT_HEADERS, + flowType: 'implicit', + debug: false, +}; +/** Current session will be checked for refresh at this interval. */ +const AUTO_REFRESH_TICK_DURATION = 30 * 1000; +/** + * A token refresh will be attempted this many ticks before the current session expires. */ +const AUTO_REFRESH_TICK_THRESHOLD = 3; +async function lockNoOp(name, acquireTimeout, fn) { + return await fn(); +} +export default class GoTrueClient { + /** + * Create a new client for use in the browser. + */ + constructor(options) { + var _a; + this.stateChangeEmitters = new Map(); + this.autoRefreshTicker = null; + this.visibilityChangedCallback = null; + this.refreshingDeferred = null; + /** + * Keeps track of the async client initialization. + * When null or not yet resolved the auth state is `unknown` + * Once resolved the the auth state is known and it's save to call any further client methods. + * Keep extra care to never reject or throw uncaught errors + */ + this.initializePromise = null; + this.detectSessionInUrl = true; + /** + * Used to broadcast state change events to other tabs listening. + */ + this.broadcastChannel = null; + this.instanceID = GoTrueClient.nextInstanceID; + GoTrueClient.nextInstanceID += 1; + if (this.instanceID > 0 && isBrowser()) { + console.warn('Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.'); + } + const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options); + this.logDebugMessages = settings.debug; + this.inMemorySession = null; + this.storageKey = settings.storageKey; + this.autoRefreshToken = settings.autoRefreshToken; + this.persistSession = settings.persistSession; + this.storage = settings.storage || localStorageAdapter; + this.admin = new GoTrueAdminApi({ + url: settings.url, + headers: settings.headers, + fetch: settings.fetch, + }); + this.url = settings.url; + this.headers = settings.headers; + this.fetch = resolveFetch(settings.fetch); + this.lock = settings.lock || lockNoOp; + this.detectSessionInUrl = settings.detectSessionInUrl; + this.flowType = settings.flowType; + this.mfa = { + verify: this._verify.bind(this), + enroll: this._enroll.bind(this), + unenroll: this._unenroll.bind(this), + challenge: this._challenge.bind(this), + listFactors: this._listFactors.bind(this), + challengeAndVerify: this._challengeAndVerify.bind(this), + getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this), + }; + if (this.persistSession && this.storage === localStorageAdapter && !supportsLocalStorage()) { + console.warn(`No storage option exists to persist the session, which may result in unexpected behavior when using auth. + If you want to set persistSession to true, please provide a storage option or you may set persistSession to false to disable this warning.`); + } + if (isBrowser() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) { + try { + this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey); + } + catch (e) { + console.error('Failed to create a new BroadcastChannel, multi-tab state changes will not be available', e); + } + (_a = this.broadcastChannel) === null || _a === void 0 ? void 0 : _a.addEventListener('message', async (event) => { + this._debug('received broadcast notification from other tab or client', event); + await this._notifyAllSubscribers(event.data.event, event.data.session, false); // broadcast = false so we don't get an endless loop of messages + }); + } + this.initialize(); + } + _debug(...args) { + if (this.logDebugMessages) { + console.log(`GoTrueClient@${this.instanceID} (${version}) ${new Date().toISOString()}`, ...args); + } + return this; + } + /** + * Initializes the client session either from the url or from storage. + * This method is automatically called when instantiating the client, but should also be called + * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). + */ + initialize() { + if (this.initializePromise) { + return this.initializePromise; + } + return this._initialize(); + } + /** + * IMPORTANT: + * 1. Never throw in this method, as it is called from the constructor + * 2. Never return a session from this method as it would be cached over + * the whole lifetime of the client + */ + async _initialize() { + if (this.initializePromise) { + throw new Error('Double call of #_initialize()'); + } + this.initializePromise = this._acquireLock(-1, async () => await stackGuard('_initialize', async () => { + try { + const isPKCEFlow = isBrowser() ? await this._isPKCEFlow() : false; + this._debug('#_initialize()', 'begin', 'is PKCE flow', isPKCEFlow); + if (isPKCEFlow || (this.detectSessionInUrl && this._isImplicitGrantFlow())) { + const { data, error } = await this._getSessionFromURL(isPKCEFlow); + if (error) { + this._debug('#_initialize()', 'error detecting session from URL', error); + // failed login attempt via url, + // remove old session as in verifyOtp, signUp and signInWith* + await this._removeSession(); + return { error }; + } + const { session, redirectType } = data; + this._debug('#_initialize()', 'detected session in URL', session, 'redirect type', redirectType); + await this._saveSession(session); + setTimeout(async () => { + if (redirectType === 'recovery') { + await this._notifyAllSubscribers('PASSWORD_RECOVERY', session); + } + else { + await this._notifyAllSubscribers('SIGNED_IN', session); + } + }, 0); + return { error: null }; + } + // no login attempt via callback url try to recover session from storage + await this._recoverAndRefresh(); + return { error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { error }; + } + return { + error: new AuthUnknownError('Unexpected error during initialization', error), + }; + } + finally { + await this._handleVisibilityChange(); + this._debug('#_initialize()', 'end'); + } + })); + return await this.initializePromise; + } + /** + * Creates a new user. + * + * Be aware that if a user account exists in the system you may get back an + * error message that attempts to hide this information from the user. + * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. + * + * @returns A logged-in session if the server has "autoconfirm" ON + * @returns A user if the server has "autoconfirm" OFF + */ + async signUp(credentials) { + var _a, _b, _c; + try { + await this._removeSession(); + let res; + if ('email' in credentials) { + const { email, password, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + const codeVerifier = generatePKCEVerifier(); + await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier); + codeChallenge = await generatePKCEChallenge(codeVerifier); + codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'; + } + res = await _request(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: { + email, + password, + data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + xform: _sessionResponse, + }); + } + else if ('phone' in credentials) { + const { phone, password, options } = credentials; + res = await _request(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + body: { + phone, + password, + data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {}, + channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : 'sms', + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: _sessionResponse, + }); + } + else { + throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); + } + const { data, error } = res; + if (error || !data) { + return { data: { user: null, session: null }, error: error }; + } + const session = data.session; + const user = data.user; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return { data: { user, session }, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Log in an existing user with an email and password or phone and password. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or that the + * email/phone and password combination is wrong or that the account can only + * be accessed via social login. + */ + async signInWithPassword(credentials) { + try { + await this._removeSession(); + let res; + if ('email' in credentials) { + const { email, password, options } = credentials; + res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + email, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: _sessionResponse, + }); + } + else if ('phone' in credentials) { + const { phone, password, options } = credentials; + res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + phone, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: _sessionResponse, + }); + } + else { + throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); + } + const { data, error } = res; + if (error) { + return { data: { user: null, session: null }, error }; + } + else if (!data || !data.session || !data.user) { + return { data: { user: null, session: null }, error: new AuthInvalidTokenResponseError() }; + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return { data: { user: data.user, session: data.session }, error }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Log in an existing user via a third-party provider. + * This method supports the PKCE flow. + */ + async signInWithOAuth(credentials) { + var _a, _b, _c, _d; + await this._removeSession(); + return await this._handleProviderSignIn(credentials.provider, { + redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, + scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, + queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, + skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect, + }); + } + /** + * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. + */ + async exchangeCodeForSession(authCode) { + const codeVerifier = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`); + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=pkce`, { + headers: this.headers, + body: { + auth_code: authCode, + code_verifier: codeVerifier, + }, + xform: _sessionResponse, + }); + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + if (error) { + return { data: { user: null, session: null }, error }; + } + else if (!data || !data.session || !data.user) { + return { data: { user: null, session: null }, error: new AuthInvalidTokenResponseError() }; + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return { data, error }; + } + /** + * Allows signing in with an OIDC ID token. The authentication provider used + * should be enabled and configured. + */ + async signInWithIdToken(credentials) { + await this._removeSession(); + try { + const { options, provider, token, access_token, nonce } = credentials; + const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + body: { + provider, + id_token: token, + access_token, + nonce, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: _sessionResponse, + }); + const { data, error } = res; + if (error) { + return { data: { user: null, session: null }, error }; + } + else if (!data || !data.session || !data.user) { + return { + data: { user: null, session: null }, + error: new AuthInvalidTokenResponseError(), + }; + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return { data, error }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Log in a user using magiclink or a one-time password (OTP). + * + * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. + * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. + * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or, that the account + * can only be accessed via social login. + * + * Do note that you will need to configure a Whatsapp sender on Twilio + * if you are using phone sign in with the 'whatsapp' channel. The whatsapp + * channel is not supported on other providers + * at this time. + * This method supports PKCE when an email is passed. + */ + async signInWithOtp(credentials) { + var _a, _b, _c, _d, _e; + try { + await this._removeSession(); + if ('email' in credentials) { + const { email, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + const codeVerifier = generatePKCEVerifier(); + await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier); + codeChallenge = await generatePKCEChallenge(codeVerifier); + codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'; + } + const { error } = await _request(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + email, + data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, + create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + }); + return { data: { user: null, session: null }, error }; + } + if ('phone' in credentials) { + const { phone, options } = credentials; + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + phone, + data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {}, + create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + channel: (_e = options === null || options === void 0 ? void 0 : options.channel) !== null && _e !== void 0 ? _e : 'sms', + }, + }); + return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error }; + } + throw new AuthInvalidCredentialsError('You must provide either an email or phone number.'); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Log in a user given a User supplied OTP received via mobile. + */ + async verifyOtp(params) { + var _a, _b; + try { + if (params.type !== 'email_change' && params.type !== 'phone_change') { + // we don't want to remove the authenticated session if the user is performing an email_change or phone_change verification + await this._removeSession(); + } + let redirectTo = undefined; + let captchaToken = undefined; + if ('options' in params) { + redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo; + captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken; + } + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/verify`, { + headers: this.headers, + body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }), + redirectTo, + xform: _sessionResponse, + }); + if (error) { + throw error; + } + if (!data) { + throw new Error('An error occurred on token verification.'); + } + const session = data.session; + const user = data.user; + if (session === null || session === void 0 ? void 0 : session.access_token) { + await this._saveSession(session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return { data: { user, session }, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Attempts a single-sign on using an enterprise Identity Provider. A + * successful SSO attempt will redirect the current page to the identity + * provider authorization page. The redirect URL is implementation and SSO + * protocol specific. + * + * You can use it by providing a SSO domain. Typically you can extract this + * domain by asking users for their email address. If this domain is + * registered on the Auth instance the redirect will use that organization's + * currently active SSO Identity Provider for the login. + * + * If you have built an organization-specific login page, you can use the + * organization's SSO Identity Provider UUID directly instead. + */ + async signInWithSSO(params) { + var _a, _b, _c; + try { + await this._removeSession(); + return await _request(this.fetch, 'POST', `${this.url}/sso`, { + body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, ('providerId' in params ? { provider_id: params.providerId } : null)), ('domain' in params ? { domain: params.domain } : null)), { redirect_to: (_b = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo) !== null && _b !== void 0 ? _b : undefined }), (((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken) + ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } + : null)), { skip_http_redirect: true }), + headers: this.headers, + xform: _ssoResponse, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Sends a reauthentication OTP to the user's email or phone number. + * Requires the user to be signed-in. + */ + async reauthenticate() { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) + throw sessionError; + if (!session) + throw new AuthSessionMissingError(); + const { error } = await _request(this.fetch, 'GET', `${this.url}/reauthenticate`, { + headers: this.headers, + jwt: session.access_token, + }); + return { data: { user: null, session: null }, error }; + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. + */ + async resend(credentials) { + try { + if (credentials.type != 'email_change' && credentials.type != 'phone_change') { + await this._removeSession(); + } + const endpoint = `${this.url}/resend`; + if ('email' in credentials) { + const { email, type, options } = credentials; + const { error } = await _request(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + email, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + }); + return { data: { user: null, session: null }, error }; + } + else if ('phone' in credentials) { + const { phone, type, options } = credentials; + const { data, error } = await _request(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + phone, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + }); + return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error }; + } + throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a type'); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Returns the session, refreshing it if necessary. + * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. + */ + async getSession() { + return this._useSession(async (result) => { + return result; + }); + } + /** + * Acquires a global lock based on the storage key. + */ + async _acquireLock(acquireTimeout, fn) { + this._debug('#_acquireLock', 'begin', acquireTimeout); + try { + if (!(await stackGuardsSupported())) { + this._debug('#_acquireLock', 'Stack guards not supported, so exclusive locking is not performed as it can lead to deadlocks if the lock is attempted to be recursively acquired (as the recursion cannot be detected).'); + return await fn(); + } + if (isInStackGuard('_acquireLock')) { + this._debug('#_acquireLock', 'recursive call'); + return await fn(); + } + return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => { + this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey); + try { + return await stackGuard('_acquireLock', async () => { + return await fn(); + }); + } + finally { + this._debug('#_acquireLock', 'lock released for storage key', this.storageKey); + } + }); + } + finally { + this._debug('#_acquireLock', 'end'); + } + } + /** + * Use instead of {@link #getSession} inside the library. It is + * semantically usually what you want, as getting a session involves some + * processing afterwards that requires only one client operating on the + * session at once across multiple tabs or processes. + */ + async _useSession(fn) { + this._debug('#_useSession', 'begin'); + try { + if (isInStackGuard('_useSession')) { + this._debug('#_useSession', 'recursive call'); + // the use of __loadSession here is the only correct use of the function! + const result = await this.__loadSession(); + return await fn(result); + } + return await this._acquireLock(-1, async () => { + return await stackGuard('_useSession', async () => { + // the use of __loadSession here is the only correct use of the function! + const result = await this.__loadSession(); + return await fn(result); + }); + }); + } + finally { + this._debug('#_useSession', 'end'); + } + } + /** + * NEVER USE DIRECTLY! + * + * Always use {@link #_useSession}. + */ + async __loadSession() { + this._debug('#__loadSession()', 'begin'); + if (this.logDebugMessages && !isInStackGuard('_useSession') && (await stackGuardsSupported())) { + throw new Error('Please use #_useSession()'); + } + if (isInStackGuard('_initialize')) { + this._debug('#__loadSession', '#_initialize recursion detected', new Error().stack); + } + // always wait for #_initialize() to finish before loading anything from + // storage + await this.initializePromise; + try { + let currentSession = null; + if (this.persistSession) { + const maybeSession = await getItemAsync(this.storage, this.storageKey); + this._debug('#getSession()', 'session from storage', maybeSession); + if (maybeSession !== null) { + if (this._isValidSession(maybeSession)) { + currentSession = maybeSession; + } + else { + this._debug('#getSession()', 'session from storage is not valid'); + await this._removeSession(); + } + } + } + else { + currentSession = this.inMemorySession; + this._debug('#getSession()', 'session from memory', currentSession); + } + if (!currentSession) { + return { data: { session: null }, error: null }; + } + const hasExpired = currentSession.expires_at + ? currentSession.expires_at <= Date.now() / 1000 + : false; + this._debug('#__loadSession()', `session has${hasExpired ? '' : ' not'} expired`, 'expires_at', currentSession.expires_at); + if (!hasExpired) { + return { data: { session: currentSession }, error: null }; + } + const { session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return { data: { session: null }, error }; + } + return { data: { session }, error: null }; + } + finally { + this._debug('#__loadSession()', 'end'); + } + } + /** + * Gets the current user details if there is an existing session. + * @param jwt Takes in an optional access token jwt. If no jwt is provided, getUser() will attempt to get the jwt from the current session. + */ + async getUser(jwt) { + try { + if (jwt) { + return await _request(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: jwt, + xform: _userResponse, + }); + } + return await this._useSession(async (result) => { + var _a, _b; + const { data, error } = result; + if (error) { + throw error; + } + return await _request(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : undefined, + xform: _userResponse, + }); + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Updates user data for a logged in user. + */ + async updateUser(attributes, options = {}) { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + throw sessionError; + } + if (!sessionData.session) { + throw new AuthSessionMissingError(); + } + const session = sessionData.session; + const { data, error: userError } = await _request(this.fetch, 'PUT', `${this.url}/user`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: attributes, + jwt: session.access_token, + xform: _userResponse, + }); + if (userError) + throw userError; + session.user = data.user; + await this._saveSession(session); + await this._notifyAllSubscribers('USER_UPDATED', session); + return { data: { user: session.user }, error: null }; + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Decodes a JWT (without performing any validation). + */ + _decodeJWT(jwt) { + return decodeJWTPayload(jwt); + } + /** + * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. + * If the refresh token or access token in the current session is invalid, an error will be thrown. + * @param currentSession The current session that minimally contains an access token and refresh token. + */ + async setSession(currentSession) { + try { + if (!currentSession.access_token || !currentSession.refresh_token) { + throw new AuthSessionMissingError(); + } + const timeNow = Date.now() / 1000; + let expiresAt = timeNow; + let hasExpired = true; + let session = null; + const payload = decodeJWTPayload(currentSession.access_token); + if (payload.exp) { + expiresAt = payload.exp; + hasExpired = expiresAt <= timeNow; + } + if (hasExpired) { + const { session: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return { data: { user: null, session: null }, error: error }; + } + if (!refreshedSession) { + return { data: { user: null, session: null }, error: null }; + } + session = refreshedSession; + } + else { + const { data, error } = await this.getUser(currentSession.access_token); + if (error) { + throw error; + } + session = { + access_token: currentSession.access_token, + refresh_token: currentSession.refresh_token, + user: data.user, + token_type: 'bearer', + expires_in: expiresAt - timeNow, + expires_at: expiresAt, + }; + await this._saveSession(session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return { data: { user: session.user, session }, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { session: null, user: null }, error }; + } + throw error; + } + } + /** + * Returns a new session, regardless of expiry status. + * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). + * If the current session's refresh token is invalid, an error will be thrown. + * @param currentSession The current session. If passed in, it must contain a refresh token. + */ + async refreshSession(currentSession) { + try { + return await this._useSession(async (result) => { + var _a; + if (!currentSession) { + const { data, error } = result; + if (error) { + throw error; + } + currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : undefined; + } + if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) { + throw new AuthSessionMissingError(); + } + const { session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return { data: { user: null, session: null }, error: error }; + } + if (!session) { + return { data: { user: null, session: null }, error: null }; + } + return { data: { user: session.user, session }, error: null }; + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error }; + } + throw error; + } + } + /** + * Gets the session data from a URL string + */ + async _getSessionFromURL(isPKCEFlow) { + try { + if (!isBrowser()) + throw new AuthImplicitGrantRedirectError('No browser detected.'); + if (this.flowType === 'implicit' && !this._isImplicitGrantFlow()) { + throw new AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.'); + } + else if (this.flowType == 'pkce' && !isPKCEFlow) { + throw new AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.'); + } + const params = parseParametersFromURL(window.location.href); + if (isPKCEFlow) { + if (!params.code) + throw new AuthPKCEGrantCodeExchangeError('No code detected.'); + const { data, error } = await this.exchangeCodeForSession(params.code); + if (error) + throw error; + const url = new URL(window.location.href); + url.searchParams.delete('code'); + window.history.replaceState(window.history.state, '', url.toString()); + return { data: { session: data.session, redirectType: null }, error: null }; + } + if (params.error || params.error_description || params.error_code) { + throw new AuthImplicitGrantRedirectError(params.error_description || 'Error in URL with unspecified error_description', { + error: params.error || 'unspecified_error', + code: params.error_code || 'unspecified_code', + }); + } + const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, token_type, } = params; + if (!access_token || !expires_in || !refresh_token || !token_type) { + throw new AuthImplicitGrantRedirectError('No session defined in URL'); + } + const timeNow = Math.round(Date.now() / 1000); + const expiresIn = parseInt(expires_in); + const expires_at = timeNow + expiresIn; + const { data, error } = await this.getUser(access_token); + if (error) + throw error; + const session = { + provider_token, + provider_refresh_token, + access_token, + expires_in: expiresIn, + expires_at, + refresh_token, + token_type, + user: data.user, + }; + // Remove tokens from URL + window.location.hash = ''; + this._debug('#_getSessionFromURL()', 'clearing window.location.hash'); + return { data: { session, redirectType: params.type }, error: null }; + } + catch (error) { + if (isAuthError(error)) { + return { data: { session: null, redirectType: null }, error }; + } + throw error; + } + } + /** + * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) + */ + _isImplicitGrantFlow() { + const params = parseParametersFromURL(window.location.href); + return !!(isBrowser() && (params.access_token || params.error_description)); + } + /** + * Checks if the current URL and backing storage contain parameters given by a PKCE flow + */ + async _isPKCEFlow() { + const params = parseParametersFromURL(window.location.href); + const currentStorageContent = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`); + return !!(params.code && currentStorageContent); + } + /** + * Inside a browser context, `signOut()` will remove the logged in user from the browser session + * and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. + * + * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. + * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. + * + * If using others scope, no `SIGNED_OUT` event is fired! + */ + async signOut({ scope } = { scope: 'global' }) { + return await this._useSession(async (result) => { + var _a; + const { data, error: sessionError } = result; + if (sessionError) { + return { error: sessionError }; + } + const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token; + if (accessToken) { + const { error } = await this.admin.signOut(accessToken, scope); + if (error) { + // ignore 404s since user might not exist anymore + // ignore 401s since an invalid or expired JWT should sign out the current session + if (!(isAuthApiError(error) && (error.status === 404 || error.status === 401))) { + return { error }; + } + } + } + if (scope !== 'others') { + await this._removeSession(); + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`); + await this._notifyAllSubscribers('SIGNED_OUT', null); + } + return { error: null }; + }); + } + /** + * Receive a notification every time an auth event happens. + * @param callback A callback function to be invoked when an auth event happens. + */ + onAuthStateChange(callback) { + const id = uuid(); + const subscription = { + id, + callback, + unsubscribe: () => { + this._debug('#unsubscribe()', 'state change callback with id removed', id); + this.stateChangeEmitters.delete(id); + }, + }; + this._debug('#onAuthStateChange()', 'registered callback with id', id); + this.stateChangeEmitters.set(id, subscription); + this._emitInitialSession(id); + return { data: { subscription } }; + } + async _emitInitialSession(id) { + return await this._useSession(async (result) => { + var _a, _b; + try { + const { data: { session }, error, } = result; + if (error) + throw error; + await ((_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback('INITIAL_SESSION', session)); + this._debug('INITIAL_SESSION', 'callback id', id, 'session', session); + } + catch (err) { + await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback('INITIAL_SESSION', null)); + this._debug('INITIAL_SESSION', 'callback id', id, 'error', err); + console.error(err); + } + }); + } + /** + * Sends a password reset request to an email address. + * This method supports the PKCE flow. + * @param email The email address of the user. + * @param options.redirectTo The URL to send the user to after they click the password reset link. + * @param options.captchaToken Verification token received when the user completes the captcha on the site. + */ + async resetPasswordForEmail(email, options = {}) { + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + const codeVerifier = generatePKCEVerifier(); + await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier); + codeChallenge = await generatePKCEChallenge(codeVerifier); + codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'; + } + try { + return await _request(this.fetch, 'POST', `${this.url}/recover`, { + body: { + email, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + gotrue_meta_security: { captcha_token: options.captchaToken }, + }, + headers: this.headers, + redirectTo: options.redirectTo, + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Generates a new JWT. + * @param refreshToken A valid refresh token that was returned on login. + */ + async _refreshAccessToken(refreshToken) { + const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, 'begin'); + try { + const startedAt = Date.now(); + // will attempt to refresh the token with exponential backoff + return await retryable(async (attempt) => { + await sleep(attempt * 200); // 0, 200, 400, 800, ... + this._debug(debugName, 'refreshing attempt', attempt); + return await _request(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, { + body: { refresh_token: refreshToken }, + headers: this.headers, + xform: _sessionResponse, + }); + }, (attempt, _, result) => result && + result.error && + isAuthRetryableFetchError(result.error) && + // retryable only if the request can be sent before the backoff overflows the tick duration + Date.now() + (attempt + 1) * 200 - startedAt < AUTO_REFRESH_TICK_DURATION); + } + catch (error) { + this._debug(debugName, 'error', error); + if (isAuthError(error)) { + return { data: { session: null, user: null }, error }; + } + throw error; + } + finally { + this._debug(debugName, 'end'); + } + } + _isValidSession(maybeSession) { + const isValidSession = typeof maybeSession === 'object' && + maybeSession !== null && + 'access_token' in maybeSession && + 'refresh_token' in maybeSession && + 'expires_at' in maybeSession; + return isValidSession; + } + async _handleProviderSignIn(provider, options) { + const url = await this._getUrlForProvider(provider, { + redirectTo: options.redirectTo, + scopes: options.scopes, + queryParams: options.queryParams, + }); + this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url); + // try to open on the browser + if (isBrowser() && !options.skipBrowserRedirect) { + window.location.assign(url); + } + return { data: { provider, url }, error: null }; + } + /** + * Recovers the session from LocalStorage and refreshes + * Note: this method is async to accommodate for AsyncStorage e.g. in React native. + */ + async _recoverAndRefresh() { + var _a; + const debugName = '#_recoverAndRefresh()'; + this._debug(debugName, 'begin'); + try { + const currentSession = await getItemAsync(this.storage, this.storageKey); + this._debug(debugName, 'session from storage', currentSession); + if (!this._isValidSession(currentSession)) { + this._debug(debugName, 'session is not valid'); + if (currentSession !== null) { + await this._removeSession(); + } + return; + } + const timeNow = Math.round(Date.now() / 1000); + const expiresWithMargin = ((_a = currentSession.expires_at) !== null && _a !== void 0 ? _a : Infinity) < timeNow + EXPIRY_MARGIN; + this._debug(debugName, `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${EXPIRY_MARGIN}s`); + if (expiresWithMargin) { + if (this.autoRefreshToken && currentSession.refresh_token) { + const { error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + console.error(error); + if (!isAuthRetryableFetchError(error)) { + this._debug(debugName, 'refresh failed with a non-retryable error, removing the session', error); + await this._removeSession(); + } + } + } + } + else { + // no need to persist currentSession again, as we just loaded it from + // local storage; persisting it again may overwrite a value saved by + // another client with access to the same local storage + await this._notifyAllSubscribers('SIGNED_IN', currentSession); + } + } + catch (err) { + this._debug(debugName, 'error', err); + console.error(err); + return; + } + finally { + this._debug(debugName, 'end'); + } + } + async _callRefreshToken(refreshToken) { + var _a, _b; + if (!refreshToken) { + throw new AuthSessionMissingError(); + } + // refreshing is already in progress + if (this.refreshingDeferred) { + return this.refreshingDeferred.promise; + } + const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, 'begin'); + try { + this.refreshingDeferred = new Deferred(); + const { data, error } = await this._refreshAccessToken(refreshToken); + if (error) + throw error; + if (!data.session) + throw new AuthSessionMissingError(); + await this._saveSession(data.session); + await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session); + const result = { session: data.session, error: null }; + this.refreshingDeferred.resolve(result); + return result; + } + catch (error) { + this._debug(debugName, 'error', error); + if (isAuthError(error)) { + const result = { session: null, error }; + (_a = this.refreshingDeferred) === null || _a === void 0 ? void 0 : _a.resolve(result); + return result; + } + (_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error); + throw error; + } + finally { + this.refreshingDeferred = null; + this._debug(debugName, 'end'); + } + } + async _notifyAllSubscribers(event, session, broadcast = true) { + const debugName = `#_notifyAllSubscribers(${event})`; + this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`); + try { + if (this.broadcastChannel && broadcast) { + this.broadcastChannel.postMessage({ event, session }); + } + const errors = []; + const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => { + try { + await x.callback(event, session); + } + catch (e) { + errors.push(e); + } + }); + await Promise.all(promises); + if (errors.length > 0) { + for (let i = 0; i < errors.length; i += 1) { + console.error(errors[i]); + } + throw errors[0]; + } + } + finally { + this._debug(debugName, 'end'); + } + } + /** + * set currentSession and currentUser + * process to _startAutoRefreshToken if possible + */ + async _saveSession(session) { + this._debug('#_saveSession()', session); + if (!this.persistSession) { + this.inMemorySession = session; + } + if (this.persistSession && session.expires_at) { + await this._persistSession(session); + } + } + _persistSession(currentSession) { + this._debug('#_persistSession()', currentSession); + return setItemAsync(this.storage, this.storageKey, currentSession); + } + async _removeSession() { + this._debug('#_removeSession()'); + if (this.persistSession) { + await removeItemAsync(this.storage, this.storageKey); + } + else { + this.inMemorySession = null; + } + } + /** + * Removes any registered visibilitychange callback. + * + * {@see #startAutoRefresh} + * {@see #stopAutoRefresh} + */ + _removeVisibilityChangedCallback() { + this._debug('#_removeVisibilityChangedCallback()'); + const callback = this.visibilityChangedCallback; + this.visibilityChangedCallback = null; + try { + if (callback && isBrowser() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) { + window.removeEventListener('visibilitychange', callback); + } + } + catch (e) { + console.error('removing visibilitychange callback failed', e); + } + } + /** + * This is the private implementation of {@link #startAutoRefresh}. Use this + * within the library. + */ + async _startAutoRefresh() { + await this._stopAutoRefresh(); + this._debug('#_startAutoRefresh()'); + const ticker = setInterval(() => this._autoRefreshTokenTick(), AUTO_REFRESH_TICK_DURATION); + this.autoRefreshTicker = ticker; + if (ticker && typeof ticker === 'object' && typeof ticker.unref === 'function') { + // ticker is a NodeJS Timeout object that has an `unref` method + // https://nodejs.org/api/timers.html#timeoutunref + // When auto refresh is used in NodeJS (like for testing) the + // `setInterval` is preventing the process from being marked as + // finished and tests run endlessly. This can be prevented by calling + // `unref()` on the returned object. + ticker.unref(); + // @ts-ignore + } + else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') { + // similar like for NodeJS, but with the Deno API + // https://deno.land/api@latest?unstable&s=Deno.unrefTimer + // @ts-ignore + Deno.unrefTimer(ticker); + } + // run the tick immediately, but in the next pass of the event loop so that + // #_initialize can be allowed to complete without recursively waiting on + // itself + setTimeout(async () => { + await this.initializePromise; + await this._autoRefreshTokenTick(); + }, 0); + } + /** + * This is the private implementation of {@link #stopAutoRefresh}. Use this + * within the library. + */ + async _stopAutoRefresh() { + this._debug('#_stopAutoRefresh()'); + const ticker = this.autoRefreshTicker; + this.autoRefreshTicker = null; + if (ticker) { + clearInterval(ticker); + } + } + /** + * Starts an auto-refresh process in the background. The session is checked + * every few seconds. Close to the time of expiration a process is started to + * refresh the session. If refreshing fails it will be retried for as long as + * necessary. + * + * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need + * to call this function, it will be called for you. + * + * On browsers the refresh process works only when the tab/window is in the + * foreground to conserve resources as well as prevent race conditions and + * flooding auth with requests. If you call this method any managed + * visibility change callback will be removed and you must manage visibility + * changes on your own. + * + * On non-browser platforms the refresh process works *continuously* in the + * background, which may not be desirable. You should hook into your + * platform's foreground indication mechanism and call these methods + * appropriately to conserve resources. + * + * {@see #stopAutoRefresh} + */ + async startAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._startAutoRefresh(); + } + /** + * Stops an active auto refresh process running in the background (if any). + * + * If you call this method any managed visibility change callback will be + * removed and you must manage visibility changes on your own. + * + * See {@link #startAutoRefresh} for more details. + */ + async stopAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._stopAutoRefresh(); + } + /** + * Runs the auto refresh token tick. + */ + async _autoRefreshTokenTick() { + this._debug('#_autoRefreshTokenTick()', 'begin'); + try { + const now = Date.now(); + try { + return await this._useSession(async (result) => { + const { data: { session }, } = result; + if (!session || !session.refresh_token || !session.expires_at) { + this._debug('#_autoRefreshTokenTick()', 'no session'); + return; + } + // session will expire in this many ticks (or has already expired if <= 0) + const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / AUTO_REFRESH_TICK_DURATION); + this._debug('#_autoRefreshTokenTick()', `access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`); + if (expiresInTicks <= AUTO_REFRESH_TICK_THRESHOLD) { + await this._callRefreshToken(session.refresh_token); + } + }); + } + catch (e) { + console.error('Auto refresh tick failed with error. This is likely a transient error.', e); + } + } + finally { + this._debug('#_autoRefreshTokenTick()', 'end'); + } + } + /** + * Registers callbacks on the browser / platform, which in-turn run + * algorithms when the browser window/tab are in foreground. On non-browser + * platforms it assumes always foreground. + */ + async _handleVisibilityChange() { + this._debug('#_handleVisibilityChange()'); + if (!isBrowser() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) { + if (this.autoRefreshToken) { + // in non-browser environments the refresh token ticker runs always + this.startAutoRefresh(); + } + return false; + } + try { + this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false); + window === null || window === void 0 ? void 0 : window.addEventListener('visibilitychange', this.visibilityChangedCallback); + // now immediately call the visbility changed callback to setup with the + // current visbility state + await this._onVisibilityChanged(true); // initial call + } + catch (error) { + console.error('_handleVisibilityChange', error); + } + } + /** + * Callback registered with `window.addEventListener('visibilitychange')`. + */ + async _onVisibilityChanged(isInitial) { + this._debug(`#_onVisibilityChanged(${isInitial})`, 'visibilityState', document.visibilityState); + if (document.visibilityState === 'visible') { + // to avoid recursively depending on #_initialize(), run the visibility + // changed callback in the next event loop tick + setTimeout(async () => { + if (!isInitial) { + // initial visibility change setup is handled in another flow under #initialize() + await this.initializePromise; + await this._recoverAndRefresh(); + this._debug('#_onVisibilityChanged()', 'finished waiting for initialize, _recoverAndRefresh'); + } + if (this.autoRefreshToken) { + // in browser environments the refresh token ticker runs only on focused tabs + // which prevents race conditions + this._startAutoRefresh(); + } + }, 0); + } + else if (document.visibilityState === 'hidden') { + if (this.autoRefreshToken) { + this._stopAutoRefresh(); + } + } + } + /** + * Generates the relevant login URL for a third-party provider. + * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. + * @param options.scopes A space-separated list of scopes granted to the OAuth application. + * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. + */ + async _getUrlForProvider(provider, options) { + const urlParams = [`provider=${encodeURIComponent(provider)}`]; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`); + } + if (options === null || options === void 0 ? void 0 : options.scopes) { + urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`); + } + if (this.flowType === 'pkce') { + const codeVerifier = generatePKCEVerifier(); + await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier); + const codeChallenge = await generatePKCEChallenge(codeVerifier); + const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'; + this._debug('PKCE', 'code verifier', `${codeVerifier.substring(0, 5)}...`, 'code challenge', codeChallenge, 'method', codeChallengeMethod); + const flowParams = new URLSearchParams({ + code_challenge: `${encodeURIComponent(codeChallenge)}`, + code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`, + }); + urlParams.push(flowParams.toString()); + } + if (options === null || options === void 0 ? void 0 : options.queryParams) { + const query = new URLSearchParams(options.queryParams); + urlParams.push(query.toString()); + } + return `${this.url}/authorize?${urlParams.join('&')}`; + } + async _unenroll(params) { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return { data: null, error: sessionError }; + } + return await _request(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, { + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * {@see GoTrueMFAApi#enroll} + */ + async _enroll(params) { + try { + return await this._useSession(async (result) => { + var _a, _b; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return { data: null, error: sessionError }; + } + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors`, { + body: { + friendly_name: params.friendlyName, + factor_type: params.factorType, + issuer: params.issuer, + }, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + if (error) { + return { data: null, error }; + } + if ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code) { + data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`; + } + return { data, error: null }; + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * {@see GoTrueMFAApi#verify} + */ + async _verify(params) { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return { data: null, error: sessionError }; + } + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/verify`, { + body: { code: params.code, challenge_id: params.challengeId }, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + if (error) { + return { data: null, error }; + } + await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1000) + data.expires_in }, data)); + await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data); + return { data, error }; + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * {@see GoTrueMFAApi#challenge} + */ + async _challenge(params) { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return { data: null, error: sessionError }; + } + return await _request(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/challenge`, { + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + }); + } + catch (error) { + if (isAuthError(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * {@see GoTrueMFAApi#challengeAndVerify} + */ + async _challengeAndVerify(params) { + const { data: challengeData, error: challengeError } = await this._challenge({ + factorId: params.factorId, + }); + if (challengeError) { + return { data: null, error: challengeError }; + } + return await this._verify({ + factorId: params.factorId, + challengeId: challengeData.id, + code: params.code, + }); + } + /** + * {@see GoTrueMFAApi#listFactors} + */ + async _listFactors() { + const { data: { user }, error: userError, } = await this.getUser(); + if (userError) { + return { data: null, error: userError }; + } + const factors = (user === null || user === void 0 ? void 0 : user.factors) || []; + const totp = factors.filter((factor) => factor.factor_type === 'totp' && factor.status === 'verified'); + return { + data: { + all: factors, + totp, + }, + error: null, + }; + } + /** + * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} + */ + async _getAuthenticatorAssuranceLevel() { + return await this._useSession(async (result) => { + var _a, _b; + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return { data: null, error: sessionError }; + } + if (!session) { + return { + data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] }, + error: null, + }; + } + const payload = this._decodeJWT(session.access_token); + let currentLevel = null; + if (payload.aal) { + currentLevel = payload.aal; + } + let nextLevel = currentLevel; + const verifiedFactors = (_b = (_a = session.user.factors) === null || _a === void 0 ? void 0 : _a.filter((factor) => factor.status === 'verified')) !== null && _b !== void 0 ? _b : []; + if (verifiedFactors.length > 0) { + nextLevel = 'aal2'; + } + const currentAuthenticationMethods = payload.amr || []; + return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null }; + }); + } +} +GoTrueClient.nextInstanceID = 0; +//# sourceMappingURL=GoTrueClient.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js.map b/node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js.map new file mode 100644 index 0000000..502e1d8 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GoTrueClient.js","sourceRoot":"","sources":["../../src/GoTrueClient.ts"],"names":[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B,KAAK,EAAE,YAAY,GACpB,GAAG,MAAM,CAAA;YACV,IAAI,YAAY,EAAE;gBAChB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,YAAY,EAAE,CAAA;aAC3C;YACD,IAAI,CAAC,OAAO,EAAE;gBACZ,OAAO;oBACL,IAAI,EAAE,EAAE,YAAY,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,4BAA4B,EAAE,EAAE,EAAE;oBAC/E,KAAK,EAAE,IAAI;iBACZ,CAAA;aACF;YAED,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,YAAY,CAAC,CAAA;YAErD,IAAI,YAAY,GAAwC,IAAI,CAAA;YAE5D,IAAI,OAAO,CAAC,GAAG,EAAE;gBACf,YAAY,GAAG,OAAO,CAAC,GAAG,CAAA;aAC3B;YAED,IAAI,SAAS,GAAwC,YAAY,CAAA;YAEjE,MAAM,eAAe,GACnB,MAAA,MAAA,OAAO,CAAC,IAAI,CAAC,OAAO,0CAAE,MAAM,CAAC,CAAC,MAAc,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,KAAK,UAAU,CAAC,mCAAI,EAAE,CAAA;YAEtF,IAAI,eAAe,CAAC,MAAM,GAAG,CAAC,EAAE;gBAC9B,SAAS,GAAG,MAAM,CAAA;aACnB;YAED,MAAM,4BAA4B,GAAG,OAAO,CAAC,GAAG,IAAI,EAAE,CAAA;YAEtD,OAAO,EAAE,IAAI,EAAE,EAAE,YAAY,EAAE,SAAS,EAAE,4BAA4B,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;QACzF,CAAC,CAAC,CAAA;IACJ,CAAC;;AAtgEc,2BAAc,GAAG,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/index.d.ts b/node_modules/@supabase/gotrue-js/dist/module/index.d.ts new file mode 100644 index 0000000..55c6880 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/index.d.ts @@ -0,0 +1,7 @@ +import GoTrueAdminApi from './GoTrueAdminApi'; +import GoTrueClient from './GoTrueClient'; +export { GoTrueAdminApi, GoTrueClient }; +export * from './lib/types'; +export * from './lib/errors'; +export { navigatorLock, NavigatorLockAcquireTimeoutError, internals as lockInternals, } from './lib/locks'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/index.d.ts.map b/node_modules/@supabase/gotrue-js/dist/module/index.d.ts.map new file mode 100644 index 0000000..86d54e5 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAC7C,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,CAAA;AACvC,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,OAAO,EACL,aAAa,EACb,gCAAgC,EAChC,SAAS,IAAI,aAAa,GAC3B,MAAM,aAAa,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/index.js b/node_modules/@supabase/gotrue-js/dist/module/index.js new file mode 100644 index 0000000..62322cd --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/index.js @@ -0,0 +1,7 @@ +import GoTrueAdminApi from './GoTrueAdminApi'; +import GoTrueClient from './GoTrueClient'; +export { GoTrueAdminApi, GoTrueClient }; +export * from './lib/types'; +export * from './lib/errors'; +export { navigatorLock, NavigatorLockAcquireTimeoutError, internals as lockInternals, } from './lib/locks'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/index.js.map b/node_modules/@supabase/gotrue-js/dist/module/index.js.map new file mode 100644 index 0000000..90cb36a --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAC7C,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,CAAA;AACvC,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,OAAO,EACL,aAAa,EACb,gCAAgC,EAChC,SAAS,IAAI,aAAa,GAC3B,MAAM,aAAa,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/constants.d.ts b/node_modules/@supabase/gotrue-js/dist/module/lib/constants.d.ts new file mode 100644 index 0000000..234e0cb --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/constants.d.ts @@ -0,0 +1,12 @@ +export declare const GOTRUE_URL = "http://localhost:9999"; +export declare const STORAGE_KEY = "supabase.auth.token"; +export declare const AUDIENCE = ""; +export declare const DEFAULT_HEADERS: { + 'X-Client-Info': string; +}; +export declare const EXPIRY_MARGIN = 10; +export declare const NETWORK_FAILURE: { + MAX_RETRIES: number; + RETRY_INTERVAL: number; +}; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/constants.d.ts.map b/node_modules/@supabase/gotrue-js/dist/module/lib/constants.d.ts.map new file mode 100644 index 0000000..8d3efbe --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,UAAU,0BAA0B,CAAA;AACjD,eAAO,MAAM,WAAW,wBAAwB,CAAA;AAChD,eAAO,MAAM,QAAQ,KAAK,CAAA;AAC1B,eAAO,MAAM,eAAe;;CAA8C,CAAA;AAC1E,eAAO,MAAM,aAAa,KAAK,CAAA;AAC/B,eAAO,MAAM,eAAe;;;CAG3B,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/constants.js b/node_modules/@supabase/gotrue-js/dist/module/lib/constants.js new file mode 100644 index 0000000..fedd879 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/constants.js @@ -0,0 +1,11 @@ +import { version } from './version'; +export const GOTRUE_URL = 'http://localhost:9999'; +export const STORAGE_KEY = 'supabase.auth.token'; +export const AUDIENCE = ''; +export const DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version}` }; +export const EXPIRY_MARGIN = 10; // in seconds +export const NETWORK_FAILURE = { + MAX_RETRIES: 10, + RETRY_INTERVAL: 2, // in deciseconds +}; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/constants.js.map b/node_modules/@supabase/gotrue-js/dist/module/lib/constants.js.map new file mode 100644 index 0000000..e3093d1 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACnC,MAAM,CAAC,MAAM,UAAU,GAAG,uBAAuB,CAAA;AACjD,MAAM,CAAC,MAAM,WAAW,GAAG,qBAAqB,CAAA;AAChD,MAAM,CAAC,MAAM,QAAQ,GAAG,EAAE,CAAA;AAC1B,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,eAAe,EAAE,aAAa,OAAO,EAAE,EAAE,CAAA;AAC1E,MAAM,CAAC,MAAM,aAAa,GAAG,EAAE,CAAA,CAAC,aAAa;AAC7C,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,WAAW,EAAE,EAAE;IACf,cAAc,EAAE,CAAC,EAAE,iBAAiB;CACrC,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/errors.d.ts b/node_modules/@supabase/gotrue-js/dist/module/lib/errors.d.ts new file mode 100644 index 0000000..f2fcedd --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/errors.d.ts @@ -0,0 +1,82 @@ +export declare class AuthError extends Error { + status: number | undefined; + protected __isAuthError: boolean; + constructor(message: string, status?: number); +} +export declare function isAuthError(error: unknown): error is AuthError; +export declare class AuthApiError extends AuthError { + status: number; + constructor(message: string, status: number); + toJSON(): { + name: string; + message: string; + status: number; + }; +} +export declare function isAuthApiError(error: unknown): error is AuthApiError; +export declare class AuthUnknownError extends AuthError { + originalError: unknown; + constructor(message: string, originalError: unknown); +} +export declare class CustomAuthError extends AuthError { + name: string; + status: number; + constructor(message: string, name: string, status: number); + toJSON(): { + name: string; + message: string; + status: number; + }; +} +export declare class AuthSessionMissingError extends CustomAuthError { + constructor(); +} +export declare class AuthInvalidTokenResponseError extends CustomAuthError { + constructor(); +} +export declare class AuthInvalidCredentialsError extends CustomAuthError { + constructor(message: string); +} +export declare class AuthImplicitGrantRedirectError extends CustomAuthError { + details: { + error: string; + code: string; + } | null; + constructor(message: string, details?: { + error: string; + code: string; + } | null); + toJSON(): { + name: string; + message: string; + status: number; + details: { + error: string; + code: string; + } | null; + }; +} +export declare class AuthPKCEGrantCodeExchangeError extends CustomAuthError { + details: { + error: string; + code: string; + } | null; + constructor(message: string, details?: { + error: string; + code: string; + } | null); + toJSON(): { + name: string; + message: string; + status: number; + details: { + error: string; + code: string; + } | null; + }; +} +export declare class AuthRetryableFetchError extends CustomAuthError { + constructor(message: string, status: number); +} +export declare function isAuthRetryableFetchError(error: unknown): error is AuthRetryableFetchError; +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/errors.d.ts.map b/node_modules/@supabase/gotrue-js/dist/module/lib/errors.d.ts.map new file mode 100644 index 0000000..5fa1a60 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/errors.d.ts.map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AM,CAAA;KAAE,GAAG,IAAW;IAKnF,MAAM;;;;;;;;;CAQP;AAED,qBAAa,8BAA+B,SAAQ,eAAe;IACjE,OAAO,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAO;gBAC1C,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,IAAW;IAKnF,MAAM;;;;;;;;;CAQP;AAED,qBAAa,uBAAwB,SAAQ,eAAe;gBAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CAG5C;AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,uBAAuB,CAE1F"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/errors.js b/node_modules/@supabase/gotrue-js/dist/module/lib/errors.js new file mode 100644 index 0000000..1f135a4 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/errors.js @@ -0,0 +1,103 @@ +export class AuthError extends Error { + constructor(message, status) { + super(message); + this.__isAuthError = true; + this.name = 'AuthError'; + this.status = status; + } +} +export function isAuthError(error) { + return typeof error === 'object' && error !== null && '__isAuthError' in error; +} +export class AuthApiError extends AuthError { + constructor(message, status) { + super(message, status); + this.name = 'AuthApiError'; + this.status = status; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + }; + } +} +export function isAuthApiError(error) { + return isAuthError(error) && error.name === 'AuthApiError'; +} +export class AuthUnknownError extends AuthError { + constructor(message, originalError) { + super(message); + this.name = 'AuthUnknownError'; + this.originalError = originalError; + } +} +export class CustomAuthError extends AuthError { + constructor(message, name, status) { + super(message); + this.name = name; + this.status = status; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + }; + } +} +export class AuthSessionMissingError extends CustomAuthError { + constructor() { + super('Auth session missing!', 'AuthSessionMissingError', 400); + } +} +export class AuthInvalidTokenResponseError extends CustomAuthError { + constructor() { + super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500); + } +} +export class AuthInvalidCredentialsError extends CustomAuthError { + constructor(message) { + super(message, 'AuthInvalidCredentialsError', 400); + } +} +export class AuthImplicitGrantRedirectError extends CustomAuthError { + constructor(message, details = null) { + super(message, 'AuthImplicitGrantRedirectError', 500); + this.details = null; + this.details = details; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + }; + } +} +export class AuthPKCEGrantCodeExchangeError extends CustomAuthError { + constructor(message, details = null) { + super(message, 'AuthPKCEGrantCodeExchangeError', 500); + this.details = null; + this.details = details; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + }; + } +} +export class AuthRetryableFetchError extends CustomAuthError { + constructor(message, status) { + super(message, 'AuthRetryableFetchError', status); + } +} +export function isAuthRetryableFetchError(error) { + return isAuthError(error) && error.name === 'AuthRetryableFetchError'; +} +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/errors.js.map b/node_modules/@supabase/gotrue-js/dist/module/lib/errors.js.map new file mode 100644 index 0000000..aaf713e --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,SAAU,SAAQ,KAAK;IAIlC,YAAY,OAAe,EAAE,MAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAA;QAHN,kBAAa,GAAG,IAAI,CAAA;QAI5B,IAAI,CAAC,IAAI,GAAG,WAAW,CAAA;QACvB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;CACF;AAED,MAAM,UAAU,WAAW,CAAC,KAAc;IACxC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAA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CAAC,CAAA;IACnD,CAAC;CACF;AAED,MAAM,UAAU,yBAAyB,CAAC,KAAc;IACtD,OAAO,WAAW,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,yBAAyB,CAAA;AACvE,CAAC"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/fetch.d.ts b/node_modules/@supabase/gotrue-js/dist/module/lib/fetch.d.ts new file mode 100644 index 0000000..40d47c5 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/fetch.d.ts @@ -0,0 +1,32 @@ +import { AuthResponse, SSOResponse, GenerateLinkResponse, UserResponse } from './types'; +export declare type Fetch = typeof fetch; +export interface FetchOptions { + headers?: { + [key: string]: string; + }; + noResolveJson?: boolean; +} +export interface FetchParameters { + signal?: AbortSignal; +} +export declare type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'DELETE'; +interface GotrueRequestOptions extends FetchOptions { + jwt?: string; + redirectTo?: string; + body?: object; + query?: { + [key: string]: string; + }; + /** + * Function that transforms api response from gotrue into a desirable / standardised format + */ + xform?: (data: any) => any; +} +export declare function _request(fetcher: Fetch, method: RequestMethodType, url: string, options?: GotrueRequestOptions): Promise; +export declare function _sessionResponse(data: any): AuthResponse; +export declare function _userResponse(data: any): UserResponse; +export declare function _ssoResponse(data: any): SSOResponse; +export declare function _generateLinkResponse(data: any): GenerateLinkResponse; +export declare function _noResolveJsonResponse(data: any): Response; +export {}; +//# sourceMappingURL=fetch.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/fetch.d.ts.map b/node_modules/@supabase/gotrue-js/dist/module/lib/fetch.d.ts.map new file mode 100644 index 0000000..a884f38 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/fetch.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AACA,OAAO,EACL,YAAY,EACZ,WAA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abase/gotrue-js/dist/module/lib/fetch.js new file mode 100644 index 0000000..3963463 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/fetch.js @@ -0,0 +1,127 @@ +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +import { expiresAt, looksLikeFetchResponse } from './helpers'; +import { AuthApiError, AuthRetryableFetchError, AuthUnknownError } from './errors'; +const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); +const NETWORK_ERROR_CODES = [502, 503, 504]; +async function handleError(error) { + if (!looksLikeFetchResponse(error)) { + throw new AuthRetryableFetchError(_getErrorMessage(error), 0); + } + if (NETWORK_ERROR_CODES.includes(error.status)) { + // status in 500...599 range - server had an error, request might be retryed. + throw new AuthRetryableFetchError(_getErrorMessage(error), error.status); + } + let data; + try { + data = await error.json(); + } + catch (e) { + throw new AuthUnknownError(_getErrorMessage(e), e); + } + throw new AuthApiError(_getErrorMessage(data), error.status || 500); +} +const _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === 'GET') { + return params; + } + params.headers = Object.assign({ 'Content-Type': 'application/json;charset=UTF-8' }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + return Object.assign(Object.assign({}, params), parameters); +}; +export async function _request(fetcher, method, url, options) { + var _a; + const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers); + if (options === null || options === void 0 ? void 0 : options.jwt) { + headers['Authorization'] = `Bearer ${options.jwt}`; + } + const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {}; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + qs['redirect_to'] = options.redirectTo; + } + const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : ''; + const data = await _handleRequest(fetcher, method, url + queryString, { headers, noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson }, {}, options === null || options === void 0 ? void 0 : options.body); + return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null }; +} +async function _handleRequest(fetcher, method, url, options, parameters, body) { + const requestParams = _getRequestParams(method, options, parameters, body); + let result; + try { + result = await fetcher(url, requestParams); + } + catch (e) { + console.error(e); + // fetch failed, likely due to a network or CORS error + throw new AuthRetryableFetchError(_getErrorMessage(e), 0); + } + if (!result.ok) { + await handleError(result); + } + if (options === null || options === void 0 ? void 0 : options.noResolveJson) { + return result; + } + try { + return await result.json(); + } + catch (e) { + await handleError(e); + } +} +export function _sessionResponse(data) { + var _a; + let session = null; + if (hasSession(data)) { + session = Object.assign({}, data); + session.expires_at = expiresAt(data.expires_in); + } + const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; + return { data: { session, user }, error: null }; +} +export function _userResponse(data) { + var _a; + const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; + return { data: { user }, error: null }; +} +export function _ssoResponse(data) { + return { data, error: null }; +} +export function _generateLinkResponse(data) { + const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = __rest(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]); + const properties = { + action_link, + email_otp, + hashed_token, + redirect_to, + verification_type, + }; + const user = Object.assign({}, rest); + return { + data: { + properties, + user, + }, + error: null, + }; +} +export function _noResolveJsonResponse(data) { + return data; +} +/** + * hasSession checks if the response object contains a valid session + * @param data A response object + * @returns true if a session is in the response + */ +function hasSession(data) { + return data.access_token && data.refresh_token && data.expires_in; +} +//# sourceMappingURL=fetch.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/fetch.js.map b/node_modules/@supabase/gotrue-js/dist/module/lib/fetch.js.map new file mode 100644 index 0000000..b3e02d1 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/fetch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,MAAM,WAAW,CAAA;AAS7D,OAAO,EAAE,YAAY,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;AAiBlF,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAU,EAAE,CAC5C,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,OAAO,IAAI,GAAG,CAAC,iBAAiB,IAAI,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAA;AAErF,MAAM,mBAAmB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;AAE3C,KAAK,UAAU,WAAW,CAAC,KAAc;IACvC,IAAI,CAAC,sBAAsB,CAAC,KAAK,CAAC,EAAE;QAClC,MAAM,IAAI,uBAAuB,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAA;KAC9D;IAED,IAAI,mBAAmB,CAAC,QAAQ,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE;QAC9C,6EAA6E;QAC7E,MAAM,IAAI,uBAAuB,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,CAAA;KACzE;IAED,IAAI,IAAS,CAAA;IACb,IAAI;QACF,IAAI,GAAG,MAAM,KAAK,CAAC,IAAI,EAAE,CAAA;KAC1B;IAAC,OAAO,CAAM,EAAE;QACf,MAAM,IAAI,gBAAgB,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;KACnD;IA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J,UAAU;YACV,IAAI;SACL;QACD,KAAK,EAAE,IAAI;KACZ,CAAA;AACH,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,IAAS;IAC9C,OAAO,IAAI,CAAA;AACb,CAAC;AAED;;;;GAIG;AACH,SAAS,UAAU,CAAC,IAAS;IAC3B,OAAO,IAAI,CAAC,YAAY,IAAI,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,UAAU,CAAA;AACnE,CAAC"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/helpers.d.ts b/node_modules/@supabase/gotrue-js/dist/module/lib/helpers.d.ts new file mode 100644 index 0000000..bf793c5 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/helpers.d.ts @@ -0,0 +1,77 @@ +import { SupportedStorage } from './types'; +export declare function expiresAt(expiresIn: number): number; +export declare function uuid(): string; +export declare const isBrowser: () => boolean; +/** + * Checks whether localStorage is supported on this browser. + */ +export declare const supportsLocalStorage: () => boolean; +/** + * Extracts parameters encoded in the URL both in the query and fragment. + */ +export declare function parseParametersFromURL(href: string): { + [parameter: string]: string; +}; +declare type Fetch = typeof fetch; +export declare const resolveFetch: (customFetch?: Fetch) => Fetch; +export declare const looksLikeFetchResponse: (maybeResponse: unknown) => maybeResponse is Response; +export declare const setItemAsync: (storage: SupportedStorage, key: string, data: any) => Promise; +export declare const getItemAsync: (storage: SupportedStorage, key: string) => Promise; +export declare const removeItemAsync: (storage: SupportedStorage, key: string) => Promise; +export declare function decodeBase64URL(value: string): string; +/** + * A deferred represents some asynchronous work that is not yet finished, which + * may or may not culminate in a value. + * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts + */ +export declare class Deferred { + static promiseConstructor: PromiseConstructor; + readonly promise: PromiseLike; + readonly resolve: (value?: T | PromiseLike) => void; + readonly reject: (reason?: any) => any; + constructor(); +} +export declare function decodeJWTPayload(token: string): any; +/** + * Creates a promise that resolves to null after some time. + */ +export declare function sleep(time: number): Promise; +/** + * Converts the provided async function into a retryable function. Each result + * or thrown error is sent to the isRetryable function which should return true + * if the function should run again. + */ +export declare function retryable(fn: (attempt: number) => Promise, isRetryable: (attempt: number, error: any | null, result?: T) => boolean): Promise; +export declare function generatePKCEVerifier(): string; +export declare function generatePKCEChallenge(verifier: string): Promise; +/** + * Checks if the current caller of the function is in a {@link + * #stackGuard} of the provided `name`. Works by looking through + * the stack trace of an `Error` object for a special function + * name (generated by {@link #stackGuard}). + * + * @param name The name of the stack guard to check for. Must be `[a-zA-Z0-9_-]` only. + */ +export declare function isInStackGuard(name: string): boolean; +/** + * Creates a minification resistant stack guard, i.e. if you + * call {@link #isInStackGuard} from within the `fn` parameter + * function, you will always get `true` otherwise it will be + * `false`. + * + * Works by dynamically defining a function name before calling + * into `fn`, which is then parsed from the stack trace on an + * `Error` object within {@link #isInStackGuard}. + * + * @param name The name of the stack guard. Must be `[a-zA-Z0-9_-]` only. + * @param fn The async/await function to be run within the stack guard. + */ +export declare function stackGuard(name: string, fn: () => Promise): Promise; +/** + * Returns if the JavaScript engine supports stack guards. If it doesn't + * certain features that depend on detecting recursive calls should be disabled + * to prevent deadlocks. + */ +export declare function stackGuardsSupported(): Promise; +export {}; +//# sourceMappingURL=helpers.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/helpers.d.ts.map b/node_modules/@supabase/gotrue-js/dist/module/lib/helpers.d.ts.map new file mode 100644 index 0000000..be8393d --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAC1C,wBAAgB,SAAS,CAAC,SAAS,EAAE,MAAM,UAG1C;AAED,wBAAgB,IAAI,WAMnB;AAED,eAAO,MAAM,SAAS,eAAwC,CAAA;AAO9D;;GAEG;AACH,eAAO,MAA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E,GAAG,GAAG,IAAI,EAAE,MAAM,CAAC,EAAE,CAAC,KAAK,OAAO,GACvE,OAAO,CAAC,CAAC,CAAC,CAuBZ;AAOD,wBAAgB,oBAAoB,WAcnC;AAiBD,wBAAsB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,mBAS3D;AA8BD;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAuBpD;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,UAAU,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAoBlF;AAED;;;;GAIG;AACH,wBAAsB,oBAAoB,IAAI,OAAO,CAAC,OAAO,CAAC,CAQ7D"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/helpers.js b/node_modules/@supabase/gotrue-js/dist/module/lib/helpers.js new file mode 100644 index 0000000..4e30c01 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/helpers.js @@ -0,0 +1,359 @@ +export function expiresAt(expiresIn) { + const timeNow = Math.round(Date.now() / 1000); + return timeNow + expiresIn; +} +export function uuid() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +} +export const isBrowser = () => typeof document !== 'undefined'; +const localStorageWriteTests = { + tested: false, + writable: false, +}; +/** + * Checks whether localStorage is supported on this browser. + */ +export const supportsLocalStorage = () => { + if (!isBrowser()) { + return false; + } + try { + if (typeof globalThis.localStorage !== 'object') { + return false; + } + } + catch (e) { + // DOM exception when accessing `localStorage` + return false; + } + if (localStorageWriteTests.tested) { + return localStorageWriteTests.writable; + } + const randomKey = `lswt-${Math.random()}${Math.random()}`; + try { + globalThis.localStorage.setItem(randomKey, randomKey); + globalThis.localStorage.removeItem(randomKey); + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = true; + } + catch (e) { + // localStorage can't be written to + // https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = false; + } + return localStorageWriteTests.writable; +}; +/** + * Extracts parameters encoded in the URL both in the query and fragment. + */ +export function parseParametersFromURL(href) { + const result = {}; + const url = new URL(href); + if (url.hash && url.hash[0] === '#') { + try { + const hashSearchParams = new URLSearchParams(url.hash.substring(1)); + hashSearchParams.forEach((value, key) => { + result[key] = value; + }); + } + catch (e) { + // hash is not a query string + } + } + // search parameters take precedence over hash parameters + url.searchParams.forEach((value, key) => { + result[key] = value; + }); + return result; +} +export const resolveFetch = (customFetch) => { + let _fetch; + if (customFetch) { + _fetch = customFetch; + } + else if (typeof fetch === 'undefined') { + _fetch = async (...args) => await (await import('cross-fetch')).fetch(...args); + } + else { + _fetch = fetch; + } + return (...args) => _fetch(...args); +}; +export const looksLikeFetchResponse = (maybeResponse) => { + return (typeof maybeResponse === 'object' && + maybeResponse !== null && + 'status' in maybeResponse && + 'ok' in maybeResponse && + 'json' in maybeResponse && + typeof maybeResponse.json === 'function'); +}; +// Storage helpers +export const setItemAsync = async (storage, key, data) => { + await storage.setItem(key, JSON.stringify(data)); +}; +export const getItemAsync = async (storage, key) => { + const value = await storage.getItem(key); + if (!value) { + return null; + } + try { + return JSON.parse(value); + } + catch (_a) { + return value; + } +}; +export const removeItemAsync = async (storage, key) => { + await storage.removeItem(key); +}; +export function decodeBase64URL(value) { + const key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + let base64 = ''; + let chr1, chr2, chr3; + let enc1, enc2, enc3, enc4; + let i = 0; + value = value.replace('-', '+').replace('_', '/'); + while (i < value.length) { + enc1 = key.indexOf(value.charAt(i++)); + enc2 = key.indexOf(value.charAt(i++)); + enc3 = key.indexOf(value.charAt(i++)); + enc4 = key.indexOf(value.charAt(i++)); + chr1 = (enc1 << 2) | (enc2 >> 4); + chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); + chr3 = ((enc3 & 3) << 6) | enc4; + base64 = base64 + String.fromCharCode(chr1); + if (enc3 != 64 && chr2 != 0) { + base64 = base64 + String.fromCharCode(chr2); + } + if (enc4 != 64 && chr3 != 0) { + base64 = base64 + String.fromCharCode(chr3); + } + } + return base64; +} +/** + * A deferred represents some asynchronous work that is not yet finished, which + * may or may not culminate in a value. + * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts + */ +export class Deferred { + constructor() { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + this.promise = new Deferred.promiseConstructor((res, rej) => { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + this.resolve = res; + this.reject = rej; + }); + } +} +Deferred.promiseConstructor = Promise; +// Taken from: https://stackoverflow.com/questions/38552003/how-to-decode-jwt-token-in-javascript-without-using-a-library +export function decodeJWTPayload(token) { + // Regex checks for base64url format + const base64UrlRegex = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i; + const parts = token.split('.'); + if (parts.length !== 3) { + throw new Error('JWT is not valid: not a JWT structure'); + } + if (!base64UrlRegex.test(parts[1])) { + throw new Error('JWT is not valid: payload is not in base64url format'); + } + const base64Url = parts[1]; + return JSON.parse(decodeBase64URL(base64Url)); +} +/** + * Creates a promise that resolves to null after some time. + */ +export async function sleep(time) { + return await new Promise((accept) => { + setTimeout(() => accept(null), time); + }); +} +/** + * Converts the provided async function into a retryable function. Each result + * or thrown error is sent to the isRetryable function which should return true + * if the function should run again. + */ +export function retryable(fn, isRetryable) { + const promise = new Promise((accept, reject) => { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + (async () => { + for (let attempt = 0; attempt < Infinity; attempt++) { + try { + const result = await fn(attempt); + if (!isRetryable(attempt, null, result)) { + accept(result); + return; + } + } + catch (e) { + if (!isRetryable(attempt, e)) { + reject(e); + return; + } + } + } + })(); + }); + return promise; +} +function dec2hex(dec) { + return ('0' + dec.toString(16)).substr(-2); +} +// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs +export function generatePKCEVerifier() { + const verifierLength = 56; + const array = new Uint32Array(verifierLength); + if (typeof crypto === 'undefined') { + const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'; + const charSetLen = charSet.length; + let verifier = ''; + for (let i = 0; i < verifierLength; i++) { + verifier += charSet.charAt(Math.floor(Math.random() * charSetLen)); + } + return verifier; + } + crypto.getRandomValues(array); + return Array.from(array, dec2hex).join(''); +} +async function sha256(randomString) { + const encoder = new TextEncoder(); + const encodedData = encoder.encode(randomString); + const hash = await crypto.subtle.digest('SHA-256', encodedData); + const bytes = new Uint8Array(hash); + return Array.from(bytes) + .map((c) => String.fromCharCode(c)) + .join(''); +} +function base64urlencode(str) { + return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} +export async function generatePKCEChallenge(verifier) { + if (typeof crypto === 'undefined') { + console.warn('WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.'); + return verifier; + } + const hashed = await sha256(verifier); + return base64urlencode(hashed); +} +const STACK_GUARD_PREFIX = `__stack_guard__`; +const STACK_GUARD_SUFFIX = `__`; +// Firefox and WebKit based browsers encode the stack entry differently, but +// they all include the function name. So instead of trying to parse the entry, +// we're only looking for the special string `__stack_guard__${guardName}__`. +// Guard names can only be letters with dashes or underscores. +// +// Example Firefox stack trace: +// ``` +// __stack_guard__EXAMPLE__@debugger eval code:1:55 +// @debugger eval code:1:3 +// ``` +// +// Example WebKit/Chrome stack trace: +// ``` +// Error +// at Object.__stack_guard__EXAMPLE__ (:1:55) +// at :1:13 +// ``` +// +const STACK_ENTRY_REGEX = /__stack_guard__([a-zA-Z0-9_-]+)__/; +let STACK_GUARD_CHECKED = false; +let STACK_GUARD_CHECK_FN; // eslint-disable-line prefer-const +let STACK_GUARDS_SUPPORTED = false; +/** + * Checks if the current caller of the function is in a {@link + * #stackGuard} of the provided `name`. Works by looking through + * the stack trace of an `Error` object for a special function + * name (generated by {@link #stackGuard}). + * + * @param name The name of the stack guard to check for. Must be `[a-zA-Z0-9_-]` only. + */ +export function isInStackGuard(name) { + var _a, _b; + STACK_GUARD_CHECK_FN(); + let error; + try { + throw new Error(); + } + catch (e) { + error = e; + } + const stack = (_b = (_a = error.stack) === null || _a === void 0 ? void 0 : _a.split('\n')) !== null && _b !== void 0 ? _b : []; + for (let i = 0; i < stack.length; i += 1) { + const entry = stack[i]; + const match = entry.match(STACK_ENTRY_REGEX); + if (match && match[1] === name) { + return true; + } + } + return false; +} +/** + * Creates a minification resistant stack guard, i.e. if you + * call {@link #isInStackGuard} from within the `fn` parameter + * function, you will always get `true` otherwise it will be + * `false`. + * + * Works by dynamically defining a function name before calling + * into `fn`, which is then parsed from the stack trace on an + * `Error` object within {@link #isInStackGuard}. + * + * @param name The name of the stack guard. Must be `[a-zA-Z0-9_-]` only. + * @param fn The async/await function to be run within the stack guard. + */ +export async function stackGuard(name, fn) { + await STACK_GUARD_CHECK_FN(); + const guardName = `${STACK_GUARD_PREFIX}${name}${STACK_GUARD_SUFFIX}`; + const guardFunc = { + // per ECMAScript rules, this defines a new function with the dynamic name + // contained in the `guardName` variable + // this function name shows up in stack traces and is resistant to mangling + // from minification processes as it is determined at runtime + [guardName]: async () => await fn(), + }; + // Safari does not log the name of a dynamically named function unless you + // explicitly set the displayName + Object.assign(guardFunc[guardName], { displayName: guardName }); + return await guardFunc[guardName](); +} +/** + * Returns if the JavaScript engine supports stack guards. If it doesn't + * certain features that depend on detecting recursive calls should be disabled + * to prevent deadlocks. + */ +export async function stackGuardsSupported() { + if (STACK_GUARD_CHECKED) { + return STACK_GUARDS_SUPPORTED; + } + await STACK_GUARD_CHECK_FN(); + return STACK_GUARDS_SUPPORTED; +} +let STACK_GUARD_WARNING_LOGGED = false; +// In certain cases, if this file is transpiled using an ES2015 target, or is +// running in a JS engine that does not support async/await stack traces, this +// function will log a single warning message. +STACK_GUARD_CHECK_FN = async () => { + if (!STACK_GUARD_CHECKED) { + STACK_GUARD_CHECKED = true; + await stackGuard('ENV_CHECK', async () => { + // sleeping for the next tick as Safari loses track of the async/await + // trace beyond this point + await sleep(0); + const result = isInStackGuard('ENV_CHECK'); + STACK_GUARDS_SUPPORTED = result; + if (!result && !STACK_GUARD_WARNING_LOGGED) { + STACK_GUARD_WARNING_LOGGED = true; + console.warn('@supabase/gotrue-js: Stack guards not supported in this environment. Generally not an issue but may point to a very conservative transpilation environment (use ES2017 or above) that implements async/await with generators, or this is a JavaScript engine that does not support async/await stack traces. Safari is known to not support stack guards.'); + } + return result; + }); + } +}; +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/helpers.js.map b/node_modules/@supabase/gotrue-js/dist/module/lib/helpers.js.map new file mode 100644 index 0000000..9bb987a --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AACA,MAAM,UAAU,SAAS,CAAC,SAAiB;IACzC,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAA;IAC7C,OAAO,OAAO,GAAG,SAAS,CAAA;AAC5B,CAAC;AAED,MAAM,UAAU,IAAI;IAClB,OAAO,sCAAsC,CAAC,OAAO,CAAC,OAAO,EAAE,UAAU,CAAC;QACxE,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EAChC,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,CA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1C,0BAA0B,GAAG,IAAI,CAAA;gBACjC,OAAO,CAAC,IAAI,CACV,2VAA2V,CAC5V,CAAA;aACF;YAED,OAAO,MAAM,CAAA;QACf,CAAC,CAAC,CAAA;KACH;AACH,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/local-storage.d.ts b/node_modules/@supabase/gotrue-js/dist/module/lib/local-storage.d.ts new file mode 100644 index 0000000..4e090a2 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/local-storage.d.ts @@ -0,0 +1,4 @@ +import { SupportedStorage } from './types'; +declare const localStorageAdapter: SupportedStorage; +export default localStorageAdapter; +//# sourceMappingURL=local-storage.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/local-storage.d.ts.map b/node_modules/@supabase/gotrue-js/dist/module/lib/local-storage.d.ts.map new file mode 100644 index 0000000..65b92be --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/local-storage.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"local-storage.d.ts","sourceRoot":"","sources":["../../../src/lib/local-storage.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE1C,QAAA,MAAM,mBAAmB,EAAE,gBAsB1B,CAAA;AAED,eAAe,mBAAmB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/local-storage.js b/node_modules/@supabase/gotrue-js/dist/module/lib/local-storage.js new file mode 100644 index 0000000..39f7356 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/local-storage.js @@ -0,0 +1,23 @@ +import { supportsLocalStorage } from './helpers'; +const localStorageAdapter = { + getItem: (key) => { + if (!supportsLocalStorage()) { + return null; + } + return globalThis.localStorage.getItem(key); + }, + setItem: (key, value) => { + if (!supportsLocalStorage()) { + return; + } + globalThis.localStorage.setItem(key, value); + }, + removeItem: (key) => { + if (!supportsLocalStorage()) { + return; + } + globalThis.localStorage.removeItem(key); + }, +}; +export default localStorageAdapter; +//# sourceMappingURL=local-storage.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/local-storage.js.map b/node_modules/@supabase/gotrue-js/dist/module/lib/local-storage.js.map new file mode 100644 index 0000000..1d26b36 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/local-storage.js.map @@ -0,0 +1 @@ +{"version":3,"file":"local-storage.js","sourceRoot":"","sources":["../../../src/lib/local-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAA;AAGhD,MAAM,mBAAmB,GAAqB;IAC5C,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;QACf,IAAI,CAAC,oBAAoB,EAAE,EAAE;YAC3B,OAAO,IAAI,CAAA;SACZ;QAED,OAAO,UAAU,CAAC,YAAY,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;IAC7C,CAAC;IACD,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE;QACtB,IAAI,CAAC,oBAAoB,EAAE,EAAE;YAC3B,OAAM;SACP;QAED,UAAU,CAAC,YAAY,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;IAC7C,CAAC;IACD,UAAU,EAAE,CAAC,GAAG,EAAE,EAAE;QAClB,IAAI,CAAC,oBAAoB,EAAE,EAAE;YAC3B,OAAM;SACP;QAED,UAAU,CAAC,YAAY,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;IACzC,CAAC;CACF,CAAA;AAED,eAAe,mBAAmB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/locks.d.ts b/node_modules/@supabase/gotrue-js/dist/module/lib/locks.d.ts new file mode 100644 index 0000000..6e1178d --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/locks.d.ts @@ -0,0 +1,42 @@ +/** + * @experimental + */ +export declare const internals: { + /** + * @experimental + */ + debug: boolean; +}; +export declare class NavigatorLockAcquireTimeoutError extends Error { + readonly isAcquireTimeout = true; + constructor(message: string); +} +/** + * Implements a global exclusive lock using the Navigator LockManager API. It + * is available on all browsers released after 2022-03-15 with Safari being the + * last one to release support. If the API is not available, this function will + * throw. Make sure you check availablility before configuring {@link + * GoTrueClient}. + * + * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug` + * local storage item to `true`. + * + * Internals: + * + * Since the LockManager API does not preserve stack traces for the async + * function passed in the `request` method, a trick is used where acquiring the + * lock releases a previously started promise to run the operation in the `fn` + * function. The lock waits for that promise to finish (with or without error), + * while the function will finally wait for the result anyway. + * + * @experimental + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + */ +export declare function navigatorLock(name: string, acquireTimeout: number, fn: () => Promise): Promise; +//# sourceMappingURL=locks.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/locks.d.ts.map b/node_modules/@supabase/gotrue-js/dist/module/lib/locks.d.ts.map new file mode 100644 index 0000000..a9a7dbe --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/locks.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"locks.d.ts","sourceRoot":"","sources":["../../../src/lib/locks.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,SAAS;IACpB;;OAEG;;CAMJ,CAAA;AAED,qBAAa,gCAAiC,SAAQ,KAAK;IACzD,SAAgB,gBAAgB,QAAO;gBAE3B,OAAO,EAAE,MAAM;CAG5B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAsB,aAAa,CAAC,CAAC,EACnC,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,EACtB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACnB,OAAO,CAAC,CAAC,CAAC,CA2GZ"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/locks.js b/node_modules/@supabase/gotrue-js/dist/module/lib/locks.js new file mode 100644 index 0000000..d249b46 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/locks.js @@ -0,0 +1,130 @@ +/** + * @experimental + */ +export const internals = { + /** + * @experimental + */ + debug: !!(globalThis && + globalThis.localStorage && + globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true'), +}; +export class NavigatorLockAcquireTimeoutError extends Error { + constructor(message) { + super(message); + this.isAcquireTimeout = true; + } +} +/** + * Implements a global exclusive lock using the Navigator LockManager API. It + * is available on all browsers released after 2022-03-15 with Safari being the + * last one to release support. If the API is not available, this function will + * throw. Make sure you check availablility before configuring {@link + * GoTrueClient}. + * + * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug` + * local storage item to `true`. + * + * Internals: + * + * Since the LockManager API does not preserve stack traces for the async + * function passed in the `request` method, a trick is used where acquiring the + * lock releases a previously started promise to run the operation in the `fn` + * function. The lock waits for that promise to finish (with or without error), + * while the function will finally wait for the result anyway. + * + * @experimental + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + */ +export async function navigatorLock(name, acquireTimeout, fn) { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout); + } + let beginOperation = null; + let rejectOperation = null; + const beginOperationPromise = new Promise((accept, reject) => { + beginOperation = accept; + rejectOperation = reject; + }); + // this lets us preserve stack traces over the operation, which the + // navigator.locks.request function does not preserve well still + const result = (async () => { + await beginOperationPromise; + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: operation start'); + } + try { + return await fn(); + } + finally { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: operation end'); + } + } + })(); + const abortController = new globalThis.AbortController(); + if (acquireTimeout > 0) { + setTimeout(() => { + beginOperation = null; + abortController.abort(); + if (rejectOperation) { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name); + } + if (rejectOperation) { + rejectOperation(new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${name}" timed out after ${acquireTimeout}ms`)); + } + beginOperation = null; + rejectOperation = null; + } + }, acquireTimeout); + } + await globalThis.navigator.locks.request(name, { + mode: 'exclusive', + ifAvailable: acquireTimeout === 0, + signal: abortController.signal, + }, async (lock) => { + if (lock) { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock acquired', name); + } + try { + if (beginOperation) { + beginOperation(); + beginOperation = null; + rejectOperation = null; + await result; + } + } + catch (e) { + // not important to handle the error here + } + finally { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock released', name); + } + } + } + else { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock not immediately available', name); + } + // no lock was available because acquireTimeout === 0 + const timeout = new Error(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`); + timeout.isAcquireTimeout = true; + if (rejectOperation) { + rejectOperation(new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`)); + } + beginOperation = null; + rejectOperation = null; + } + }); + return await result; +} +//# sourceMappingURL=locks.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/locks.js.map b/node_modules/@supabase/gotrue-js/dist/module/lib/locks.js.map new file mode 100644 index 0000000..4b357a9 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/locks.js.map @@ -0,0 +1 @@ +{"version":3,"file":"locks.js","sourceRoot":"","sources":["../../../src/lib/locks.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG;IAC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AE,IAAI,CAAC,CAAA;aAClF;YAED,qDAAqD;YACrD,MAAM,OAAO,GAAQ,IAAI,KAAK,CAC5B,sDAAsD,IAAI,sBAAsB,CACjF,CAAA;YACD,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAA;YAE/B,IAAI,eAAe,EAAE;gBACnB,eAAe,CACb,IAAI,gCAAgC,CAClC,sDAAsD,IAAI,sBAAsB,CACjF,CACF,CAAA;aACF;YACD,cAAc,GAAG,IAAI,CAAA;YACrB,eAAe,GAAG,IAAI,CAAA;SACvB;IACH,CAAC,CACF,CAAA;IAED,OAAO,MAAM,MAAM,CAAA;AACrB,CAAC"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/polyfills.d.ts b/node_modules/@supabase/gotrue-js/dist/module/lib/polyfills.d.ts new file mode 100644 index 0000000..d85562a --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/polyfills.d.ts @@ -0,0 +1,5 @@ +/** + * https://mathiasbynens.be/notes/globalthis + */ +export declare function polyfillGlobalThis(): void; +//# sourceMappingURL=polyfills.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/polyfills.d.ts.map b/node_modules/@supabase/gotrue-js/dist/module/lib/polyfills.d.ts.map new file mode 100644 index 0000000..ee5ea0f --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/polyfills.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfills.d.ts","sourceRoot":"","sources":["../../../src/lib/polyfills.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,wBAAgB,kBAAkB,SAmBjC"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/polyfills.js b/node_modules/@supabase/gotrue-js/dist/module/lib/polyfills.js new file mode 100644 index 0000000..7ab7d6c --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/polyfills.js @@ -0,0 +1,26 @@ +/** + * https://mathiasbynens.be/notes/globalthis + */ +export function polyfillGlobalThis() { + if (typeof globalThis === 'object') + return; + try { + Object.defineProperty(Object.prototype, '__magic__', { + get: function () { + return this; + }, + configurable: true, + }); + // @ts-expect-error 'Allow access to magic' + __magic__.globalThis = __magic__; + // @ts-expect-error 'Allow access to magic' + delete Object.prototype.__magic__; + } + catch (e) { + if (typeof self !== 'undefined') { + // @ts-expect-error 'Allow access to globals' + self.globalThis = self; + } + } +} +//# sourceMappingURL=polyfills.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/polyfills.js.map b/node_modules/@supabase/gotrue-js/dist/module/lib/polyfills.js.map new file mode 100644 index 0000000..63c5c15 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/polyfills.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfills.js","sourceRoot":"","sources":["../../../src/lib/polyfills.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,UAAU,kBAAkB;IAChC,IAAI,OAAO,UAAU,KAAK,QAAQ;QAAE,OAAM;IAC1C,IAAI;QACF,MAAM,CAAC,cAAc,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE;YACnD,GAAG,EAAE;gBACH,OAAO,IAAI,CAAA;YACb,CAAC;YACD,YAAY,EAAE,IAAI;SACnB,CAAC,CAAA;QACF,2CAA2C;QAC3C,SAAS,CAAC,UAAU,GAAG,SAAS,CAAA;QAChC,2CAA2C;QAC3C,OAAO,MAAM,CAAC,SAAS,CAAC,SAAS,CAAA;KAClC;IAAC,OAAO,CAAC,EAAE;QACV,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;YAC/B,6CAA6C;YAC7C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;SACvB;KACF;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/types.d.ts b/node_modules/@supabase/gotrue-js/dist/module/lib/types.d.ts new file mode 100644 index 0000000..9efcd2e --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/types.d.ts @@ -0,0 +1,905 @@ +import { AuthError } from './errors'; +import { Fetch } from './fetch'; +/** One of the providers supported by GoTrue. */ +export declare type Provider = 'apple' | 'azure' | 'bitbucket' | 'discord' | 'facebook' | 'figma' | 'github' | 'gitlab' | 'google' | 'kakao' | 'keycloak' | 'linkedin' | 'notion' | 'slack' | 'spotify' | 'twitch' | 'twitter' | 'workos' | 'zoom'; +export declare type AuthChangeEventMFA = 'MFA_CHALLENGE_VERIFIED'; +export declare type AuthChangeEvent = 'INITIAL_SESSION' | 'PASSWORD_RECOVERY' | 'SIGNED_IN' | 'SIGNED_OUT' | 'TOKEN_REFRESHED' | 'USER_UPDATED' | AuthChangeEventMFA; +/** + * Provide your own global lock implementation instead of the default + * implementation. The function should acquire a lock for the duration of the + * `fn` async function, such that no other client instances will be able to + * hold it at the same time. + * + * @experimental + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout should occur. If positive it + * should throw an Error with an `isAcquireTimeout` + * property set to true if the operation fails to be + * acquired after this much time (ms). + * @param fn The operation to execute when the lock is acquired. + */ +export declare type LockFunc = (name: string, acquireTimeout: number, fn: () => Promise) => Promise; +export declare type GoTrueClientOptions = { + url?: string; + headers?: { + [key: string]: string; + }; + storageKey?: string; + detectSessionInUrl?: boolean; + autoRefreshToken?: boolean; + persistSession?: boolean; + storage?: SupportedStorage; + fetch?: Fetch; + flowType?: AuthFlowType; + debug?: boolean; + /** + * Provide your own locking mechanism based on the environment. By default no locking is done at this time. + * + * @experimental + */ + lock?: LockFunc; +}; +export declare type AuthResponse = { + data: { + user: User | null; + session: Session | null; + }; + error: null; +} | { + data: { + user: null; + session: null; + }; + error: AuthError; +}; +/** + * AuthOtpResponse is returned when OTP is used. + * + * {@see AuthRsponse} + */ +export declare type AuthOtpResponse = { + data: { + user: null; + session: null; + messageId?: string | null; + }; + error: null; +} | { + data: { + user: null; + session: null; + messageId?: string | null; + }; + error: AuthError; +}; +export declare type AuthTokenResponse = { + data: { + user: User; + session: Session; + }; + error: null; +} | { + data: { + user: null; + session: null; + }; + error: AuthError; +}; +export declare type OAuthResponse = { + data: { + provider: Provider; + url: string; + }; + error: null; +} | { + data: { + provider: Provider; + url: null; + }; + error: AuthError; +}; +export declare type SSOResponse = { + data: { + /** + * URL to open in a browser which will complete the sign-in flow by + * taking the user to the identity provider's authentication flow. + * + * On browsers you can set the URL to `window.location.href` to take + * the user to the authentication flow. + */ + url: string; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +export declare type UserResponse = { + data: { + user: User; + }; + error: null; +} | { + data: { + user: null; + }; + error: AuthError; +}; +export interface Session { + /** + * The oauth provider token. If present, this can be used to make external API requests to the oauth provider used. + */ + provider_token?: string | null; + /** + * The oauth provider refresh token. If present, this can be used to refresh the provider_token via the oauth provider's API. + * Not all oauth providers return a provider refresh token. If the provider_refresh_token is missing, please refer to the oauth provider's documentation for information on how to obtain the provider refresh token. + */ + provider_refresh_token?: string | null; + /** + * The access token jwt. It is recommended to set the JWT_EXPIRY to a shorter expiry value. + */ + access_token: string; + /** + * A one-time used refresh token that never expires. + */ + refresh_token: string; + /** + * The number of seconds until the token expires (since it was issued). Returned when a login is confirmed. + */ + expires_in: number; + /** + * A timestamp of when the token will expire. Returned when a login is confirmed. + */ + expires_at?: number; + token_type: string; + user: User; +} +/** + * An authentication methord reference (AMR) entry. + * + * An entry designates what method was used by the user to verify their + * identity and at what time. + * + * @see {@link GoTrueMFAApi#getAuthenticatorAssuranceLevel}. + */ +export interface AMREntry { + /** Authentication method name. */ + method: 'password' | 'otp' | 'oauth' | 'mfa/totp' | string; + /** + * Timestamp when the method was successfully used. Represents number of + * seconds since 1st January 1970 (UNIX epoch) in UTC. + */ + timestamp: number; +} +export interface UserIdentity { + id: string; + user_id: string; + identity_data?: { + [key: string]: any; + }; + provider: string; + created_at?: string; + last_sign_in_at?: string; + updated_at?: string; +} +/** + * A MFA factor. + * + * @see {@link GoTrueMFAApi#enroll} + * @see {@link GoTrueMFAApi#listFactors} + * @see {@link GoTrueMFAAdminApi#listFactors} + */ +export interface Factor { + /** ID of the factor. */ + id: string; + /** Friendly name of the factor, useful to disambiguate between multiple factors. */ + friendly_name?: string; + /** + * Type of factor. Only `totp` supported with this version but may change in + * future versions. + */ + factor_type: 'totp' | string; + /** Factor's status. */ + status: 'verified' | 'unverified'; + created_at: string; + updated_at: string; +} +export interface UserAppMetadata { + provider?: string; + [key: string]: any; +} +export interface UserMetadata { + [key: string]: any; +} +export interface User { + id: string; + app_metadata: UserAppMetadata; + user_metadata: UserMetadata; + aud: string; + confirmation_sent_at?: string; + recovery_sent_at?: string; + email_change_sent_at?: string; + new_email?: string; + new_phone?: string; + invited_at?: string; + action_link?: string; + email?: string; + phone?: string; + created_at: string; + confirmed_at?: string; + email_confirmed_at?: string; + phone_confirmed_at?: string; + last_sign_in_at?: string; + role?: string; + updated_at?: string; + identities?: UserIdentity[]; + factors?: Factor[]; +} +export interface UserAttributes { + /** + * The user's email. + */ + email?: string; + /** + * The user's phone. + */ + phone?: string; + /** + * The user's password. + */ + password?: string; + /** + * The nonce sent for reauthentication if the user's password is to be updated. + * + * Call reauthenticate() to obtain the nonce first. + */ + nonce?: string; + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + * + */ + data?: object; +} +export interface AdminUserAttributes extends Omit { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * + * The `user_metadata` should be a JSON object that includes user-specific info, such as their first and last name. + * + * Note: When using the GoTrueAdminApi and wanting to modify a user's metadata, + * this attribute is used instead of UserAttributes data. + * + */ + user_metadata?: object; + /** + * A custom data object to store the user's application specific metadata. This maps to the `auth.users.app_metadata` column. + * + * Only a service role can modify. + * + * The `app_metadata` should be a JSON object that includes app-specific info, such as identity providers, roles, and other + * access control information. + */ + app_metadata?: object; + /** + * Confirms the user's email address if set to true. + * + * Only a service role can modify. + */ + email_confirm?: boolean; + /** + * Confirms the user's phone number if set to true. + * + * Only a service role can modify. + */ + phone_confirm?: boolean; + /** + * Determines how long a user is banned for. + * + * The format for the ban duration follows a strict sequence of decimal numbers with a unit suffix. + * Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + * + * For example, some possible durations include: '300ms', '2h45m'. + * + * Setting the ban duration to 'none' lifts the ban on the user. + */ + ban_duration?: string | 'none'; +} +export interface Subscription { + /** + * The subscriber UUID. This will be set by the client. + */ + id: string; + /** + * The function to call every time there is an event. eg: (eventName) => {} + */ + callback: (event: AuthChangeEvent, session: Session | null) => void; + /** + * Call this to remove the listener. + */ + unsubscribe: () => void; +} +export interface UpdatableFactorAttributes { + friendlyName: string; +} +export declare type SignUpWithPasswordCredentials = { + /** The user's email address. */ + email: string; + /** The user's password. */ + password: string; + options?: { + /** The redirect url embedded in the email link */ + emailRedirectTo?: string; + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +} | { + /** The user's phone number. */ + phone: string; + /** The user's password. */ + password: string; + options?: { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** Verification token received when the user completes the captcha on the site. Requires a configured WhatsApp sender on Twilio */ + captchaToken?: string; + /** Messaging channel to use (e.g. whatsapp or sms) */ + channel?: 'sms' | 'whatsapp'; + }; +}; +export declare type SignInWithPasswordCredentials = { + /** The user's email address. */ + email: string; + /** The user's password. */ + password: string; + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +} | { + /** The user's phone number. */ + phone: string; + /** The user's password. */ + password: string; + options?: { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export declare type SignInWithPasswordlessCredentials = { + /** The user's email address. */ + email: string; + options?: { + /** The redirect url embedded in the email link */ + emailRedirectTo?: string; + /** If set to false, this method will not create a new user. Defaults to true. */ + shouldCreateUser?: boolean; + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +} | { + /** The user's phone number. */ + phone: string; + options?: { + /** If set to false, this method will not create a new user. Defaults to true. */ + shouldCreateUser?: boolean; + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + /** Messaging channel to use (e.g. whatsapp or sms) */ + channel?: 'sms' | 'whatsapp'; + }; +}; +export declare type AuthFlowType = 'implicit' | 'pkce'; +export declare type SignInWithOAuthCredentials = { + /** One of the providers supported by GoTrue. */ + provider: Provider; + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string; + /** A space-separated list of scopes granted to the OAuth application. */ + scopes?: string; + /** An object of query params */ + queryParams?: { + [key: string]: string; + }; + /** If set to true does not immediately redirect the current browser context to visit the OAuth authorization page for the provider. */ + skipBrowserRedirect?: boolean; + }; +}; +export declare type SignInWithIdTokenCredentials = { + /** Provider name or OIDC `iss` value identifying which provider should be used to verify the provided token. Supported names: `google`, `apple`, `azure`, `facebook`, `keycloak` (deprecated). */ + provider: 'google' | 'apple' | 'azure' | 'facebook' | string; + /** OIDC ID token issued by the specified provider. The `iss` claim in the ID token must match the supplied provider. Some ID tokens contain an `at_hash` which require that you provide an `access_token` value to be accepted properly. If the token contains a `nonce` claim you must supply the nonce used to obtain the ID token. */ + token: string; + /** If the ID token contains an `at_hash` claim, then the hash of this value is compared to the value in the ID token. */ + access_token?: string; + /** If the ID token contains a `nonce` claim, then the hash of this value is compared to the value in the ID token. */ + nonce?: string; + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export declare type VerifyOtpParams = VerifyMobileOtpParams | VerifyEmailOtpParams | VerifyTokenHashParams; +export interface VerifyMobileOtpParams { + /** The user's phone number. */ + phone: string; + /** The otp sent to the user's phone number. */ + token: string; + /** The user's verification type. */ + type: MobileOtpType; + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string; + /** + * Verification token received when the user completes the captcha on the site. + * + * @deprecated + */ + captchaToken?: string; + }; +} +export interface VerifyEmailOtpParams { + /** The user's email address. */ + email: string; + /** The otp sent to the user's email address. */ + token: string; + /** The user's verification type. */ + type: EmailOtpType; + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string; + /** Verification token received when the user completes the captcha on the site. + * + * @deprecated + */ + captchaToken?: string; + }; +} +export interface VerifyTokenHashParams { + /** The token hash used in an email link */ + token_hash: string; + /** The user's verification type. */ + type: EmailOtpType; +} +export declare type MobileOtpType = 'sms' | 'phone_change'; +export declare type EmailOtpType = 'signup' | 'invite' | 'magiclink' | 'recovery' | 'email_change' | 'email'; +export declare type ResendParams = { + type: Extract; + email: string; + options?: { + /** A URL to send the user to after they have signed-in. */ + emailRedirectTo?: string; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +} | { + type: Extract; + phone: string; + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export declare type SignInWithSSO = { + /** UUID of the SSO provider to invoke single-sign on to. */ + providerId: string; + options?: { + /** A URL to send the user to after they have signed-in. */ + redirectTo?: string; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +} | { + /** Domain name of the organization for which to invoke single-sign on. */ + domain: string; + options?: { + /** A URL to send the user to after they have signed-in. */ + redirectTo?: string; + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string; + }; +}; +export declare type GenerateSignupLinkParams = { + type: 'signup'; + email: string; + password: string; + options?: Pick; +}; +export declare type GenerateInviteOrMagiclinkParams = { + type: 'invite' | 'magiclink'; + /** The user's email */ + email: string; + options?: Pick; +}; +export declare type GenerateRecoveryLinkParams = { + type: 'recovery'; + /** The user's email */ + email: string; + options?: Pick; +}; +export declare type GenerateEmailChangeLinkParams = { + type: 'email_change_current' | 'email_change_new'; + /** The user's email */ + email: string; + /** + * The user's new email. Only required if type is 'email_change_current' or 'email_change_new'. + */ + newEmail: string; + options?: Pick; +}; +export interface GenerateLinkOptions { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object; + /** The URL which will be appended to the email link generated. */ + redirectTo?: string; +} +export declare type GenerateLinkParams = GenerateSignupLinkParams | GenerateInviteOrMagiclinkParams | GenerateRecoveryLinkParams | GenerateEmailChangeLinkParams; +export declare type GenerateLinkResponse = { + data: { + properties: GenerateLinkProperties; + user: User; + }; + error: null; +} | { + data: { + properties: null; + user: null; + }; + error: AuthError; +}; +/** The properties related to the email link generated */ +export declare type GenerateLinkProperties = { + /** + * The email link to send to the user. + * The action_link follows the following format: auth/v1/verify?type={verification_type}&token={hashed_token}&redirect_to={redirect_to} + * */ + action_link: string; + /** + * The raw email OTP. + * You should send this in the email if you want your users to verify using an OTP instead of the action link. + * */ + email_otp: string; + /** + * The hashed token appended to the action link. + * */ + hashed_token: string; + /** The URL appended to the action link. */ + redirect_to: string; + /** The verification type that the email link is associated to. */ + verification_type: GenerateLinkType; +}; +export declare type GenerateLinkType = 'signup' | 'invite' | 'magiclink' | 'recovery' | 'email_change_current' | 'email_change_new'; +export declare type MFAEnrollParams = { + /** The type of factor being enrolled. */ + factorType: 'totp'; + /** Domain which the user is enrolled with. */ + issuer?: string; + /** Human readable name assigned to the factor. */ + friendlyName?: string; +}; +export declare type MFAUnenrollParams = { + /** ID of the factor being unenrolled. */ + factorId: string; +}; +export declare type MFAVerifyParams = { + /** ID of the factor being verified. Returned in enroll(). */ + factorId: string; + /** ID of the challenge being verified. Returned in challenge(). */ + challengeId: string; + /** Verification code provided by the user. */ + code: string; +}; +export declare type MFAChallengeParams = { + /** ID of the factor to be challenged. Returned in enroll(). */ + factorId: string; +}; +export declare type MFAChallengeAndVerifyParams = { + /** ID of the factor being verified. Returned in enroll(). */ + factorId: string; + /** Verification code provided by the user. */ + code: string; +}; +export declare type AuthMFAVerifyResponse = { + data: { + /** New access token (JWT) after successful verification. */ + access_token: string; + /** Type of token, typically `Bearer`. */ + token_type: string; + /** Number of seconds in which the access token will expire. */ + expires_in: number; + /** Refresh token you can use to obtain new access tokens when expired. */ + refresh_token: string; + /** Updated user profile. */ + user: User; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +export declare type AuthMFAEnrollResponse = { + data: { + /** ID of the factor that was just enrolled (in an unverified state). */ + id: string; + /** Type of MFA factor. Only `totp` supported for now. */ + type: 'totp'; + /** TOTP enrollment information. */ + totp: { + /** Contains a QR code encoding the authenticator URI. You can + * convert it to a URL by prepending `data:image/svg+xml;utf-8,` to + * the value. Avoid logging this value to the console. */ + qr_code: string; + /** The TOTP secret (also encoded in the QR code). Show this secret + * in a password-style field to the user, in case they are unable to + * scan the QR code. Avoid logging this value to the console. */ + secret: string; + /** The authenticator URI encoded within the QR code, should you need + * to use it. Avoid loggin this value to the console. */ + uri: string; + }; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +export declare type AuthMFAUnenrollResponse = { + data: { + /** ID of the factor that was successfully unenrolled. */ + id: string; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +export declare type AuthMFAChallengeResponse = { + data: { + /** ID of the newly created challenge. */ + id: string; + /** Timestamp in UNIX seconds when this challenge will no longer be usable. */ + expires_at: number; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +export declare type AuthMFAListFactorsResponse = { + data: { + /** All available factors (verified and unverified). */ + all: Factor[]; + /** Only verified TOTP factors. (A subset of `all`.) */ + totp: Factor[]; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +export declare type AuthenticatorAssuranceLevels = 'aal1' | 'aal2'; +export declare type AuthMFAGetAuthenticatorAssuranceLevelResponse = { + data: { + /** Current AAL level of the session. */ + currentLevel: AuthenticatorAssuranceLevels | null; + /** + * Next possible AAL level for the session. If the next level is higher + * than the current one, the user should go through MFA. + * + * @see {@link GoTrueMFAApi#challenge} + */ + nextLevel: AuthenticatorAssuranceLevels | null; + /** + * A list of all authentication methods attached to this session. Use + * the information here to detect the last time a user verified a + * factor, for example if implementing a step-up scenario. + */ + currentAuthenticationMethods: AMREntry[]; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +/** + * Contains the full multi-factor authentication API. + * + */ +export interface GoTrueMFAApi { + /** + * Starts the enrollment process for a new Multi-Factor Authentication (MFA) + * factor. This method creates a new `unverified` factor. + * To verify a factor, present the QR code or secret to the user and ask them to add it to their + * authenticator app. + * The user has to enter the code from their authenticator app to verify it. + * + * Upon verifying a factor, all other sessions are logged out and the current session's authenticator level is promoted to `aal2`. + * + */ + enroll(params: MFAEnrollParams): Promise; + /** + * Prepares a challenge used to verify that a user has access to a MFA + * factor. + */ + challenge(params: MFAChallengeParams): Promise; + /** + * Verifies a code against a challenge. The verification code is + * provided by the user by entering a code seen in their authenticator app. + */ + verify(params: MFAVerifyParams): Promise; + /** + * Unenroll removes a MFA factor. + * A user has to have an `aal2` authenticator level in order to unenroll a `verified` factor. + */ + unenroll(params: MFAUnenrollParams): Promise; + /** + * Helper method which creates a challenge and immediately uses the given code to verify against it thereafter. The verification code is + * provided by the user by entering a code seen in their authenticator app. + */ + challengeAndVerify(params: MFAChallengeAndVerifyParams): Promise; + /** + * Returns the list of MFA factors enabled for this user. + * + * @see {@link GoTrueMFAApi#enroll} + * @see {@link GoTrueMFAApi#getAuthenticatorAssuranceLevel} + * @see {@link GoTrueClient#getUser} + * + */ + listFactors(): Promise; + /** + * Returns the Authenticator Assurance Level (AAL) for the active session. + * + * - `aal1` (or `null`) means that the user's identity has been verified only + * with a conventional login (email+password, OTP, magic link, social login, + * etc.). + * - `aal2` means that the user's identity has been verified both with a conventional login and at least one MFA factor. + * + * Although this method returns a promise, it's fairly quick (microseconds) + * and rarely uses the network. You can use this to check whether the current + * user needs to be shown a screen to verify their MFA factors. + * + */ + getAuthenticatorAssuranceLevel(): Promise; +} +/** + * @expermental + */ +export declare type AuthMFAAdminDeleteFactorResponse = { + data: { + /** ID of the factor that was successfully deleted. */ + id: string; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +/** + * @expermental + */ +export declare type AuthMFAAdminDeleteFactorParams = { + /** ID of the MFA factor to delete. */ + id: string; + /** ID of the user whose factor is being deleted. */ + userId: string; +}; +/** + * @expermental + */ +export declare type AuthMFAAdminListFactorsResponse = { + data: { + /** All factors attached to the user. */ + factors: Factor[]; + }; + error: null; +} | { + data: null; + error: AuthError; +}; +/** + * @expermental + */ +export declare type AuthMFAAdminListFactorsParams = { + /** ID of the user. */ + userId: string; +}; +/** + * Contains the full multi-factor authentication administration API. + * + * @expermental + */ +export interface GoTrueAdminMFAApi { + /** + * Lists all factors associated to a user. + * + */ + listFactors(params: AuthMFAAdminListFactorsParams): Promise; + /** + * Deletes a factor on a user. This will log the user out of all active + * sessions if the deleted factor was verified. + * + * @see {@link GoTrueMFAApi#unenroll} + * + * @expermental + */ + deleteFactor(params: AuthMFAAdminDeleteFactorParams): Promise; +} +declare type AnyFunction = (...args: any[]) => any; +declare type MaybePromisify = T | Promise; +declare type PromisifyMethods = { + [K in keyof T]: T[K] extends AnyFunction ? (...args: Parameters) => MaybePromisify> : T[K]; +}; +export declare type SupportedStorage = PromisifyMethods>; +export declare type InitializeResult = { + error: AuthError | null; +}; +export declare type CallRefreshTokenResult = { + session: Session; + error: null; +} | { + session: null; + error: AuthError; +}; +export declare type Pagination = { + [key: string]: any; + nextPage: number | null; + lastPage: number; + total: number; +}; +export declare type PageParams = { + /** The page number */ + page?: number; + /** Number of items returned per page */ + perPage?: number; +}; +export declare type SignOut = { + /** + * Determines which sessions should be + * logged out. Global means all + * sessions by this account. Local + * means only this session. Others + * means all other sessions except the + * current one. When using others, + * there is no sign-out event fired on + * the current session! + */ + scope?: 'global' | 'local' | 'others'; +}; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/types.d.ts.map b/node_modules/@supabase/gotrue-js/dist/module/lib/types.d.ts.map new file mode 100644 index 0000000..47b5175 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AACpC,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAE/B,gDAAgD;AAChD,oBAAY,QAAQ,GAChB,OAAO,GACP,OAAO,GACP,WAAW,GACX,SAAS,GACT,UAAU,GACV,OAAO,GACP,QAAQ,GACR,QAAQ,GACR,QAAQ,GACR,OAAO,GACP,UAAU,GACV,UAAU,GACV,QAAQ,GACR,OAAO,GACP,SAAS,GACT,QAAQ,GACR,SAAS,GACT,QAAQ,GACR,MAAM,CAAA;AAEV,oBAAY,kBAAkB,GAAG,wBAAwB,CAAA;AAEzD,oBAAY,eAAe,GACvB,iBAAiB,GACjB,mBAAmB,GACnB,WAAW,GACX,YAAY,GACZ,iBAAiB,GACjB,cAAc,GACd,kBAAkB,CAAA;AAEtB;;;;;;;;;;;;;;GAcG;AACH,oBAAY,QAAQ,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,CAAA;AAEpG,oBAAY,mBAAmB,GAAG;IAEhC,GAAG,CAAC,EAAE,MAAM,CAAA;IAEZ,OAAO,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAA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C,CAAA;AAEpG,oBAAY,gBAAgB,GAAG;IAAE,KAAK,EAAE,SAAS,GAAG,IAAI,CAAA;CAAE,CAAA;AAE1D,oBAAY,sBAAsB,GAC9B;IACE,OAAO,EAAE,OAAO,CAAA;IAChB,KAAK,EAAE,IAAI,CAAA;CACZ,GACD;IACE,OAAO,EAAE,IAAI,CAAA;IACb,KAAK,EAAE,SAAS,CAAA;CACjB,CAAA;AAEL,oBAAY,UAAU,GAAG;IACvB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;IAClB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;IACvB,QAAQ,EAAE,MAAM,CAAA;IAChB,KAAK,EAAE,MAAM,CAAA;CACd,CAAA;AAED,oBAAY,UAAU,GAAG;IACvB,sBAAsB;IACtB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,wCAAwC;IACxC,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB,CAAA;AAED,oBAAY,OAAO,GAAG;IACpB;;;;;;;;;OASG;IACH,KAAK,CAAC,EAAE,QAAQ,GAAG,OAAO,GAAG,QAAQ,CAAA;CACtC,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/types.js b/node_modules/@supabase/gotrue-js/dist/module/lib/types.js new file mode 100644 index 0000000..718fd38 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/types.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/types.js.map b/node_modules/@supabase/gotrue-js/dist/module/lib/types.js.map new file mode 100644 index 0000000..5bb5e4d --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/version.d.ts b/node_modules/@supabase/gotrue-js/dist/module/lib/version.d.ts new file mode 100644 index 0000000..177f1a8 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.46.1"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/version.d.ts.map b/node_modules/@supabase/gotrue-js/dist/module/lib/version.d.ts.map new file mode 100644 index 0000000..808651b --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,OAAO,UAAU,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/version.js b/node_modules/@supabase/gotrue-js/dist/module/lib/version.js new file mode 100644 index 0000000..6f62933 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/version.js @@ -0,0 +1,3 @@ +// Generated by genversion. +export const version = '2.46.1'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/dist/module/lib/version.js.map b/node_modules/@supabase/gotrue-js/dist/module/lib/version.js.map new file mode 100644 index 0000000..cad5370 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/dist/module/lib/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAAA,2BAA2B;AAC3B,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/gotrue-js/package.json b/node_modules/@supabase/gotrue-js/package.json new file mode 100644 index 0000000..4a5bd13 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/package.json @@ -0,0 +1,68 @@ +{ + "name": "@supabase/gotrue-js", + "version": "2.46.1", + "description": "Isomorphic GoTrue client", + "keywords": [ + "gotrue", + "supabase", + "auth", + "authentication" + ], + "homepage": "https://github.com/supabase/gotrue-js", + "bugs": "https://github.com/supabase/gotrue-js/issues", + "license": "MIT", + "author": "Supabase", + "files": [ + "dist", + "src" + ], + "main": "dist/main/index.js", + "module": "dist/module/index.js", + "types": "dist/module/index.d.ts", + "repository": "supabase/gotrue-js", + "scripts": { + "clean": "rimraf dist docs", + "coverage": "echo \"run npm test\"", + "format": "prettier --write \"{src,test}/**/*.ts\"", + "build": "genversion src/lib/version.ts --es6 && run-s clean format build:* && run-s lint", + "build:main": "tsc -p tsconfig.json", + "build:module": "tsc -p tsconfig.module.json", + "lint": "eslint ./src/**/* test/**/*.test.ts", + "test": "run-s test:clean test:infra test:suite test:clean", + "test:suite": "jest --runInBand", + "test:infra": "cd infra && docker-compose down && docker-compose pull && docker-compose up -d && sleep 30", + "test:clean": "cd infra && docker-compose down", + "docs": "typedoc src/index.ts --out docs/v2 --excludePrivate --excludeProtected", + "docs:json": "typedoc --json docs/v2/spec.json --excludeExternals --excludePrivate --excludeProtected src/index.ts" + }, + "dependencies": { + "cross-fetch": "^3.1.5" + }, + "devDependencies": { + "@types/faker": "^5.1.6", + "@types/jest": "^28.1.6", + "@types/jsonwebtoken": "^8.5.6", + "@types/node": "^18.16.19", + "@types/node-fetch": "^2.6.4", + "@typescript-eslint/eslint-plugin": "^5.30.7", + "@typescript-eslint/parser": "^5.30.7", + "eslint": "^8.20.0", + "eslint-config-prettier": "^8.5.0", + "eslint-config-standard": "^17.0.0", + "eslint-plugin-import": "^2.26.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-promise": "^6.0.0", + "faker": "^5.3.1", + "genversion": "^3.1.1", + "jest": "^28.1.3", + "jest-mock-server": "^0.1.0", + "jsonwebtoken": "^9.0.0", + "npm-run-all": "^4.1.5", + "prettier": "2.7.1", + "rimraf": "^3.0.2", + "semantic-release-plugin-update-version-in-files": "^1.1.0", + "ts-jest": "^28.0.7", + "typedoc": "^0.22.16", + "typescript": "^4.7.4" + } +} diff --git a/node_modules/@supabase/gotrue-js/src/GoTrueAdminApi.ts b/node_modules/@supabase/gotrue-js/src/GoTrueAdminApi.ts new file mode 100644 index 0000000..ddd5149 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/src/GoTrueAdminApi.ts @@ -0,0 +1,333 @@ +import { + Fetch, + _generateLinkResponse, + _noResolveJsonResponse, + _request, + _userResponse, +} from './lib/fetch' +import { resolveFetch } from './lib/helpers' +import { + AdminUserAttributes, + GenerateLinkParams, + GenerateLinkResponse, + Pagination, + User, + UserResponse, + GoTrueAdminMFAApi, + AuthMFAAdminDeleteFactorParams, + AuthMFAAdminDeleteFactorResponse, + AuthMFAAdminListFactorsParams, + AuthMFAAdminListFactorsResponse, + PageParams, +} from './lib/types' +import { AuthError, isAuthError } from './lib/errors' + +export default class GoTrueAdminApi { + /** Contains all MFA administration methods. */ + mfa: GoTrueAdminMFAApi + + protected url: string + protected headers: { + [key: string]: string + } + protected fetch: Fetch + + constructor({ + url = '', + headers = {}, + fetch, + }: { + url: string + headers?: { + [key: string]: string + } + fetch?: Fetch + }) { + this.url = url + this.headers = headers + this.fetch = resolveFetch(fetch) + this.mfa = { + listFactors: this._listFactors.bind(this), + deleteFactor: this._deleteFactor.bind(this), + } + } + + /** + * Removes a logged-in session. + * @param jwt A valid, logged-in JWT. + * @param scope The logout sope. + */ + async signOut( + jwt: string, + scope: 'global' | 'local' | 'others' = 'global' + ): Promise<{ data: null; error: AuthError | null }> { + try { + await _request(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, { + headers: this.headers, + jwt, + noResolveJson: true, + }) + return { data: null, error: null } + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Sends an invite link to an email address. + * @param email The email address of the user. + * @param options Additional options to be included when inviting. + */ + async inviteUserByEmail( + email: string, + options: { + /** A custom data object to store additional metadata about the user. This maps to the `auth.users.user_metadata` column. */ + data?: object + + /** The URL which will be appended to the email link sent to the user's email address. Once clicked the user will end up on this URL. */ + redirectTo?: string + } = {} + ): Promise { + try { + return await _request(this.fetch, 'POST', `${this.url}/invite`, { + body: { email, data: options.data }, + headers: this.headers, + redirectTo: options.redirectTo, + xform: _userResponse, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error } + } + + throw error + } + } + + /** + * Generates email links and OTPs to be sent via a custom email provider. + * @param email The user's email. + * @param options.password User password. For signup only. + * @param options.data Optional user metadata. For signup only. + * @param options.redirectTo The redirect url which should be appended to the generated link + */ + async generateLink(params: GenerateLinkParams): Promise { + try { + const { options, ...rest } = params + const body: any = { ...rest, ...options } + if ('newEmail' in rest) { + // replace newEmail with new_email in request body + body.new_email = rest?.newEmail + delete body['newEmail'] + } + return await _request(this.fetch, 'POST', `${this.url}/admin/generate_link`, { + body: body, + headers: this.headers, + xform: _generateLinkResponse, + redirectTo: options?.redirectTo, + }) + } catch (error) { + if (isAuthError(error)) { + return { + data: { + properties: null, + user: null, + }, + error, + } + } + throw error + } + } + + // User Admin API + /** + * Creates a new user. + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async createUser(attributes: AdminUserAttributes): Promise { + try { + return await _request(this.fetch, 'POST', `${this.url}/admin/users`, { + body: attributes, + headers: this.headers, + xform: _userResponse, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error } + } + + throw error + } + } + + /** + * Get a list of users. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. + */ + async listUsers( + params?: PageParams + ): Promise< + | { data: { users: User[]; aud: string } & Pagination; error: null } + | { data: { users: [] }; error: AuthError } + > { + try { + const pagination: Pagination = { nextPage: null, lastPage: 0, total: 0 } + const response = await _request(this.fetch, 'GET', `${this.url}/admin/users`, { + headers: this.headers, + noResolveJson: true, + query: { + page: params?.page?.toString() ?? '', + per_page: params?.perPage?.toString() ?? '', + }, + xform: _noResolveJsonResponse, + }) + if (response.error) throw response.error + + const users = await response.json() + const total = response.headers.get('x-total-count') ?? 0 + const links = response.headers.get('link')?.split(',') ?? [] + if (links.length > 0) { + links.forEach((link: string) => { + const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)) + const rel = JSON.parse(link.split(';')[1].split('=')[1]) + pagination[`${rel}Page`] = page + }) + + pagination.total = parseInt(total) + } + return { data: { ...users, ...pagination }, error: null } + } catch (error) { + if (isAuthError(error)) { + return { data: { users: [] }, error } + } + throw error + } + } + + /** + * Get user by id. + * + * @param uid The user's unique identifier + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async getUserById(uid: string): Promise { + try { + return await _request(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, { + headers: this.headers, + xform: _userResponse, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error } + } + + throw error + } + } + + /** + * Updates the user data. + * + * @param attributes The data you want to update. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async updateUserById(uid: string, attributes: AdminUserAttributes): Promise { + try { + return await _request(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, { + body: attributes, + headers: this.headers, + xform: _userResponse, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error } + } + + throw error + } + } + + /** + * Delete a user. Requires a `service_role` key. + * + * @param id The user id you want to remove. + * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. + * Defaults to false for backward compatibility. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async deleteUser(id: string, shouldSoftDelete = false): Promise { + try { + return await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, { + headers: this.headers, + body: { + should_soft_delete: shouldSoftDelete, + }, + xform: _userResponse, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error } + } + + throw error + } + } + + private async _listFactors( + params: AuthMFAAdminListFactorsParams + ): Promise { + try { + const { data, error } = await _request( + this.fetch, + 'GET', + `${this.url}/admin/users/${params.userId}/factors`, + { + headers: this.headers, + xform: (factors: any) => { + return { data: { factors }, error: null } + }, + } + ) + return { data, error } + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + + throw error + } + } + + private async _deleteFactor( + params: AuthMFAAdminDeleteFactorParams + ): Promise { + try { + const data = await _request( + this.fetch, + 'DELETE', + `${this.url}/admin/users/${params.userId}/factors/${params.id}`, + { + headers: this.headers, + } + ) + + return { data, error: null } + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + + throw error + } + } +} diff --git a/node_modules/@supabase/gotrue-js/src/GoTrueClient.ts b/node_modules/@supabase/gotrue-js/src/GoTrueClient.ts new file mode 100644 index 0000000..b09012a --- /dev/null +++ b/node_modules/@supabase/gotrue-js/src/GoTrueClient.ts @@ -0,0 +1,2165 @@ +import GoTrueAdminApi from './GoTrueAdminApi' +import { DEFAULT_HEADERS, EXPIRY_MARGIN, GOTRUE_URL, STORAGE_KEY } from './lib/constants' +import { + AuthError, + AuthImplicitGrantRedirectError, + AuthPKCEGrantCodeExchangeError, + AuthInvalidCredentialsError, + AuthRetryableFetchError, + AuthSessionMissingError, + AuthInvalidTokenResponseError, + AuthUnknownError, + isAuthApiError, + isAuthError, + isAuthRetryableFetchError, +} from './lib/errors' +import { Fetch, _request, _sessionResponse, _userResponse, _ssoResponse } from './lib/fetch' +import { + decodeJWTPayload, + Deferred, + getItemAsync, + isBrowser, + removeItemAsync, + resolveFetch, + setItemAsync, + uuid, + retryable, + sleep, + generatePKCEVerifier, + generatePKCEChallenge, + supportsLocalStorage, + stackGuard, + isInStackGuard, + stackGuardsSupported, + parseParametersFromURL, +} from './lib/helpers' +import localStorageAdapter from './lib/local-storage' +import { polyfillGlobalThis } from './lib/polyfills' +import { version } from './lib/version' + +import type { + AuthChangeEvent, + AuthResponse, + AuthTokenResponse, + AuthOtpResponse, + CallRefreshTokenResult, + GoTrueClientOptions, + InitializeResult, + OAuthResponse, + SSOResponse, + Provider, + Session, + SignInWithIdTokenCredentials, + SignInWithOAuthCredentials, + SignInWithPasswordCredentials, + SignInWithPasswordlessCredentials, + SignUpWithPasswordCredentials, + SignInWithSSO, + SignOut, + Subscription, + SupportedStorage, + User, + UserAttributes, + UserResponse, + VerifyOtpParams, + GoTrueMFAApi, + MFAEnrollParams, + AuthMFAEnrollResponse, + MFAChallengeParams, + AuthMFAChallengeResponse, + MFAUnenrollParams, + AuthMFAUnenrollResponse, + MFAVerifyParams, + AuthMFAVerifyResponse, + AuthMFAListFactorsResponse, + AMREntry, + AuthMFAGetAuthenticatorAssuranceLevelResponse, + AuthenticatorAssuranceLevels, + Factor, + MFAChallengeAndVerifyParams, + ResendParams, + AuthFlowType, + LockFunc, +} from './lib/types' + +polyfillGlobalThis() // Make "globalThis" available + +const DEFAULT_OPTIONS: Omit, 'fetch' | 'storage' | 'lock'> = { + url: GOTRUE_URL, + storageKey: STORAGE_KEY, + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + headers: DEFAULT_HEADERS, + flowType: 'implicit', + debug: false, +} + +/** Current session will be checked for refresh at this interval. */ +const AUTO_REFRESH_TICK_DURATION = 30 * 1000 + +/** + * A token refresh will be attempted this many ticks before the current session expires. */ +const AUTO_REFRESH_TICK_THRESHOLD = 3 + +async function lockNoOp(name: string, acquireTimeout: number, fn: () => Promise): Promise { + return await fn() +} + +export default class GoTrueClient { + private static nextInstanceID = 0 + + private instanceID: number + + /** + * Namespace for the GoTrue admin methods. + * These methods should only be used in a trusted server-side environment. + */ + admin: GoTrueAdminApi + /** + * Namespace for the MFA methods. + */ + mfa: GoTrueMFAApi + /** + * The storage key used to identify the values saved in localStorage + */ + protected storageKey: string + + /** + * The session object for the currently logged in user. If null, it means there isn't a logged-in user. + * Only used if persistSession is false. + */ + protected inMemorySession: Session | null + + protected flowType: AuthFlowType + + protected autoRefreshToken: boolean + protected persistSession: boolean + protected storage: SupportedStorage + protected stateChangeEmitters: Map = new Map() + protected autoRefreshTicker: ReturnType | null = null + protected visibilityChangedCallback: (() => Promise) | null = null + protected refreshingDeferred: Deferred | null = null + /** + * Keeps track of the async client initialization. + * When null or not yet resolved the auth state is `unknown` + * Once resolved the the auth state is known and it's save to call any further client methods. + * Keep extra care to never reject or throw uncaught errors + */ + protected initializePromise: Promise | null = null + protected detectSessionInUrl = true + protected url: string + protected headers: { + [key: string]: string + } + protected fetch: Fetch + protected lock: LockFunc + + /** + * Used to broadcast state change events to other tabs listening. + */ + protected broadcastChannel: BroadcastChannel | null = null + + protected logDebugMessages: boolean + + /** + * Create a new client for use in the browser. + */ + constructor(options: GoTrueClientOptions) { + this.instanceID = GoTrueClient.nextInstanceID + GoTrueClient.nextInstanceID += 1 + + if (this.instanceID > 0 && isBrowser()) { + console.warn( + 'Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.' + ) + } + + const settings = { ...DEFAULT_OPTIONS, ...options } + this.logDebugMessages = settings.debug + this.inMemorySession = null + this.storageKey = settings.storageKey + this.autoRefreshToken = settings.autoRefreshToken + this.persistSession = settings.persistSession + this.storage = settings.storage || localStorageAdapter + this.admin = new GoTrueAdminApi({ + url: settings.url, + headers: settings.headers, + fetch: settings.fetch, + }) + + this.url = settings.url + this.headers = settings.headers + this.fetch = resolveFetch(settings.fetch) + this.lock = settings.lock || lockNoOp + this.detectSessionInUrl = settings.detectSessionInUrl + this.flowType = settings.flowType + + this.mfa = { + verify: this._verify.bind(this), + enroll: this._enroll.bind(this), + unenroll: this._unenroll.bind(this), + challenge: this._challenge.bind(this), + listFactors: this._listFactors.bind(this), + challengeAndVerify: this._challengeAndVerify.bind(this), + getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this), + } + + if (this.persistSession && this.storage === localStorageAdapter && !supportsLocalStorage()) { + console.warn( + `No storage option exists to persist the session, which may result in unexpected behavior when using auth. + If you want to set persistSession to true, please provide a storage option or you may set persistSession to false to disable this warning.` + ) + } + + if (isBrowser() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) { + try { + this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey) + } catch (e: any) { + console.error( + 'Failed to create a new BroadcastChannel, multi-tab state changes will not be available', + e + ) + } + + this.broadcastChannel?.addEventListener('message', async (event) => { + this._debug('received broadcast notification from other tab or client', event) + + await this._notifyAllSubscribers(event.data.event, event.data.session, false) // broadcast = false so we don't get an endless loop of messages + }) + } + + this.initialize() + } + + private _debug(...args: any[]): GoTrueClient { + if (this.logDebugMessages) { + console.log( + `GoTrueClient@${this.instanceID} (${version}) ${new Date().toISOString()}`, + ...args + ) + } + + return this + } + + /** + * Initializes the client session either from the url or from storage. + * This method is automatically called when instantiating the client, but should also be called + * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). + */ + initialize(): Promise { + if (this.initializePromise) { + return this.initializePromise + } + + return this._initialize() + } + + /** + * IMPORTANT: + * 1. Never throw in this method, as it is called from the constructor + * 2. Never return a session from this method as it would be cached over + * the whole lifetime of the client + */ + private async _initialize(): Promise { + if (this.initializePromise) { + throw new Error('Double call of #_initialize()') + } + + this.initializePromise = this._acquireLock( + -1, + async () => + await stackGuard('_initialize', async () => { + try { + const isPKCEFlow = isBrowser() ? await this._isPKCEFlow() : false + this._debug('#_initialize()', 'begin', 'is PKCE flow', isPKCEFlow) + + if (isPKCEFlow || (this.detectSessionInUrl && this._isImplicitGrantFlow())) { + const { data, error } = await this._getSessionFromURL(isPKCEFlow) + if (error) { + this._debug('#_initialize()', 'error detecting session from URL', error) + + // failed login attempt via url, + // remove old session as in verifyOtp, signUp and signInWith* + await this._removeSession() + + return { error } + } + + const { session, redirectType } = data + + this._debug( + '#_initialize()', + 'detected session in URL', + session, + 'redirect type', + redirectType + ) + + await this._saveSession(session) + + setTimeout(async () => { + if (redirectType === 'recovery') { + await this._notifyAllSubscribers('PASSWORD_RECOVERY', session) + } else { + await this._notifyAllSubscribers('SIGNED_IN', session) + } + }, 0) + + return { error: null } + } + // no login attempt via callback url try to recover session from storage + await this._recoverAndRefresh() + return { error: null } + } catch (error) { + if (isAuthError(error)) { + return { error } + } + + return { + error: new AuthUnknownError('Unexpected error during initialization', error), + } + } finally { + await this._handleVisibilityChange() + this._debug('#_initialize()', 'end') + } + }) + ) + + return await this.initializePromise + } + + /** + * Creates a new user. + * + * Be aware that if a user account exists in the system you may get back an + * error message that attempts to hide this information from the user. + * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. + * + * @returns A logged-in session if the server has "autoconfirm" ON + * @returns A user if the server has "autoconfirm" OFF + */ + async signUp(credentials: SignUpWithPasswordCredentials): Promise { + try { + await this._removeSession() + + let res: AuthResponse + if ('email' in credentials) { + const { email, password, options } = credentials + let codeChallenge: string | null = null + let codeChallengeMethod: string | null = null + if (this.flowType === 'pkce') { + const codeVerifier = generatePKCEVerifier() + await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier) + codeChallenge = await generatePKCEChallenge(codeVerifier) + codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256' + } + res = await _request(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + redirectTo: options?.emailRedirectTo, + body: { + email, + password, + data: options?.data ?? {}, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + xform: _sessionResponse, + }) + } else if ('phone' in credentials) { + const { phone, password, options } = credentials + res = await _request(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + body: { + phone, + password, + data: options?.data ?? {}, + channel: options?.channel ?? 'sms', + gotrue_meta_security: { captcha_token: options?.captchaToken }, + }, + xform: _sessionResponse, + }) + } else { + throw new AuthInvalidCredentialsError( + 'You must provide either an email or phone number and a password' + ) + } + + const { data, error } = res + + if (error || !data) { + return { data: { user: null, session: null }, error: error } + } + + const session: Session | null = data.session + const user: User | null = data.user + + if (data.session) { + await this._saveSession(data.session) + await this._notifyAllSubscribers('SIGNED_IN', session) + } + + return { data: { user, session }, error: null } + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error } + } + + throw error + } + } + + /** + * Log in an existing user with an email and password or phone and password. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or that the + * email/phone and password combination is wrong or that the account can only + * be accessed via social login. + */ + async signInWithPassword(credentials: SignInWithPasswordCredentials): Promise { + try { + await this._removeSession() + + let res: AuthResponse + if ('email' in credentials) { + const { email, password, options } = credentials + res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + email, + password, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + }, + xform: _sessionResponse, + }) + } else if ('phone' in credentials) { + const { phone, password, options } = credentials + res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + phone, + password, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + }, + xform: _sessionResponse, + }) + } else { + throw new AuthInvalidCredentialsError( + 'You must provide either an email or phone number and a password' + ) + } + const { data, error } = res + + if (error) { + return { data: { user: null, session: null }, error } + } else if (!data || !data.session || !data.user) { + return { data: { user: null, session: null }, error: new AuthInvalidTokenResponseError() } + } + if (data.session) { + await this._saveSession(data.session) + await this._notifyAllSubscribers('SIGNED_IN', data.session) + } + return { data: { user: data.user, session: data.session }, error } + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error } + } + throw error + } + } + + /** + * Log in an existing user via a third-party provider. + * This method supports the PKCE flow. + */ + async signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise { + await this._removeSession() + + return await this._handleProviderSignIn(credentials.provider, { + redirectTo: credentials.options?.redirectTo, + scopes: credentials.options?.scopes, + queryParams: credentials.options?.queryParams, + skipBrowserRedirect: credentials.options?.skipBrowserRedirect, + }) + } + + /** + * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. + */ + async exchangeCodeForSession(authCode: string): Promise { + const codeVerifier = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`) + const { data, error } = await _request( + this.fetch, + 'POST', + `${this.url}/token?grant_type=pkce`, + { + headers: this.headers, + body: { + auth_code: authCode, + code_verifier: codeVerifier, + }, + xform: _sessionResponse, + } + ) + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`) + if (error) { + return { data: { user: null, session: null }, error } + } else if (!data || !data.session || !data.user) { + return { data: { user: null, session: null }, error: new AuthInvalidTokenResponseError() } + } + if (data.session) { + await this._saveSession(data.session) + await this._notifyAllSubscribers('SIGNED_IN', data.session) + } + return { data, error } + } + + /** + * Allows signing in with an OIDC ID token. The authentication provider used + * should be enabled and configured. + */ + async signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise { + await this._removeSession() + + try { + const { options, provider, token, access_token, nonce } = credentials + + const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + body: { + provider, + id_token: token, + access_token, + nonce, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + }, + xform: _sessionResponse, + }) + + const { data, error } = res + if (error) { + return { data: { user: null, session: null }, error } + } else if (!data || !data.session || !data.user) { + return { + data: { user: null, session: null }, + error: new AuthInvalidTokenResponseError(), + } + } + if (data.session) { + await this._saveSession(data.session) + await this._notifyAllSubscribers('SIGNED_IN', data.session) + } + return { data, error } + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error } + } + throw error + } + } + + /** + * Log in a user using magiclink or a one-time password (OTP). + * + * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. + * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. + * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or, that the account + * can only be accessed via social login. + * + * Do note that you will need to configure a Whatsapp sender on Twilio + * if you are using phone sign in with the 'whatsapp' channel. The whatsapp + * channel is not supported on other providers + * at this time. + * This method supports PKCE when an email is passed. + */ + async signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise { + try { + await this._removeSession() + + if ('email' in credentials) { + const { email, options } = credentials + let codeChallenge: string | null = null + let codeChallengeMethod: string | null = null + if (this.flowType === 'pkce') { + const codeVerifier = generatePKCEVerifier() + await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier) + codeChallenge = await generatePKCEChallenge(codeVerifier) + codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256' + } + const { error } = await _request(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + email, + data: options?.data ?? {}, + create_user: options?.shouldCreateUser ?? true, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + redirectTo: options?.emailRedirectTo, + }) + return { data: { user: null, session: null }, error } + } + if ('phone' in credentials) { + const { phone, options } = credentials + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + phone, + data: options?.data ?? {}, + create_user: options?.shouldCreateUser ?? true, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + channel: options?.channel ?? 'sms', + }, + }) + return { data: { user: null, session: null, messageId: data?.message_id }, error } + } + throw new AuthInvalidCredentialsError('You must provide either an email or phone number.') + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error } + } + + throw error + } + } + + /** + * Log in a user given a User supplied OTP received via mobile. + */ + async verifyOtp(params: VerifyOtpParams): Promise { + try { + if (params.type !== 'email_change' && params.type !== 'phone_change') { + // we don't want to remove the authenticated session if the user is performing an email_change or phone_change verification + await this._removeSession() + } + + let redirectTo = undefined + let captchaToken = undefined + if ('options' in params) { + redirectTo = params.options?.redirectTo + captchaToken = params.options?.captchaToken + } + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/verify`, { + headers: this.headers, + body: { + ...params, + gotrue_meta_security: { captcha_token: captchaToken }, + }, + redirectTo, + xform: _sessionResponse, + }) + + if (error) { + throw error + } + + if (!data) { + throw new Error('An error occurred on token verification.') + } + + const session: Session | null = data.session + const user: User = data.user + + if (session?.access_token) { + await this._saveSession(session as Session) + await this._notifyAllSubscribers('SIGNED_IN', session) + } + + return { data: { user, session }, error: null } + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error } + } + + throw error + } + } + + /** + * Attempts a single-sign on using an enterprise Identity Provider. A + * successful SSO attempt will redirect the current page to the identity + * provider authorization page. The redirect URL is implementation and SSO + * protocol specific. + * + * You can use it by providing a SSO domain. Typically you can extract this + * domain by asking users for their email address. If this domain is + * registered on the Auth instance the redirect will use that organization's + * currently active SSO Identity Provider for the login. + * + * If you have built an organization-specific login page, you can use the + * organization's SSO Identity Provider UUID directly instead. + */ + async signInWithSSO(params: SignInWithSSO): Promise { + try { + await this._removeSession() + + return await _request(this.fetch, 'POST', `${this.url}/sso`, { + body: { + ...('providerId' in params ? { provider_id: params.providerId } : null), + ...('domain' in params ? { domain: params.domain } : null), + redirect_to: params.options?.redirectTo ?? undefined, + ...(params?.options?.captchaToken + ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } + : null), + skip_http_redirect: true, // fetch does not handle redirects + }, + headers: this.headers, + xform: _ssoResponse, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + throw error + } + } + + /** + * Sends a reauthentication OTP to the user's email or phone number. + * Requires the user to be signed-in. + */ + async reauthenticate(): Promise { + try { + return await this._useSession(async (result) => { + const { + data: { session }, + error: sessionError, + } = result + if (sessionError) throw sessionError + if (!session) throw new AuthSessionMissingError() + + const { error } = await _request(this.fetch, 'GET', `${this.url}/reauthenticate`, { + headers: this.headers, + jwt: session.access_token, + }) + return { data: { user: null, session: null }, error } + }) + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error } + } + throw error + } + } + + /** + * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. + */ + async resend(credentials: ResendParams): Promise { + try { + if (credentials.type != 'email_change' && credentials.type != 'phone_change') { + await this._removeSession() + } + + const endpoint = `${this.url}/resend` + if ('email' in credentials) { + const { email, type, options } = credentials + const { error } = await _request(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + email, + type, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + }, + redirectTo: options?.emailRedirectTo, + }) + return { data: { user: null, session: null }, error } + } else if ('phone' in credentials) { + const { phone, type, options } = credentials + const { data, error } = await _request(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + phone, + type, + gotrue_meta_security: { captcha_token: options?.captchaToken }, + }, + }) + return { data: { user: null, session: null, messageId: data?.message_id }, error } + } + throw new AuthInvalidCredentialsError( + 'You must provide either an email or phone number and a type' + ) + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error } + } + throw error + } + } + + /** + * Returns the session, refreshing it if necessary. + * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. + */ + async getSession() { + return this._useSession(async (result) => { + return result + }) + } + + /** + * Acquires a global lock based on the storage key. + */ + private async _acquireLock(acquireTimeout: number, fn: () => Promise): Promise { + this._debug('#_acquireLock', 'begin', acquireTimeout) + + try { + if (!(await stackGuardsSupported())) { + this._debug( + '#_acquireLock', + 'Stack guards not supported, so exclusive locking is not performed as it can lead to deadlocks if the lock is attempted to be recursively acquired (as the recursion cannot be detected).' + ) + + return await fn() + } + + if (isInStackGuard('_acquireLock')) { + this._debug('#_acquireLock', 'recursive call') + return await fn() + } + + return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => { + this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey) + + try { + return await stackGuard('_acquireLock', async () => { + return await fn() + }) + } finally { + this._debug('#_acquireLock', 'lock released for storage key', this.storageKey) + } + }) + } finally { + this._debug('#_acquireLock', 'end') + } + } + + /** + * Use instead of {@link #getSession} inside the library. It is + * semantically usually what you want, as getting a session involves some + * processing afterwards that requires only one client operating on the + * session at once across multiple tabs or processes. + */ + private async _useSession( + fn: ( + result: + | { + data: { + session: Session + } + error: null + } + | { + data: { + session: null + } + error: AuthError + } + | { + data: { + session: null + } + error: null + } + ) => Promise + ): Promise { + this._debug('#_useSession', 'begin') + + try { + if (isInStackGuard('_useSession')) { + this._debug('#_useSession', 'recursive call') + + // the use of __loadSession here is the only correct use of the function! + const result = await this.__loadSession() + + return await fn(result) + } + + return await this._acquireLock(-1, async () => { + return await stackGuard('_useSession', async () => { + // the use of __loadSession here is the only correct use of the function! + const result = await this.__loadSession() + + return await fn(result) + }) + }) + } finally { + this._debug('#_useSession', 'end') + } + } + + /** + * NEVER USE DIRECTLY! + * + * Always use {@link #_useSession}. + */ + private async __loadSession(): Promise< + | { + data: { + session: Session + } + error: null + } + | { + data: { + session: null + } + error: AuthError + } + | { + data: { + session: null + } + error: null + } + > { + this._debug('#__loadSession()', 'begin') + + if (this.logDebugMessages && !isInStackGuard('_useSession') && (await stackGuardsSupported())) { + throw new Error('Please use #_useSession()') + } + + if (isInStackGuard('_initialize')) { + this._debug('#__loadSession', '#_initialize recursion detected', new Error().stack) + } + + // always wait for #_initialize() to finish before loading anything from + // storage + await this.initializePromise + + try { + let currentSession: Session | null = null + + if (this.persistSession) { + const maybeSession = await getItemAsync(this.storage, this.storageKey) + + this._debug('#getSession()', 'session from storage', maybeSession) + + if (maybeSession !== null) { + if (this._isValidSession(maybeSession)) { + currentSession = maybeSession + } else { + this._debug('#getSession()', 'session from storage is not valid') + await this._removeSession() + } + } + } else { + currentSession = this.inMemorySession + this._debug('#getSession()', 'session from memory', currentSession) + } + + if (!currentSession) { + return { data: { session: null }, error: null } + } + + const hasExpired = currentSession.expires_at + ? currentSession.expires_at <= Date.now() / 1000 + : false + + this._debug( + '#__loadSession()', + `session has${hasExpired ? '' : ' not'} expired`, + 'expires_at', + currentSession.expires_at + ) + + if (!hasExpired) { + return { data: { session: currentSession }, error: null } + } + + const { session, error } = await this._callRefreshToken(currentSession.refresh_token) + if (error) { + return { data: { session: null }, error } + } + + return { data: { session }, error: null } + } finally { + this._debug('#__loadSession()', 'end') + } + } + + /** + * Gets the current user details if there is an existing session. + * @param jwt Takes in an optional access token jwt. If no jwt is provided, getUser() will attempt to get the jwt from the current session. + */ + async getUser(jwt?: string): Promise { + try { + if (jwt) { + return await _request(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: jwt, + xform: _userResponse, + }) + } + + return await this._useSession(async (result) => { + const { data, error } = result + if (error) { + throw error + } + + return await _request(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: data.session?.access_token ?? undefined, + xform: _userResponse, + }) + }) + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error } + } + + throw error + } + } + + /** + * Updates user data for a logged in user. + */ + async updateUser( + attributes: UserAttributes, + options: { + emailRedirectTo?: string | undefined + } = {} + ): Promise { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result + if (sessionError) { + throw sessionError + } + if (!sessionData.session) { + throw new AuthSessionMissingError() + } + const session: Session = sessionData.session + const { data, error: userError } = await _request(this.fetch, 'PUT', `${this.url}/user`, { + headers: this.headers, + redirectTo: options?.emailRedirectTo, + body: attributes, + jwt: session.access_token, + xform: _userResponse, + }) + if (userError) throw userError + session.user = data.user as User + await this._saveSession(session) + await this._notifyAllSubscribers('USER_UPDATED', session) + + return { data: { user: session.user }, error: null } + }) + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null }, error } + } + + throw error + } + } + + /** + * Decodes a JWT (without performing any validation). + */ + private _decodeJWT(jwt: string): { + exp?: number + aal?: AuthenticatorAssuranceLevels | null + amr?: AMREntry[] | null + } { + return decodeJWTPayload(jwt) + } + + /** + * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. + * If the refresh token or access token in the current session is invalid, an error will be thrown. + * @param currentSession The current session that minimally contains an access token and refresh token. + */ + async setSession(currentSession: { + access_token: string + refresh_token: string + }): Promise { + try { + if (!currentSession.access_token || !currentSession.refresh_token) { + throw new AuthSessionMissingError() + } + + const timeNow = Date.now() / 1000 + let expiresAt = timeNow + let hasExpired = true + let session: Session | null = null + const payload = decodeJWTPayload(currentSession.access_token) + if (payload.exp) { + expiresAt = payload.exp + hasExpired = expiresAt <= timeNow + } + + if (hasExpired) { + const { session: refreshedSession, error } = await this._callRefreshToken( + currentSession.refresh_token + ) + if (error) { + return { data: { user: null, session: null }, error: error } + } + + if (!refreshedSession) { + return { data: { user: null, session: null }, error: null } + } + session = refreshedSession + } else { + const { data, error } = await this.getUser(currentSession.access_token) + if (error) { + throw error + } + session = { + access_token: currentSession.access_token, + refresh_token: currentSession.refresh_token, + user: data.user, + token_type: 'bearer', + expires_in: expiresAt - timeNow, + expires_at: expiresAt, + } + await this._saveSession(session) + await this._notifyAllSubscribers('SIGNED_IN', session) + } + + return { data: { user: session.user, session }, error: null } + } catch (error) { + if (isAuthError(error)) { + return { data: { session: null, user: null }, error } + } + + throw error + } + } + + /** + * Returns a new session, regardless of expiry status. + * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). + * If the current session's refresh token is invalid, an error will be thrown. + * @param currentSession The current session. If passed in, it must contain a refresh token. + */ + async refreshSession(currentSession?: { refresh_token: string }): Promise { + try { + return await this._useSession(async (result) => { + if (!currentSession) { + const { data, error } = result + if (error) { + throw error + } + + currentSession = data.session ?? undefined + } + + if (!currentSession?.refresh_token) { + throw new AuthSessionMissingError() + } + + const { session, error } = await this._callRefreshToken(currentSession.refresh_token) + if (error) { + return { data: { user: null, session: null }, error: error } + } + + if (!session) { + return { data: { user: null, session: null }, error: null } + } + + return { data: { user: session.user, session }, error: null } + }) + } catch (error) { + if (isAuthError(error)) { + return { data: { user: null, session: null }, error } + } + + throw error + } + } + + /** + * Gets the session data from a URL string + */ + private async _getSessionFromURL(isPKCEFlow: boolean): Promise< + | { + data: { session: Session; redirectType: string | null } + error: null + } + | { data: { session: null; redirectType: null }; error: AuthError } + > { + try { + if (!isBrowser()) throw new AuthImplicitGrantRedirectError('No browser detected.') + if (this.flowType === 'implicit' && !this._isImplicitGrantFlow()) { + throw new AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.') + } else if (this.flowType == 'pkce' && !isPKCEFlow) { + throw new AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.') + } + + const params = parseParametersFromURL(window.location.href) + + if (isPKCEFlow) { + if (!params.code) throw new AuthPKCEGrantCodeExchangeError('No code detected.') + const { data, error } = await this.exchangeCodeForSession(params.code) + if (error) throw error + + const url = new URL(window.location.href) + url.searchParams.delete('code') + + window.history.replaceState(window.history.state, '', url.toString()) + + return { data: { session: data.session, redirectType: null }, error: null } + } + + if (params.error || params.error_description || params.error_code) { + throw new AuthImplicitGrantRedirectError( + params.error_description || 'Error in URL with unspecified error_description', + { + error: params.error || 'unspecified_error', + code: params.error_code || 'unspecified_code', + } + ) + } + + const { + provider_token, + provider_refresh_token, + access_token, + refresh_token, + expires_in, + token_type, + } = params + + if (!access_token || !expires_in || !refresh_token || !token_type) { + throw new AuthImplicitGrantRedirectError('No session defined in URL') + } + + const timeNow = Math.round(Date.now() / 1000) + const expiresIn = parseInt(expires_in) + const expires_at = timeNow + expiresIn + + const { data, error } = await this.getUser(access_token) + if (error) throw error + + const session: Session = { + provider_token, + provider_refresh_token, + access_token, + expires_in: expiresIn, + expires_at, + refresh_token, + token_type, + user: data.user!!, + } + + // Remove tokens from URL + window.location.hash = '' + this._debug('#_getSessionFromURL()', 'clearing window.location.hash') + + return { data: { session, redirectType: params.type }, error: null } + } catch (error) { + if (isAuthError(error)) { + return { data: { session: null, redirectType: null }, error } + } + + throw error + } + } + + /** + * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) + */ + private _isImplicitGrantFlow(): boolean { + const params = parseParametersFromURL(window.location.href) + + return !!(isBrowser() && (params.access_token || params.error_description)) + } + /** + * Checks if the current URL and backing storage contain parameters given by a PKCE flow + */ + private async _isPKCEFlow(): Promise { + const params = parseParametersFromURL(window.location.href) + + const currentStorageContent = await getItemAsync( + this.storage, + `${this.storageKey}-code-verifier` + ) + + return !!(params.code && currentStorageContent) + } + + /** + * Inside a browser context, `signOut()` will remove the logged in user from the browser session + * and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. + * + * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. + * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. + * + * If using others scope, no `SIGNED_OUT` event is fired! + */ + async signOut({ scope }: SignOut = { scope: 'global' }): Promise<{ error: AuthError | null }> { + return await this._useSession(async (result) => { + const { data, error: sessionError } = result + if (sessionError) { + return { error: sessionError } + } + const accessToken = data.session?.access_token + if (accessToken) { + const { error } = await this.admin.signOut(accessToken, scope) + if (error) { + // ignore 404s since user might not exist anymore + // ignore 401s since an invalid or expired JWT should sign out the current session + if (!(isAuthApiError(error) && (error.status === 404 || error.status === 401))) { + return { error } + } + } + } + if (scope !== 'others') { + await this._removeSession() + await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`) + await this._notifyAllSubscribers('SIGNED_OUT', null) + } + return { error: null } + }) + } + + /** + * Receive a notification every time an auth event happens. + * @param callback A callback function to be invoked when an auth event happens. + */ + onAuthStateChange( + callback: (event: AuthChangeEvent, session: Session | null) => void | Promise + ): { + data: { subscription: Subscription } + } { + const id: string = uuid() + const subscription: Subscription = { + id, + callback, + unsubscribe: () => { + this._debug('#unsubscribe()', 'state change callback with id removed', id) + + this.stateChangeEmitters.delete(id) + }, + } + + this._debug('#onAuthStateChange()', 'registered callback with id', id) + + this.stateChangeEmitters.set(id, subscription) + + this._emitInitialSession(id) + + return { data: { subscription } } + } + + private async _emitInitialSession(id: string): Promise { + return await this._useSession(async (result) => { + try { + const { + data: { session }, + error, + } = result + if (error) throw error + + await this.stateChangeEmitters.get(id)?.callback('INITIAL_SESSION', session) + this._debug('INITIAL_SESSION', 'callback id', id, 'session', session) + } catch (err) { + await this.stateChangeEmitters.get(id)?.callback('INITIAL_SESSION', null) + this._debug('INITIAL_SESSION', 'callback id', id, 'error', err) + console.error(err) + } + }) + } + + /** + * Sends a password reset request to an email address. + * This method supports the PKCE flow. + * @param email The email address of the user. + * @param options.redirectTo The URL to send the user to after they click the password reset link. + * @param options.captchaToken Verification token received when the user completes the captcha on the site. + */ + async resetPasswordForEmail( + email: string, + options: { + redirectTo?: string + captchaToken?: string + } = {} + ): Promise< + | { + data: {} + error: null + } + | { data: null; error: AuthError } + > { + let codeChallenge: string | null = null + let codeChallengeMethod: string | null = null + if (this.flowType === 'pkce') { + const codeVerifier = generatePKCEVerifier() + await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier) + codeChallenge = await generatePKCEChallenge(codeVerifier) + codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256' + } + try { + return await _request(this.fetch, 'POST', `${this.url}/recover`, { + body: { + email, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + gotrue_meta_security: { captcha_token: options.captchaToken }, + }, + headers: this.headers, + redirectTo: options.redirectTo, + }) + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Generates a new JWT. + * @param refreshToken A valid refresh token that was returned on login. + */ + private async _refreshAccessToken(refreshToken: string): Promise { + const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)` + this._debug(debugName, 'begin') + + try { + const startedAt = Date.now() + + // will attempt to refresh the token with exponential backoff + return await retryable( + async (attempt) => { + await sleep(attempt * 200) // 0, 200, 400, 800, ... + + this._debug(debugName, 'refreshing attempt', attempt) + + return await _request(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, { + body: { refresh_token: refreshToken }, + headers: this.headers, + xform: _sessionResponse, + }) + }, + (attempt, _, result) => + result && + result.error && + isAuthRetryableFetchError(result.error) && + // retryable only if the request can be sent before the backoff overflows the tick duration + Date.now() + (attempt + 1) * 200 - startedAt < AUTO_REFRESH_TICK_DURATION + ) + } catch (error) { + this._debug(debugName, 'error', error) + + if (isAuthError(error)) { + return { data: { session: null, user: null }, error } + } + throw error + } finally { + this._debug(debugName, 'end') + } + } + + private _isValidSession(maybeSession: unknown): maybeSession is Session { + const isValidSession = + typeof maybeSession === 'object' && + maybeSession !== null && + 'access_token' in maybeSession && + 'refresh_token' in maybeSession && + 'expires_at' in maybeSession + + return isValidSession + } + + private async _handleProviderSignIn( + provider: Provider, + options: { + redirectTo?: string + scopes?: string + queryParams?: { [key: string]: string } + skipBrowserRedirect?: boolean + } + ) { + const url: string = await this._getUrlForProvider(provider, { + redirectTo: options.redirectTo, + scopes: options.scopes, + queryParams: options.queryParams, + }) + + this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url) + + // try to open on the browser + if (isBrowser() && !options.skipBrowserRedirect) { + window.location.assign(url) + } + + return { data: { provider, url }, error: null } + } + + /** + * Recovers the session from LocalStorage and refreshes + * Note: this method is async to accommodate for AsyncStorage e.g. in React native. + */ + private async _recoverAndRefresh() { + const debugName = '#_recoverAndRefresh()' + this._debug(debugName, 'begin') + + try { + const currentSession = await getItemAsync(this.storage, this.storageKey) + this._debug(debugName, 'session from storage', currentSession) + + if (!this._isValidSession(currentSession)) { + this._debug(debugName, 'session is not valid') + if (currentSession !== null) { + await this._removeSession() + } + + return + } + + const timeNow = Math.round(Date.now() / 1000) + const expiresWithMargin = (currentSession.expires_at ?? Infinity) < timeNow + EXPIRY_MARGIN + + this._debug( + debugName, + `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${EXPIRY_MARGIN}s` + ) + + if (expiresWithMargin) { + if (this.autoRefreshToken && currentSession.refresh_token) { + const { error } = await this._callRefreshToken(currentSession.refresh_token) + + if (error) { + console.error(error) + + if (!isAuthRetryableFetchError(error)) { + this._debug( + debugName, + 'refresh failed with a non-retryable error, removing the session', + error + ) + await this._removeSession() + } + } + } + } else { + // no need to persist currentSession again, as we just loaded it from + // local storage; persisting it again may overwrite a value saved by + // another client with access to the same local storage + await this._notifyAllSubscribers('SIGNED_IN', currentSession) + } + } catch (err) { + this._debug(debugName, 'error', err) + + console.error(err) + return + } finally { + this._debug(debugName, 'end') + } + } + + private async _callRefreshToken(refreshToken: string): Promise { + if (!refreshToken) { + throw new AuthSessionMissingError() + } + + // refreshing is already in progress + if (this.refreshingDeferred) { + return this.refreshingDeferred.promise + } + + const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)` + + this._debug(debugName, 'begin') + + try { + this.refreshingDeferred = new Deferred() + + const { data, error } = await this._refreshAccessToken(refreshToken) + if (error) throw error + if (!data.session) throw new AuthSessionMissingError() + + await this._saveSession(data.session) + await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session) + + const result = { session: data.session, error: null } + + this.refreshingDeferred.resolve(result) + + return result + } catch (error) { + this._debug(debugName, 'error', error) + + if (isAuthError(error)) { + const result = { session: null, error } + + this.refreshingDeferred?.resolve(result) + + return result + } + + this.refreshingDeferred?.reject(error) + throw error + } finally { + this.refreshingDeferred = null + this._debug(debugName, 'end') + } + } + + private async _notifyAllSubscribers( + event: AuthChangeEvent, + session: Session | null, + broadcast = true + ) { + const debugName = `#_notifyAllSubscribers(${event})` + this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`) + + try { + if (this.broadcastChannel && broadcast) { + this.broadcastChannel.postMessage({ event, session }) + } + + const errors: any[] = [] + const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => { + try { + await x.callback(event, session) + } catch (e: any) { + errors.push(e) + } + }) + + await Promise.all(promises) + + if (errors.length > 0) { + for (let i = 0; i < errors.length; i += 1) { + console.error(errors[i]) + } + + throw errors[0] + } + } finally { + this._debug(debugName, 'end') + } + } + + /** + * set currentSession and currentUser + * process to _startAutoRefreshToken if possible + */ + private async _saveSession(session: Session) { + this._debug('#_saveSession()', session) + + if (!this.persistSession) { + this.inMemorySession = session + } + + if (this.persistSession && session.expires_at) { + await this._persistSession(session) + } + } + + private _persistSession(currentSession: Session) { + this._debug('#_persistSession()', currentSession) + + return setItemAsync(this.storage, this.storageKey, currentSession) + } + + private async _removeSession() { + this._debug('#_removeSession()') + + if (this.persistSession) { + await removeItemAsync(this.storage, this.storageKey) + } else { + this.inMemorySession = null + } + } + + /** + * Removes any registered visibilitychange callback. + * + * {@see #startAutoRefresh} + * {@see #stopAutoRefresh} + */ + private _removeVisibilityChangedCallback() { + this._debug('#_removeVisibilityChangedCallback()') + + const callback = this.visibilityChangedCallback + this.visibilityChangedCallback = null + + try { + if (callback && isBrowser() && window?.removeEventListener) { + window.removeEventListener('visibilitychange', callback) + } + } catch (e) { + console.error('removing visibilitychange callback failed', e) + } + } + + /** + * This is the private implementation of {@link #startAutoRefresh}. Use this + * within the library. + */ + private async _startAutoRefresh() { + await this._stopAutoRefresh() + + this._debug('#_startAutoRefresh()') + + const ticker = setInterval(() => this._autoRefreshTokenTick(), AUTO_REFRESH_TICK_DURATION) + this.autoRefreshTicker = ticker + + if (ticker && typeof ticker === 'object' && typeof ticker.unref === 'function') { + // ticker is a NodeJS Timeout object that has an `unref` method + // https://nodejs.org/api/timers.html#timeoutunref + // When auto refresh is used in NodeJS (like for testing) the + // `setInterval` is preventing the process from being marked as + // finished and tests run endlessly. This can be prevented by calling + // `unref()` on the returned object. + ticker.unref() + // @ts-ignore + } else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') { + // similar like for NodeJS, but with the Deno API + // https://deno.land/api@latest?unstable&s=Deno.unrefTimer + // @ts-ignore + Deno.unrefTimer(ticker) + } + + // run the tick immediately, but in the next pass of the event loop so that + // #_initialize can be allowed to complete without recursively waiting on + // itself + setTimeout(async () => { + await this.initializePromise + await this._autoRefreshTokenTick() + }, 0) + } + + /** + * This is the private implementation of {@link #stopAutoRefresh}. Use this + * within the library. + */ + private async _stopAutoRefresh() { + this._debug('#_stopAutoRefresh()') + + const ticker = this.autoRefreshTicker + this.autoRefreshTicker = null + + if (ticker) { + clearInterval(ticker) + } + } + + /** + * Starts an auto-refresh process in the background. The session is checked + * every few seconds. Close to the time of expiration a process is started to + * refresh the session. If refreshing fails it will be retried for as long as + * necessary. + * + * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need + * to call this function, it will be called for you. + * + * On browsers the refresh process works only when the tab/window is in the + * foreground to conserve resources as well as prevent race conditions and + * flooding auth with requests. If you call this method any managed + * visibility change callback will be removed and you must manage visibility + * changes on your own. + * + * On non-browser platforms the refresh process works *continuously* in the + * background, which may not be desirable. You should hook into your + * platform's foreground indication mechanism and call these methods + * appropriately to conserve resources. + * + * {@see #stopAutoRefresh} + */ + async startAutoRefresh() { + this._removeVisibilityChangedCallback() + await this._startAutoRefresh() + } + + /** + * Stops an active auto refresh process running in the background (if any). + * + * If you call this method any managed visibility change callback will be + * removed and you must manage visibility changes on your own. + * + * See {@link #startAutoRefresh} for more details. + */ + async stopAutoRefresh() { + this._removeVisibilityChangedCallback() + await this._stopAutoRefresh() + } + + /** + * Runs the auto refresh token tick. + */ + private async _autoRefreshTokenTick() { + this._debug('#_autoRefreshTokenTick()', 'begin') + + try { + const now = Date.now() + + try { + return await this._useSession(async (result) => { + const { + data: { session }, + } = result + + if (!session || !session.refresh_token || !session.expires_at) { + this._debug('#_autoRefreshTokenTick()', 'no session') + return + } + + // session will expire in this many ticks (or has already expired if <= 0) + const expiresInTicks = Math.floor( + (session.expires_at * 1000 - now) / AUTO_REFRESH_TICK_DURATION + ) + + this._debug( + '#_autoRefreshTokenTick()', + `access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks` + ) + + if (expiresInTicks <= AUTO_REFRESH_TICK_THRESHOLD) { + await this._callRefreshToken(session.refresh_token) + } + }) + } catch (e: any) { + console.error('Auto refresh tick failed with error. This is likely a transient error.', e) + } + } finally { + this._debug('#_autoRefreshTokenTick()', 'end') + } + } + + /** + * Registers callbacks on the browser / platform, which in-turn run + * algorithms when the browser window/tab are in foreground. On non-browser + * platforms it assumes always foreground. + */ + private async _handleVisibilityChange() { + this._debug('#_handleVisibilityChange()') + + if (!isBrowser() || !window?.addEventListener) { + if (this.autoRefreshToken) { + // in non-browser environments the refresh token ticker runs always + this.startAutoRefresh() + } + + return false + } + + try { + this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false) + + window?.addEventListener('visibilitychange', this.visibilityChangedCallback) + + // now immediately call the visbility changed callback to setup with the + // current visbility state + await this._onVisibilityChanged(true) // initial call + } catch (error) { + console.error('_handleVisibilityChange', error) + } + } + + /** + * Callback registered with `window.addEventListener('visibilitychange')`. + */ + private async _onVisibilityChanged(isInitial: boolean) { + this._debug(`#_onVisibilityChanged(${isInitial})`, 'visibilityState', document.visibilityState) + + if (document.visibilityState === 'visible') { + // to avoid recursively depending on #_initialize(), run the visibility + // changed callback in the next event loop tick + setTimeout(async () => { + if (!isInitial) { + // initial visibility change setup is handled in another flow under #initialize() + await this.initializePromise + await this._recoverAndRefresh() + + this._debug( + '#_onVisibilityChanged()', + 'finished waiting for initialize, _recoverAndRefresh' + ) + } + + if (this.autoRefreshToken) { + // in browser environments the refresh token ticker runs only on focused tabs + // which prevents race conditions + this._startAutoRefresh() + } + }, 0) + } else if (document.visibilityState === 'hidden') { + if (this.autoRefreshToken) { + this._stopAutoRefresh() + } + } + } + + /** + * Generates the relevant login URL for a third-party provider. + * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. + * @param options.scopes A space-separated list of scopes granted to the OAuth application. + * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. + */ + private async _getUrlForProvider( + provider: Provider, + options: { + redirectTo?: string + scopes?: string + queryParams?: { [key: string]: string } + } + ) { + const urlParams: string[] = [`provider=${encodeURIComponent(provider)}`] + if (options?.redirectTo) { + urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`) + } + if (options?.scopes) { + urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`) + } + if (this.flowType === 'pkce') { + const codeVerifier = generatePKCEVerifier() + await setItemAsync(this.storage, `${this.storageKey}-code-verifier`, codeVerifier) + const codeChallenge = await generatePKCEChallenge(codeVerifier) + const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256' + + this._debug( + 'PKCE', + 'code verifier', + `${codeVerifier.substring(0, 5)}...`, + 'code challenge', + codeChallenge, + 'method', + codeChallengeMethod + ) + + const flowParams = new URLSearchParams({ + code_challenge: `${encodeURIComponent(codeChallenge)}`, + code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`, + }) + urlParams.push(flowParams.toString()) + } + if (options?.queryParams) { + const query = new URLSearchParams(options.queryParams) + urlParams.push(query.toString()) + } + + return `${this.url}/authorize?${urlParams.join('&')}` + } + + private async _unenroll(params: MFAUnenrollParams): Promise { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result + if (sessionError) { + return { data: null, error: sessionError } + } + + return await _request(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, { + headers: this.headers, + jwt: sessionData?.session?.access_token, + }) + }) + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + throw error + } + } + + /** + * {@see GoTrueMFAApi#enroll} + */ + private async _enroll(params: MFAEnrollParams): Promise { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result + if (sessionError) { + return { data: null, error: sessionError } + } + + const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors`, { + body: { + friendly_name: params.friendlyName, + factor_type: params.factorType, + issuer: params.issuer, + }, + headers: this.headers, + jwt: sessionData?.session?.access_token, + }) + + if (error) { + return { data: null, error } + } + + if (data?.totp?.qr_code) { + data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}` + } + + return { data, error: null } + }) + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + throw error + } + } + + /** + * {@see GoTrueMFAApi#verify} + */ + private async _verify(params: MFAVerifyParams): Promise { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result + if (sessionError) { + return { data: null, error: sessionError } + } + + const { data, error } = await _request( + this.fetch, + 'POST', + `${this.url}/factors/${params.factorId}/verify`, + { + body: { code: params.code, challenge_id: params.challengeId }, + headers: this.headers, + jwt: sessionData?.session?.access_token, + } + ) + if (error) { + return { data: null, error } + } + + await this._saveSession({ + expires_at: Math.round(Date.now() / 1000) + data.expires_in, + ...data, + }) + await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data) + + return { data, error } + }) + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + throw error + } + } + + /** + * {@see GoTrueMFAApi#challenge} + */ + private async _challenge(params: MFAChallengeParams): Promise { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result + if (sessionError) { + return { data: null, error: sessionError } + } + + return await _request( + this.fetch, + 'POST', + `${this.url}/factors/${params.factorId}/challenge`, + { + headers: this.headers, + jwt: sessionData?.session?.access_token, + } + ) + }) + } catch (error) { + if (isAuthError(error)) { + return { data: null, error } + } + throw error + } + } + + /** + * {@see GoTrueMFAApi#challengeAndVerify} + */ + private async _challengeAndVerify( + params: MFAChallengeAndVerifyParams + ): Promise { + const { data: challengeData, error: challengeError } = await this._challenge({ + factorId: params.factorId, + }) + if (challengeError) { + return { data: null, error: challengeError } + } + return await this._verify({ + factorId: params.factorId, + challengeId: challengeData.id, + code: params.code, + }) + } + + /** + * {@see GoTrueMFAApi#listFactors} + */ + private async _listFactors(): Promise { + const { + data: { user }, + error: userError, + } = await this.getUser() + if (userError) { + return { data: null, error: userError } + } + + const factors = user?.factors || [] + const totp = factors.filter( + (factor) => factor.factor_type === 'totp' && factor.status === 'verified' + ) + + return { + data: { + all: factors, + totp, + }, + error: null, + } + } + + /** + * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} + */ + private async _getAuthenticatorAssuranceLevel(): Promise { + return await this._useSession(async (result) => { + const { + data: { session }, + error: sessionError, + } = result + if (sessionError) { + return { data: null, error: sessionError } + } + if (!session) { + return { + data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] }, + error: null, + } + } + + const payload = this._decodeJWT(session.access_token) + + let currentLevel: AuthenticatorAssuranceLevels | null = null + + if (payload.aal) { + currentLevel = payload.aal + } + + let nextLevel: AuthenticatorAssuranceLevels | null = currentLevel + + const verifiedFactors = + session.user.factors?.filter((factor: Factor) => factor.status === 'verified') ?? [] + + if (verifiedFactors.length > 0) { + nextLevel = 'aal2' + } + + const currentAuthenticationMethods = payload.amr || [] + + return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null } + }) + } +} diff --git a/node_modules/@supabase/gotrue-js/src/index.ts b/node_modules/@supabase/gotrue-js/src/index.ts new file mode 100644 index 0000000..41bb187 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/src/index.ts @@ -0,0 +1,10 @@ +import GoTrueAdminApi from './GoTrueAdminApi' +import GoTrueClient from './GoTrueClient' +export { GoTrueAdminApi, GoTrueClient } +export * from './lib/types' +export * from './lib/errors' +export { + navigatorLock, + NavigatorLockAcquireTimeoutError, + internals as lockInternals, +} from './lib/locks' diff --git a/node_modules/@supabase/gotrue-js/src/lib/constants.ts b/node_modules/@supabase/gotrue-js/src/lib/constants.ts new file mode 100644 index 0000000..24fe663 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/src/lib/constants.ts @@ -0,0 +1,10 @@ +import { version } from './version' +export const GOTRUE_URL = 'http://localhost:9999' +export const STORAGE_KEY = 'supabase.auth.token' +export const AUDIENCE = '' +export const DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version}` } +export const EXPIRY_MARGIN = 10 // in seconds +export const NETWORK_FAILURE = { + MAX_RETRIES: 10, + RETRY_INTERVAL: 2, // in deciseconds +} diff --git a/node_modules/@supabase/gotrue-js/src/lib/errors.ts b/node_modules/@supabase/gotrue-js/src/lib/errors.ts new file mode 100644 index 0000000..7fe8561 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/src/lib/errors.ts @@ -0,0 +1,126 @@ +export class AuthError extends Error { + status: number | undefined + protected __isAuthError = true + + constructor(message: string, status?: number) { + super(message) + this.name = 'AuthError' + this.status = status + } +} + +export function isAuthError(error: unknown): error is AuthError { + return typeof error === 'object' && error !== null && '__isAuthError' in error +} + +export class AuthApiError extends AuthError { + status: number + + constructor(message: string, status: number) { + super(message, status) + this.name = 'AuthApiError' + this.status = status + } + + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + } + } +} + +export function isAuthApiError(error: unknown): error is AuthApiError { + return isAuthError(error) && error.name === 'AuthApiError' +} + +export class AuthUnknownError extends AuthError { + originalError: unknown + + constructor(message: string, originalError: unknown) { + super(message) + this.name = 'AuthUnknownError' + this.originalError = originalError + } +} + +export class CustomAuthError extends AuthError { + name: string + status: number + constructor(message: string, name: string, status: number) { + super(message) + this.name = name + this.status = status + } + + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + } + } +} + +export class AuthSessionMissingError extends CustomAuthError { + constructor() { + super('Auth session missing!', 'AuthSessionMissingError', 400) + } +} + +export class AuthInvalidTokenResponseError extends CustomAuthError { + constructor() { + super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500) + } +} + +export class AuthInvalidCredentialsError extends CustomAuthError { + constructor(message: string) { + super(message, 'AuthInvalidCredentialsError', 400) + } +} + +export class AuthImplicitGrantRedirectError extends CustomAuthError { + details: { error: string; code: string } | null = null + constructor(message: string, details: { error: string; code: string } | null = null) { + super(message, 'AuthImplicitGrantRedirectError', 500) + this.details = details + } + + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + } + } +} + +export class AuthPKCEGrantCodeExchangeError extends CustomAuthError { + details: { error: string; code: string } | null = null + constructor(message: string, details: { error: string; code: string } | null = null) { + super(message, 'AuthPKCEGrantCodeExchangeError', 500) + this.details = details + } + + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + } + } +} + +export class AuthRetryableFetchError extends CustomAuthError { + constructor(message: string, status: number) { + super(message, 'AuthRetryableFetchError', status) + } +} + +export function isAuthRetryableFetchError(error: unknown): error is AuthRetryableFetchError { + return isAuthError(error) && error.name === 'AuthRetryableFetchError' +} diff --git a/node_modules/@supabase/gotrue-js/src/lib/fetch.ts b/node_modules/@supabase/gotrue-js/src/lib/fetch.ts new file mode 100644 index 0000000..a443778 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/src/lib/fetch.ts @@ -0,0 +1,193 @@ +import { expiresAt, looksLikeFetchResponse } from './helpers' +import { + AuthResponse, + SSOResponse, + GenerateLinkProperties, + GenerateLinkResponse, + User, + UserResponse, +} from './types' +import { AuthApiError, AuthRetryableFetchError, AuthUnknownError } from './errors' + +export type Fetch = typeof fetch + +export interface FetchOptions { + headers?: { + [key: string]: string + } + noResolveJson?: boolean +} + +export interface FetchParameters { + signal?: AbortSignal +} + +export type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'DELETE' + +const _getErrorMessage = (err: any): string => + err.msg || err.message || err.error_description || err.error || JSON.stringify(err) + +const NETWORK_ERROR_CODES = [502, 503, 504] + +async function handleError(error: unknown) { + if (!looksLikeFetchResponse(error)) { + throw new AuthRetryableFetchError(_getErrorMessage(error), 0) + } + + if (NETWORK_ERROR_CODES.includes(error.status)) { + // status in 500...599 range - server had an error, request might be retryed. + throw new AuthRetryableFetchError(_getErrorMessage(error), error.status) + } + + let data: any + try { + data = await error.json() + } catch (e: any) { + throw new AuthUnknownError(_getErrorMessage(e), e) + } + + throw new AuthApiError(_getErrorMessage(data), error.status || 500) +} + +const _getRequestParams = ( + method: RequestMethodType, + options?: FetchOptions, + parameters?: FetchParameters, + body?: object +) => { + const params: { [k: string]: any } = { method, headers: options?.headers || {} } + + if (method === 'GET') { + return params + } + + params.headers = { 'Content-Type': 'application/json;charset=UTF-8', ...options?.headers } + params.body = JSON.stringify(body) + return { ...params, ...parameters } +} + +interface GotrueRequestOptions extends FetchOptions { + jwt?: string + redirectTo?: string + body?: object + query?: { [key: string]: string } + /** + * Function that transforms api response from gotrue into a desirable / standardised format + */ + xform?: (data: any) => any +} + +export async function _request( + fetcher: Fetch, + method: RequestMethodType, + url: string, + options?: GotrueRequestOptions +) { + const headers = { ...options?.headers } + if (options?.jwt) { + headers['Authorization'] = `Bearer ${options.jwt}` + } + const qs = options?.query ?? {} + if (options?.redirectTo) { + qs['redirect_to'] = options.redirectTo + } + const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : '' + const data = await _handleRequest( + fetcher, + method, + url + queryString, + { headers, noResolveJson: options?.noResolveJson }, + {}, + options?.body + ) + return options?.xform ? options?.xform(data) : { data: { ...data }, error: null } +} + +async function _handleRequest( + fetcher: Fetch, + method: RequestMethodType, + url: string, + options?: FetchOptions, + parameters?: FetchParameters, + body?: object +): Promise { + const requestParams = _getRequestParams(method, options, parameters, body) + + let result: any + + try { + result = await fetcher(url, requestParams) + } catch (e) { + console.error(e) + + // fetch failed, likely due to a network or CORS error + throw new AuthRetryableFetchError(_getErrorMessage(e), 0) + } + + if (!result.ok) { + await handleError(result) + } + + if (options?.noResolveJson) { + return result + } + + try { + return await result.json() + } catch (e: any) { + await handleError(e) + } +} + +export function _sessionResponse(data: any): AuthResponse { + let session = null + if (hasSession(data)) { + session = { ...data } + session.expires_at = expiresAt(data.expires_in) + } + const user: User = data.user ?? (data as User) + return { data: { session, user }, error: null } +} + +export function _userResponse(data: any): UserResponse { + const user: User = data.user ?? (data as User) + return { data: { user }, error: null } +} + +export function _ssoResponse(data: any): SSOResponse { + return { data, error: null } +} + +export function _generateLinkResponse(data: any): GenerateLinkResponse { + const { action_link, email_otp, hashed_token, redirect_to, verification_type, ...rest } = data + + const properties: GenerateLinkProperties = { + action_link, + email_otp, + hashed_token, + redirect_to, + verification_type, + } + + const user: User = { ...rest } + return { + data: { + properties, + user, + }, + error: null, + } +} + +export function _noResolveJsonResponse(data: any): Response { + return data +} + +/** + * hasSession checks if the response object contains a valid session + * @param data A response object + * @returns true if a session is in the response + */ +function hasSession(data: any): boolean { + return data.access_token && data.refresh_token && data.expires_in +} diff --git a/node_modules/@supabase/gotrue-js/src/lib/helpers.ts b/node_modules/@supabase/gotrue-js/src/lib/helpers.ts new file mode 100644 index 0000000..f826b35 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/src/lib/helpers.ts @@ -0,0 +1,440 @@ +import { SupportedStorage } from './types' +export function expiresAt(expiresIn: number) { + const timeNow = Math.round(Date.now() / 1000) + return timeNow + expiresIn +} + +export function uuid() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + const r = (Math.random() * 16) | 0, + v = c == 'x' ? r : (r & 0x3) | 0x8 + return v.toString(16) + }) +} + +export const isBrowser = () => typeof document !== 'undefined' + +const localStorageWriteTests = { + tested: false, + writable: false, +} + +/** + * Checks whether localStorage is supported on this browser. + */ +export const supportsLocalStorage = () => { + if (!isBrowser()) { + return false + } + + try { + if (typeof globalThis.localStorage !== 'object') { + return false + } + } catch (e) { + // DOM exception when accessing `localStorage` + return false + } + + if (localStorageWriteTests.tested) { + return localStorageWriteTests.writable + } + + const randomKey = `lswt-${Math.random()}${Math.random()}` + + try { + globalThis.localStorage.setItem(randomKey, randomKey) + globalThis.localStorage.removeItem(randomKey) + + localStorageWriteTests.tested = true + localStorageWriteTests.writable = true + } catch (e) { + // localStorage can't be written to + // https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document + + localStorageWriteTests.tested = true + localStorageWriteTests.writable = false + } + + return localStorageWriteTests.writable +} + +/** + * Extracts parameters encoded in the URL both in the query and fragment. + */ +export function parseParametersFromURL(href: string) { + const result: { [parameter: string]: string } = {} + + const url = new URL(href) + + if (url.hash && url.hash[0] === '#') { + try { + const hashSearchParams = new URLSearchParams(url.hash.substring(1)) + hashSearchParams.forEach((value, key) => { + result[key] = value + }) + } catch (e: any) { + // hash is not a query string + } + } + + // search parameters take precedence over hash parameters + url.searchParams.forEach((value, key) => { + result[key] = value + }) + + return result +} + +type Fetch = typeof fetch + +export const resolveFetch = (customFetch?: Fetch): Fetch => { + let _fetch: Fetch + if (customFetch) { + _fetch = customFetch + } else if (typeof fetch === 'undefined') { + _fetch = async (...args) => await (await import('cross-fetch')).fetch(...args) + } else { + _fetch = fetch + } + return (...args) => _fetch(...args) +} + +export const looksLikeFetchResponse = (maybeResponse: unknown): maybeResponse is Response => { + return ( + typeof maybeResponse === 'object' && + maybeResponse !== null && + 'status' in maybeResponse && + 'ok' in maybeResponse && + 'json' in maybeResponse && + typeof (maybeResponse as any).json === 'function' + ) +} + +// Storage helpers +export const setItemAsync = async ( + storage: SupportedStorage, + key: string, + data: any +): Promise => { + await storage.setItem(key, JSON.stringify(data)) +} + +export const getItemAsync = async (storage: SupportedStorage, key: string): Promise => { + const value = await storage.getItem(key) + + if (!value) { + return null + } + + try { + return JSON.parse(value) + } catch { + return value + } +} + +export const removeItemAsync = async (storage: SupportedStorage, key: string): Promise => { + await storage.removeItem(key) +} + +export function decodeBase64URL(value: string): string { + const key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' + let base64 = '' + let chr1, chr2, chr3 + let enc1, enc2, enc3, enc4 + let i = 0 + value = value.replace('-', '+').replace('_', '/') + + while (i < value.length) { + enc1 = key.indexOf(value.charAt(i++)) + enc2 = key.indexOf(value.charAt(i++)) + enc3 = key.indexOf(value.charAt(i++)) + enc4 = key.indexOf(value.charAt(i++)) + chr1 = (enc1 << 2) | (enc2 >> 4) + chr2 = ((enc2 & 15) << 4) | (enc3 >> 2) + chr3 = ((enc3 & 3) << 6) | enc4 + base64 = base64 + String.fromCharCode(chr1) + + if (enc3 != 64 && chr2 != 0) { + base64 = base64 + String.fromCharCode(chr2) + } + if (enc4 != 64 && chr3 != 0) { + base64 = base64 + String.fromCharCode(chr3) + } + } + return base64 +} + +/** + * A deferred represents some asynchronous work that is not yet finished, which + * may or may not culminate in a value. + * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts + */ +export class Deferred { + public static promiseConstructor: PromiseConstructor = Promise + + public readonly promise!: PromiseLike + + public readonly resolve!: (value?: T | PromiseLike) => void + + public readonly reject!: (reason?: any) => any + + public constructor() { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ;(this as any).promise = new Deferred.promiseConstructor((res, rej) => { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ;(this as any).resolve = res + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ;(this as any).reject = rej + }) + } +} + +// Taken from: https://stackoverflow.com/questions/38552003/how-to-decode-jwt-token-in-javascript-without-using-a-library +export function decodeJWTPayload(token: string) { + // Regex checks for base64url format + const base64UrlRegex = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i + + const parts = token.split('.') + + if (parts.length !== 3) { + throw new Error('JWT is not valid: not a JWT structure') + } + + if (!base64UrlRegex.test(parts[1])) { + throw new Error('JWT is not valid: payload is not in base64url format') + } + + const base64Url = parts[1] + return JSON.parse(decodeBase64URL(base64Url)) +} + +/** + * Creates a promise that resolves to null after some time. + */ +export async function sleep(time: number): Promise { + return await new Promise((accept) => { + setTimeout(() => accept(null), time) + }) +} + +/** + * Converts the provided async function into a retryable function. Each result + * or thrown error is sent to the isRetryable function which should return true + * if the function should run again. + */ +export function retryable( + fn: (attempt: number) => Promise, + isRetryable: (attempt: number, error: any | null, result?: T) => boolean +): Promise { + const promise = new Promise((accept, reject) => { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ;(async () => { + for (let attempt = 0; attempt < Infinity; attempt++) { + try { + const result = await fn(attempt) + + if (!isRetryable(attempt, null, result)) { + accept(result) + return + } + } catch (e: any) { + if (!isRetryable(attempt, e)) { + reject(e) + return + } + } + } + })() + }) + + return promise +} + +function dec2hex(dec: number) { + return ('0' + dec.toString(16)).substr(-2) +} + +// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs +export function generatePKCEVerifier() { + const verifierLength = 56 + const array = new Uint32Array(verifierLength) + if (typeof crypto === 'undefined') { + const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~' + const charSetLen = charSet.length + let verifier = '' + for (let i = 0; i < verifierLength; i++) { + verifier += charSet.charAt(Math.floor(Math.random() * charSetLen)) + } + return verifier + } + crypto.getRandomValues(array) + return Array.from(array, dec2hex).join('') +} + +async function sha256(randomString: string) { + const encoder = new TextEncoder() + const encodedData = encoder.encode(randomString) + const hash = await crypto.subtle.digest('SHA-256', encodedData) + const bytes = new Uint8Array(hash) + + return Array.from(bytes) + .map((c) => String.fromCharCode(c)) + .join('') +} + +function base64urlencode(str: string) { + return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') +} + +export async function generatePKCEChallenge(verifier: string) { + if (typeof crypto === 'undefined') { + console.warn( + 'WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.' + ) + return verifier + } + const hashed = await sha256(verifier) + return base64urlencode(hashed) +} + +const STACK_GUARD_PREFIX = `__stack_guard__` +const STACK_GUARD_SUFFIX = `__` + +// Firefox and WebKit based browsers encode the stack entry differently, but +// they all include the function name. So instead of trying to parse the entry, +// we're only looking for the special string `__stack_guard__${guardName}__`. +// Guard names can only be letters with dashes or underscores. +// +// Example Firefox stack trace: +// ``` +// __stack_guard__EXAMPLE__@debugger eval code:1:55 +// @debugger eval code:1:3 +// ``` +// +// Example WebKit/Chrome stack trace: +// ``` +// Error +// at Object.__stack_guard__EXAMPLE__ (:1:55) +// at :1:13 +// ``` +// +const STACK_ENTRY_REGEX = /__stack_guard__([a-zA-Z0-9_-]+)__/ + +let STACK_GUARD_CHECKED = false +let STACK_GUARD_CHECK_FN: () => Promise // eslint-disable-line prefer-const + +let STACK_GUARDS_SUPPORTED = false + +/** + * Checks if the current caller of the function is in a {@link + * #stackGuard} of the provided `name`. Works by looking through + * the stack trace of an `Error` object for a special function + * name (generated by {@link #stackGuard}). + * + * @param name The name of the stack guard to check for. Must be `[a-zA-Z0-9_-]` only. + */ +export function isInStackGuard(name: string): boolean { + STACK_GUARD_CHECK_FN() + + let error: Error + + try { + throw new Error() + } catch (e: any) { + error = e + } + + const stack = error.stack?.split('\n') ?? [] + + for (let i = 0; i < stack.length; i += 1) { + const entry = stack[i] + const match = entry.match(STACK_ENTRY_REGEX) + + if (match && match[1] === name) { + return true + } + } + + return false +} + +/** + * Creates a minification resistant stack guard, i.e. if you + * call {@link #isInStackGuard} from within the `fn` parameter + * function, you will always get `true` otherwise it will be + * `false`. + * + * Works by dynamically defining a function name before calling + * into `fn`, which is then parsed from the stack trace on an + * `Error` object within {@link #isInStackGuard}. + * + * @param name The name of the stack guard. Must be `[a-zA-Z0-9_-]` only. + * @param fn The async/await function to be run within the stack guard. + */ +export async function stackGuard(name: string, fn: () => Promise): Promise { + await STACK_GUARD_CHECK_FN() + + const guardName = `${STACK_GUARD_PREFIX}${name}${STACK_GUARD_SUFFIX}` + + const guardFunc: { + [funcName: string]: () => Promise + } = { + // per ECMAScript rules, this defines a new function with the dynamic name + // contained in the `guardName` variable + // this function name shows up in stack traces and is resistant to mangling + // from minification processes as it is determined at runtime + [guardName]: async () => await fn(), + } + + // Safari does not log the name of a dynamically named function unless you + // explicitly set the displayName + Object.assign(guardFunc[guardName], { displayName: guardName }) + + return await guardFunc[guardName]() +} + +/** + * Returns if the JavaScript engine supports stack guards. If it doesn't + * certain features that depend on detecting recursive calls should be disabled + * to prevent deadlocks. + */ +export async function stackGuardsSupported(): Promise { + if (STACK_GUARD_CHECKED) { + return STACK_GUARDS_SUPPORTED + } + + await STACK_GUARD_CHECK_FN() + + return STACK_GUARDS_SUPPORTED +} + +let STACK_GUARD_WARNING_LOGGED = false + +// In certain cases, if this file is transpiled using an ES2015 target, or is +// running in a JS engine that does not support async/await stack traces, this +// function will log a single warning message. +STACK_GUARD_CHECK_FN = async () => { + if (!STACK_GUARD_CHECKED) { + STACK_GUARD_CHECKED = true + + await stackGuard('ENV_CHECK', async () => { + // sleeping for the next tick as Safari loses track of the async/await + // trace beyond this point + await sleep(0) + + const result = isInStackGuard('ENV_CHECK') + STACK_GUARDS_SUPPORTED = result + + if (!result && !STACK_GUARD_WARNING_LOGGED) { + STACK_GUARD_WARNING_LOGGED = true + console.warn( + '@supabase/gotrue-js: Stack guards not supported in this environment. Generally not an issue but may point to a very conservative transpilation environment (use ES2017 or above) that implements async/await with generators, or this is a JavaScript engine that does not support async/await stack traces. Safari is known to not support stack guards.' + ) + } + + return result + }) + } +} diff --git a/node_modules/@supabase/gotrue-js/src/lib/local-storage.ts b/node_modules/@supabase/gotrue-js/src/lib/local-storage.ts new file mode 100644 index 0000000..ceea1ae --- /dev/null +++ b/node_modules/@supabase/gotrue-js/src/lib/local-storage.ts @@ -0,0 +1,28 @@ +import { supportsLocalStorage } from './helpers' +import { SupportedStorage } from './types' + +const localStorageAdapter: SupportedStorage = { + getItem: (key) => { + if (!supportsLocalStorage()) { + return null + } + + return globalThis.localStorage.getItem(key) + }, + setItem: (key, value) => { + if (!supportsLocalStorage()) { + return + } + + globalThis.localStorage.setItem(key, value) + }, + removeItem: (key) => { + if (!supportsLocalStorage()) { + return + } + + globalThis.localStorage.removeItem(key) + }, +} + +export default localStorageAdapter diff --git a/node_modules/@supabase/gotrue-js/src/lib/locks.ts b/node_modules/@supabase/gotrue-js/src/lib/locks.ts new file mode 100644 index 0000000..a169c49 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/src/lib/locks.ts @@ -0,0 +1,161 @@ +/** + * @experimental + */ +export const internals = { + /** + * @experimental + */ + debug: !!( + globalThis && + globalThis.localStorage && + globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true' + ), +} + +export class NavigatorLockAcquireTimeoutError extends Error { + public readonly isAcquireTimeout = true + + constructor(message: string) { + super(message) + } +} + +/** + * Implements a global exclusive lock using the Navigator LockManager API. It + * is available on all browsers released after 2022-03-15 with Safari being the + * last one to release support. If the API is not available, this function will + * throw. Make sure you check availablility before configuring {@link + * GoTrueClient}. + * + * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug` + * local storage item to `true`. + * + * Internals: + * + * Since the LockManager API does not preserve stack traces for the async + * function passed in the `request` method, a trick is used where acquiring the + * lock releases a previously started promise to run the operation in the `fn` + * function. The lock waits for that promise to finish (with or without error), + * while the function will finally wait for the result anyway. + * + * @experimental + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + */ +export async function navigatorLock( + name: string, + acquireTimeout: number, + fn: () => Promise +): Promise { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout) + } + + let beginOperation: (() => void) | null = null + let rejectOperation: ((error: any) => void) | null = null + const beginOperationPromise = new Promise((accept, reject) => { + beginOperation = accept + rejectOperation = reject + }) + + // this lets us preserve stack traces over the operation, which the + // navigator.locks.request function does not preserve well still + const result = (async () => { + await beginOperationPromise + + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: operation start') + } + + try { + return await fn() + } finally { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: operation end') + } + } + })() + + const abortController = new globalThis.AbortController() + + if (acquireTimeout > 0) { + setTimeout(() => { + beginOperation = null + abortController.abort() + + if (rejectOperation) { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name) + } + + if (rejectOperation) { + rejectOperation( + new NavigatorLockAcquireTimeoutError( + `Acquiring an exclusive Navigator LockManager lock "${name}" timed out after ${acquireTimeout}ms` + ) + ) + } + beginOperation = null + rejectOperation = null + } + }, acquireTimeout) + } + + await globalThis.navigator.locks.request( + name, + { + mode: 'exclusive', + ifAvailable: acquireTimeout === 0, + signal: abortController.signal, + }, + async (lock) => { + if (lock) { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock acquired', name) + } + + try { + if (beginOperation) { + beginOperation() + beginOperation = null + rejectOperation = null + await result + } + } catch (e: any) { + // not important to handle the error here + } finally { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock released', name) + } + } + } else { + if (internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock not immediately available', name) + } + + // no lock was available because acquireTimeout === 0 + const timeout: any = new Error( + `Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed` + ) + timeout.isAcquireTimeout = true + + if (rejectOperation) { + rejectOperation( + new NavigatorLockAcquireTimeoutError( + `Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed` + ) + ) + } + beginOperation = null + rejectOperation = null + } + } + ) + + return await result +} diff --git a/node_modules/@supabase/gotrue-js/src/lib/polyfills.ts b/node_modules/@supabase/gotrue-js/src/lib/polyfills.ts new file mode 100644 index 0000000..49aa2d8 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/src/lib/polyfills.ts @@ -0,0 +1,23 @@ +/** + * https://mathiasbynens.be/notes/globalthis + */ +export function polyfillGlobalThis() { + if (typeof globalThis === 'object') return + try { + Object.defineProperty(Object.prototype, '__magic__', { + get: function () { + return this + }, + configurable: true, + }) + // @ts-expect-error 'Allow access to magic' + __magic__.globalThis = __magic__ + // @ts-expect-error 'Allow access to magic' + delete Object.prototype.__magic__ + } catch (e) { + if (typeof self !== 'undefined') { + // @ts-expect-error 'Allow access to globals' + self.globalThis = self + } + } +} diff --git a/node_modules/@supabase/gotrue-js/src/lib/types.ts b/node_modules/@supabase/gotrue-js/src/lib/types.ts new file mode 100644 index 0000000..fe7a314 --- /dev/null +++ b/node_modules/@supabase/gotrue-js/src/lib/types.ts @@ -0,0 +1,1067 @@ +import { AuthError } from './errors' +import { Fetch } from './fetch' + +/** One of the providers supported by GoTrue. */ +export type Provider = + | 'apple' + | 'azure' + | 'bitbucket' + | 'discord' + | 'facebook' + | 'figma' + | 'github' + | 'gitlab' + | 'google' + | 'kakao' + | 'keycloak' + | 'linkedin' + | 'notion' + | 'slack' + | 'spotify' + | 'twitch' + | 'twitter' + | 'workos' + | 'zoom' + +export type AuthChangeEventMFA = 'MFA_CHALLENGE_VERIFIED' + +export type AuthChangeEvent = + | 'INITIAL_SESSION' + | 'PASSWORD_RECOVERY' + | 'SIGNED_IN' + | 'SIGNED_OUT' + | 'TOKEN_REFRESHED' + | 'USER_UPDATED' + | AuthChangeEventMFA + +/** + * Provide your own global lock implementation instead of the default + * implementation. The function should acquire a lock for the duration of the + * `fn` async function, such that no other client instances will be able to + * hold it at the same time. + * + * @experimental + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout should occur. If positive it + * should throw an Error with an `isAcquireTimeout` + * property set to true if the operation fails to be + * acquired after this much time (ms). + * @param fn The operation to execute when the lock is acquired. + */ +export type LockFunc = (name: string, acquireTimeout: number, fn: () => Promise) => Promise + +export type GoTrueClientOptions = { + /* The URL of the GoTrue server. */ + url?: string + /* Any additional headers to send to the GoTrue server. */ + headers?: { [key: string]: string } + /* Optional key name used for storing tokens in local storage. */ + storageKey?: string + /* Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. */ + detectSessionInUrl?: boolean + /* Set to "true" if you want to automatically refresh the token before expiring. */ + autoRefreshToken?: boolean + /* Set to "true" if you want to automatically save the user session into local storage. If set to false, session will just be saved in memory. */ + persistSession?: boolean + /* Provide your own local storage implementation to use instead of the browser's local storage. */ + storage?: SupportedStorage + /* A custom fetch implementation. */ + fetch?: Fetch + /* If set to 'pkce' PKCE flow. Defaults to the 'implicit' flow otherwise */ + flowType?: AuthFlowType + /* If debug messages are emitted. Can be used to inspect the behavior of the library. */ + debug?: boolean + /** + * Provide your own locking mechanism based on the environment. By default no locking is done at this time. + * + * @experimental + */ + lock?: LockFunc +} + +export type AuthResponse = + | { + data: { + user: User | null + session: Session | null + } + error: null + } + | { + data: { + user: null + session: null + } + error: AuthError + } + +/** + * AuthOtpResponse is returned when OTP is used. + * + * {@see AuthRsponse} + */ +export type AuthOtpResponse = + | { + data: { user: null; session: null; messageId?: string | null } + error: null + } + | { + data: { user: null; session: null; messageId?: string | null } + error: AuthError + } + +export type AuthTokenResponse = + | { + data: { + user: User + session: Session + } + error: null + } + | { + data: { + user: null + session: null + } + error: AuthError + } + +export type OAuthResponse = + | { + data: { + provider: Provider + url: string + } + error: null + } + | { + data: { + provider: Provider + url: null + } + error: AuthError + } + +export type SSOResponse = + | { + data: { + /** + * URL to open in a browser which will complete the sign-in flow by + * taking the user to the identity provider's authentication flow. + * + * On browsers you can set the URL to `window.location.href` to take + * the user to the authentication flow. + */ + url: string + } + error: null + } + | { + data: null + error: AuthError + } + +export type UserResponse = + | { + data: { + user: User + } + error: null + } + | { + data: { + user: null + } + error: AuthError + } + +export interface Session { + /** + * The oauth provider token. If present, this can be used to make external API requests to the oauth provider used. + */ + provider_token?: string | null + /** + * The oauth provider refresh token. If present, this can be used to refresh the provider_token via the oauth provider's API. + * Not all oauth providers return a provider refresh token. If the provider_refresh_token is missing, please refer to the oauth provider's documentation for information on how to obtain the provider refresh token. + */ + provider_refresh_token?: string | null + /** + * The access token jwt. It is recommended to set the JWT_EXPIRY to a shorter expiry value. + */ + access_token: string + /** + * A one-time used refresh token that never expires. + */ + refresh_token: string + /** + * The number of seconds until the token expires (since it was issued). Returned when a login is confirmed. + */ + expires_in: number + /** + * A timestamp of when the token will expire. Returned when a login is confirmed. + */ + expires_at?: number + token_type: string + user: User +} + +/** + * An authentication methord reference (AMR) entry. + * + * An entry designates what method was used by the user to verify their + * identity and at what time. + * + * @see {@link GoTrueMFAApi#getAuthenticatorAssuranceLevel}. + */ +export interface AMREntry { + /** Authentication method name. */ + method: 'password' | 'otp' | 'oauth' | 'mfa/totp' | string + + /** + * Timestamp when the method was successfully used. Represents number of + * seconds since 1st January 1970 (UNIX epoch) in UTC. + */ + timestamp: number +} + +export interface UserIdentity { + id: string + user_id: string + identity_data?: { + [key: string]: any + } + provider: string + created_at?: string + last_sign_in_at?: string + updated_at?: string +} + +/** + * A MFA factor. + * + * @see {@link GoTrueMFAApi#enroll} + * @see {@link GoTrueMFAApi#listFactors} + * @see {@link GoTrueMFAAdminApi#listFactors} + */ +export interface Factor { + /** ID of the factor. */ + id: string + + /** Friendly name of the factor, useful to disambiguate between multiple factors. */ + friendly_name?: string + + /** + * Type of factor. Only `totp` supported with this version but may change in + * future versions. + */ + factor_type: 'totp' | string + + /** Factor's status. */ + status: 'verified' | 'unverified' + + created_at: string + updated_at: string +} + +export interface UserAppMetadata { + provider?: string + [key: string]: any +} + +export interface UserMetadata { + [key: string]: any +} + +export interface User { + id: string + app_metadata: UserAppMetadata + user_metadata: UserMetadata + aud: string + confirmation_sent_at?: string + recovery_sent_at?: string + email_change_sent_at?: string + new_email?: string + new_phone?: string + invited_at?: string + action_link?: string + email?: string + phone?: string + created_at: string + confirmed_at?: string + email_confirmed_at?: string + phone_confirmed_at?: string + last_sign_in_at?: string + role?: string + updated_at?: string + identities?: UserIdentity[] + factors?: Factor[] +} + +export interface UserAttributes { + /** + * The user's email. + */ + email?: string + + /** + * The user's phone. + */ + phone?: string + + /** + * The user's password. + */ + password?: string + + /** + * The nonce sent for reauthentication if the user's password is to be updated. + * + * Call reauthenticate() to obtain the nonce first. + */ + nonce?: string + + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + * + */ + data?: object +} + +export interface AdminUserAttributes extends Omit { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * + * The `user_metadata` should be a JSON object that includes user-specific info, such as their first and last name. + * + * Note: When using the GoTrueAdminApi and wanting to modify a user's metadata, + * this attribute is used instead of UserAttributes data. + * + */ + user_metadata?: object + + /** + * A custom data object to store the user's application specific metadata. This maps to the `auth.users.app_metadata` column. + * + * Only a service role can modify. + * + * The `app_metadata` should be a JSON object that includes app-specific info, such as identity providers, roles, and other + * access control information. + */ + app_metadata?: object + + /** + * Confirms the user's email address if set to true. + * + * Only a service role can modify. + */ + email_confirm?: boolean + + /** + * Confirms the user's phone number if set to true. + * + * Only a service role can modify. + */ + phone_confirm?: boolean + + /** + * Determines how long a user is banned for. + * + * The format for the ban duration follows a strict sequence of decimal numbers with a unit suffix. + * Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". + * + * For example, some possible durations include: '300ms', '2h45m'. + * + * Setting the ban duration to 'none' lifts the ban on the user. + */ + ban_duration?: string | 'none' +} + +export interface Subscription { + /** + * The subscriber UUID. This will be set by the client. + */ + id: string + /** + * The function to call every time there is an event. eg: (eventName) => {} + */ + callback: (event: AuthChangeEvent, session: Session | null) => void + /** + * Call this to remove the listener. + */ + unsubscribe: () => void +} + +export interface UpdatableFactorAttributes { + friendlyName: string +} + +export type SignUpWithPasswordCredentials = + | { + /** The user's email address. */ + email: string + /** The user's password. */ + password: string + options?: { + /** The redirect url embedded in the email link */ + emailRedirectTo?: string + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + } + } + | { + /** The user's phone number. */ + phone: string + /** The user's password. */ + password: string + options?: { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object + /** Verification token received when the user completes the captcha on the site. Requires a configured WhatsApp sender on Twilio */ + captchaToken?: string + /** Messaging channel to use (e.g. whatsapp or sms) */ + channel?: 'sms' | 'whatsapp' + } + } +export type SignInWithPasswordCredentials = + | { + /** The user's email address. */ + email: string + /** The user's password. */ + password: string + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + } + } + | { + /** The user's phone number. */ + phone: string + /** The user's password. */ + password: string + options?: { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + } + } + +export type SignInWithPasswordlessCredentials = + | { + /** The user's email address. */ + email: string + options?: { + /** The redirect url embedded in the email link */ + emailRedirectTo?: string + /** If set to false, this method will not create a new user. Defaults to true. */ + shouldCreateUser?: boolean + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + } + } + | { + /** The user's phone number. */ + phone: string + options?: { + /** If set to false, this method will not create a new user. Defaults to true. */ + shouldCreateUser?: boolean + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + /** Messaging channel to use (e.g. whatsapp or sms) */ + channel?: 'sms' | 'whatsapp' + } + } + +export type AuthFlowType = 'implicit' | 'pkce' +export type SignInWithOAuthCredentials = { + /** One of the providers supported by GoTrue. */ + provider: Provider + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string + /** A space-separated list of scopes granted to the OAuth application. */ + scopes?: string + /** An object of query params */ + queryParams?: { [key: string]: string } + /** If set to true does not immediately redirect the current browser context to visit the OAuth authorization page for the provider. */ + skipBrowserRedirect?: boolean + } +} + +export type SignInWithIdTokenCredentials = { + /** Provider name or OIDC `iss` value identifying which provider should be used to verify the provided token. Supported names: `google`, `apple`, `azure`, `facebook`, `keycloak` (deprecated). */ + provider: 'google' | 'apple' | 'azure' | 'facebook' | string + /** OIDC ID token issued by the specified provider. The `iss` claim in the ID token must match the supplied provider. Some ID tokens contain an `at_hash` which require that you provide an `access_token` value to be accepted properly. If the token contains a `nonce` claim you must supply the nonce used to obtain the ID token. */ + token: string + /** If the ID token contains an `at_hash` claim, then the hash of this value is compared to the value in the ID token. */ + access_token?: string + /** If the ID token contains a `nonce` claim, then the hash of this value is compared to the value in the ID token. */ + nonce?: string + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + } +} + +export type VerifyOtpParams = VerifyMobileOtpParams | VerifyEmailOtpParams | VerifyTokenHashParams +export interface VerifyMobileOtpParams { + /** The user's phone number. */ + phone: string + /** The otp sent to the user's phone number. */ + token: string + /** The user's verification type. */ + type: MobileOtpType + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string + + /** + * Verification token received when the user completes the captcha on the site. + * + * @deprecated + */ + captchaToken?: string + } +} +export interface VerifyEmailOtpParams { + /** The user's email address. */ + email: string + /** The otp sent to the user's email address. */ + token: string + /** The user's verification type. */ + type: EmailOtpType + options?: { + /** A URL to send the user to after they are confirmed. */ + redirectTo?: string + + /** Verification token received when the user completes the captcha on the site. + * + * @deprecated + */ + captchaToken?: string + } +} + +export interface VerifyTokenHashParams { + /** The token hash used in an email link */ + token_hash: string + + /** The user's verification type. */ + type: EmailOtpType +} + +export type MobileOtpType = 'sms' | 'phone_change' +export type EmailOtpType = 'signup' | 'invite' | 'magiclink' | 'recovery' | 'email_change' | 'email' + +export type ResendParams = + | { + type: Extract + email: string + options?: { + /** A URL to send the user to after they have signed-in. */ + emailRedirectTo?: string + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + } + } + | { + type: Extract + phone: string + options?: { + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + } + } + +export type SignInWithSSO = + | { + /** UUID of the SSO provider to invoke single-sign on to. */ + providerId: string + + options?: { + /** A URL to send the user to after they have signed-in. */ + redirectTo?: string + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + } + } + | { + /** Domain name of the organization for which to invoke single-sign on. */ + domain: string + + options?: { + /** A URL to send the user to after they have signed-in. */ + redirectTo?: string + /** Verification token received when the user completes the captcha on the site. */ + captchaToken?: string + } + } + +export type GenerateSignupLinkParams = { + type: 'signup' + email: string + password: string + options?: Pick +} + +export type GenerateInviteOrMagiclinkParams = { + type: 'invite' | 'magiclink' + /** The user's email */ + email: string + options?: Pick +} + +export type GenerateRecoveryLinkParams = { + type: 'recovery' + /** The user's email */ + email: string + options?: Pick +} + +export type GenerateEmailChangeLinkParams = { + type: 'email_change_current' | 'email_change_new' + /** The user's email */ + email: string + /** + * The user's new email. Only required if type is 'email_change_current' or 'email_change_new'. + */ + newEmail: string + options?: Pick +} + +export interface GenerateLinkOptions { + /** + * A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column. + * + * The `data` should be a JSON object that includes user-specific info, such as their first and last name. + */ + data?: object + /** The URL which will be appended to the email link generated. */ + redirectTo?: string +} + +export type GenerateLinkParams = + | GenerateSignupLinkParams + | GenerateInviteOrMagiclinkParams + | GenerateRecoveryLinkParams + | GenerateEmailChangeLinkParams + +export type GenerateLinkResponse = + | { + data: { + properties: GenerateLinkProperties + user: User + } + error: null + } + | { + data: { + properties: null + user: null + } + error: AuthError + } + +/** The properties related to the email link generated */ +export type GenerateLinkProperties = { + /** + * The email link to send to the user. + * The action_link follows the following format: auth/v1/verify?type={verification_type}&token={hashed_token}&redirect_to={redirect_to} + * */ + action_link: string + /** + * The raw email OTP. + * You should send this in the email if you want your users to verify using an OTP instead of the action link. + * */ + email_otp: string + /** + * The hashed token appended to the action link. + * */ + hashed_token: string + /** The URL appended to the action link. */ + redirect_to: string + /** The verification type that the email link is associated to. */ + verification_type: GenerateLinkType +} + +export type GenerateLinkType = + | 'signup' + | 'invite' + | 'magiclink' + | 'recovery' + | 'email_change_current' + | 'email_change_new' + +export type MFAEnrollParams = { + /** The type of factor being enrolled. */ + factorType: 'totp' + /** Domain which the user is enrolled with. */ + issuer?: string + /** Human readable name assigned to the factor. */ + friendlyName?: string +} + +export type MFAUnenrollParams = { + /** ID of the factor being unenrolled. */ + factorId: string +} + +export type MFAVerifyParams = { + /** ID of the factor being verified. Returned in enroll(). */ + factorId: string + + /** ID of the challenge being verified. Returned in challenge(). */ + challengeId: string + + /** Verification code provided by the user. */ + code: string +} + +export type MFAChallengeParams = { + /** ID of the factor to be challenged. Returned in enroll(). */ + factorId: string +} + +export type MFAChallengeAndVerifyParams = { + /** ID of the factor being verified. Returned in enroll(). */ + factorId: string + /** Verification code provided by the user. */ + code: string +} + +export type AuthMFAVerifyResponse = + | { + data: { + /** New access token (JWT) after successful verification. */ + access_token: string + + /** Type of token, typically `Bearer`. */ + token_type: string + + /** Number of seconds in which the access token will expire. */ + expires_in: number + + /** Refresh token you can use to obtain new access tokens when expired. */ + refresh_token: string + + /** Updated user profile. */ + user: User + } + error: null + } + | { + data: null + error: AuthError + } + +export type AuthMFAEnrollResponse = + | { + data: { + /** ID of the factor that was just enrolled (in an unverified state). */ + id: string + + /** Type of MFA factor. Only `totp` supported for now. */ + type: 'totp' + + /** TOTP enrollment information. */ + totp: { + /** Contains a QR code encoding the authenticator URI. You can + * convert it to a URL by prepending `data:image/svg+xml;utf-8,` to + * the value. Avoid logging this value to the console. */ + qr_code: string + + /** The TOTP secret (also encoded in the QR code). Show this secret + * in a password-style field to the user, in case they are unable to + * scan the QR code. Avoid logging this value to the console. */ + secret: string + + /** The authenticator URI encoded within the QR code, should you need + * to use it. Avoid loggin this value to the console. */ + uri: string + } + } + error: null + } + | { + data: null + error: AuthError + } + +export type AuthMFAUnenrollResponse = + | { + data: { + /** ID of the factor that was successfully unenrolled. */ + id: string + } + error: null + } + | { data: null; error: AuthError } + +export type AuthMFAChallengeResponse = + | { + data: { + /** ID of the newly created challenge. */ + id: string + + /** Timestamp in UNIX seconds when this challenge will no longer be usable. */ + expires_at: number + } + error: null + } + | { data: null; error: AuthError } + +export type AuthMFAListFactorsResponse = + | { + data: { + /** All available factors (verified and unverified). */ + all: Factor[] + + /** Only verified TOTP factors. (A subset of `all`.) */ + totp: Factor[] + } + error: null + } + | { data: null; error: AuthError } + +export type AuthenticatorAssuranceLevels = 'aal1' | 'aal2' + +export type AuthMFAGetAuthenticatorAssuranceLevelResponse = + | { + data: { + /** Current AAL level of the session. */ + currentLevel: AuthenticatorAssuranceLevels | null + + /** + * Next possible AAL level for the session. If the next level is higher + * than the current one, the user should go through MFA. + * + * @see {@link GoTrueMFAApi#challenge} + */ + nextLevel: AuthenticatorAssuranceLevels | null + + /** + * A list of all authentication methods attached to this session. Use + * the information here to detect the last time a user verified a + * factor, for example if implementing a step-up scenario. + */ + currentAuthenticationMethods: AMREntry[] + } + error: null + } + | { data: null; error: AuthError } + +/** + * Contains the full multi-factor authentication API. + * + */ +export interface GoTrueMFAApi { + /** + * Starts the enrollment process for a new Multi-Factor Authentication (MFA) + * factor. This method creates a new `unverified` factor. + * To verify a factor, present the QR code or secret to the user and ask them to add it to their + * authenticator app. + * The user has to enter the code from their authenticator app to verify it. + * + * Upon verifying a factor, all other sessions are logged out and the current session's authenticator level is promoted to `aal2`. + * + */ + enroll(params: MFAEnrollParams): Promise + + /** + * Prepares a challenge used to verify that a user has access to a MFA + * factor. + */ + challenge(params: MFAChallengeParams): Promise + + /** + * Verifies a code against a challenge. The verification code is + * provided by the user by entering a code seen in their authenticator app. + */ + verify(params: MFAVerifyParams): Promise + + /** + * Unenroll removes a MFA factor. + * A user has to have an `aal2` authenticator level in order to unenroll a `verified` factor. + */ + unenroll(params: MFAUnenrollParams): Promise + + /** + * Helper method which creates a challenge and immediately uses the given code to verify against it thereafter. The verification code is + * provided by the user by entering a code seen in their authenticator app. + */ + challengeAndVerify(params: MFAChallengeAndVerifyParams): Promise + + /** + * Returns the list of MFA factors enabled for this user. + * + * @see {@link GoTrueMFAApi#enroll} + * @see {@link GoTrueMFAApi#getAuthenticatorAssuranceLevel} + * @see {@link GoTrueClient#getUser} + * + */ + listFactors(): Promise + + /** + * Returns the Authenticator Assurance Level (AAL) for the active session. + * + * - `aal1` (or `null`) means that the user's identity has been verified only + * with a conventional login (email+password, OTP, magic link, social login, + * etc.). + * - `aal2` means that the user's identity has been verified both with a conventional login and at least one MFA factor. + * + * Although this method returns a promise, it's fairly quick (microseconds) + * and rarely uses the network. You can use this to check whether the current + * user needs to be shown a screen to verify their MFA factors. + * + */ + getAuthenticatorAssuranceLevel(): Promise +} + +/** + * @expermental + */ +export type AuthMFAAdminDeleteFactorResponse = + | { + data: { + /** ID of the factor that was successfully deleted. */ + id: string + } + error: null + } + | { data: null; error: AuthError } + +/** + * @expermental + */ +export type AuthMFAAdminDeleteFactorParams = { + /** ID of the MFA factor to delete. */ + id: string + + /** ID of the user whose factor is being deleted. */ + userId: string +} + +/** + * @expermental + */ +export type AuthMFAAdminListFactorsResponse = + | { + data: { + /** All factors attached to the user. */ + factors: Factor[] + } + error: null + } + | { data: null; error: AuthError } + +/** + * @expermental + */ +export type AuthMFAAdminListFactorsParams = { + /** ID of the user. */ + userId: string +} + +/** + * Contains the full multi-factor authentication administration API. + * + * @expermental + */ +export interface GoTrueAdminMFAApi { + /** + * Lists all factors associated to a user. + * + */ + listFactors(params: AuthMFAAdminListFactorsParams): Promise + + /** + * Deletes a factor on a user. This will log the user out of all active + * sessions if the deleted factor was verified. + * + * @see {@link GoTrueMFAApi#unenroll} + * + * @expermental + */ + deleteFactor(params: AuthMFAAdminDeleteFactorParams): Promise +} + +type AnyFunction = (...args: any[]) => any +type MaybePromisify = T | Promise + +type PromisifyMethods = { + [K in keyof T]: T[K] extends AnyFunction + ? (...args: Parameters) => MaybePromisify> + : T[K] +} + +export type SupportedStorage = PromisifyMethods> + +export type InitializeResult = { error: AuthError | null } + +export type CallRefreshTokenResult = + | { + session: Session + error: null + } + | { + session: null + error: AuthError + } + +export type Pagination = { + [key: string]: any + nextPage: number | null + lastPage: number + total: number +} + +export type PageParams = { + /** The page number */ + page?: number + /** Number of items returned per page */ + perPage?: number +} + +export type SignOut = { + /** + * Determines which sessions should be + * logged out. Global means all + * sessions by this account. Local + * means only this session. Others + * means all other sessions except the + * current one. When using others, + * there is no sign-out event fired on + * the current session! + */ + scope?: 'global' | 'local' | 'others' +} diff --git a/node_modules/@supabase/gotrue-js/src/lib/version.ts b/node_modules/@supabase/gotrue-js/src/lib/version.ts new file mode 100644 index 0000000..e39540d --- /dev/null +++ b/node_modules/@supabase/gotrue-js/src/lib/version.ts @@ -0,0 +1,2 @@ +// Generated by genversion. +export const version = '2.46.1' diff --git a/node_modules/@supabase/postgrest-js/LICENSE b/node_modules/@supabase/postgrest-js/LICENSE new file mode 100644 index 0000000..ddeba6a --- /dev/null +++ b/node_modules/@supabase/postgrest-js/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Supabase + +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/@supabase/postgrest-js/README.md b/node_modules/@supabase/postgrest-js/README.md new file mode 100644 index 0000000..4b962dd --- /dev/null +++ b/node_modules/@supabase/postgrest-js/README.md @@ -0,0 +1,54 @@ +# `postgrest-js` + +[![Build](https://github.com/supabase/postgrest-js/workflows/CI/badge.svg)](https://github.com/supabase/postgrest-js/actions?query=branch%3Amaster) +[![Package](https://img.shields.io/npm/v/@supabase/postgrest-js)](https://www.npmjs.com/package/@supabase/postgrest-js) +[![License: MIT](https://img.shields.io/npm/l/@supabase/postgrest-js)](#license) + +Isomorphic JavaScript client for [PostgREST](https://postgrest.org). The goal of this library is to make an "ORM-like" restful interface. + +Full documentation can be found [here](https://supabase.github.io/postgrest-js/v2). + +### Quick start + +Install + +```bash +npm install @supabase/postgrest-js +``` + +Usage + +```js +import { PostgrestClient } from '@supabase/postgrest-js' + +const REST_URL = 'http://localhost:3000' +const postgrest = new PostgrestClient(REST_URL) +``` + +- select(): https://supabase.com/docs/reference/javascript/select +- insert(): https://supabase.com/docs/reference/javascript/insert +- update(): https://supabase.com/docs/reference/javascript/update +- delete(): https://supabase.com/docs/reference/javascript/delete + +#### Custom `fetch` implementation + +`postgrest-js` uses the [`cross-fetch`](https://www.npmjs.com/package/cross-fetch) library to make HTTP requests, but an alternative `fetch` implementation can be provided as an option. This is most useful in environments where `cross-fetch` is not compatible, for instance Cloudflare Workers: + +```js +import { PostgrestClient } from '@supabase/postgrest-js' + +const REST_URL = 'http://localhost:3000' +const postgrest = new PostgrestClient(REST_URL, { + fetch: (...args) => fetch(...args), +}) +``` + +## License + +This repo is licensed under MIT License. + +## Sponsors + +We are building the features of Firebase using enterprise-grade, open source products. We support existing communities wherever possible, and if the products don’t exist we build them and open source them ourselves. Thanks to these sponsors who are making the OSS ecosystem better for everyone. + +[![New Sponsor](https://user-images.githubusercontent.com/10214025/90518111-e74bbb00-e198-11ea-8f88-c9e3c1aa4b5b.png)](https://github.com/sponsors/supabase) diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestBuilder.d.ts b/node_modules/@supabase/postgrest-js/dist/main/PostgrestBuilder.d.ts new file mode 100644 index 0000000..e19cbb2 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestBuilder.d.ts @@ -0,0 +1,22 @@ +import type { Fetch, PostgrestSingleResponse } from './types'; +export default abstract class PostgrestBuilder implements PromiseLike> { + protected method: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE'; + protected url: URL; + protected headers: Record; + protected schema?: string; + protected body?: unknown; + protected shouldThrowOnError: boolean; + protected signal?: AbortSignal; + protected fetch: Fetch; + protected isMaybeSingle: boolean; + constructor(builder: PostgrestBuilder); + /** + * If there's an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + * + * {@link https://github.com/supabase/supabase-js/issues/92} + */ + throwOnError(): this; + then, TResult2 = never>(onfulfilled?: ((value: PostgrestSingleResponse) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): PromiseLike; +} +//# sourceMappingURL=PostgrestBuilder.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestBuilder.d.ts.map b/node_modules/@supabase/postgrest-js/dist/main/PostgrestBuilder.d.ts.map new file mode 100644 index 0000000..6528224 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestBuilder.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestBuilder.d.ts","sourceRoot":"","sources":["../../src/PostgrestBuilder.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,KAAK,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAA;AAE7D,MAAM,CAAC,OAAO,CAAC,QAAQ,OAAO,gBAAgB,CAAC,MAAM,CACnD,YAAW,WAAW,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC;IAEvD,SAAS,CAAC,MAAM,EAAE,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,QAAQ,CAAA;IAC9D,SAAS,CAAC,GAAG,EAAE,GAAG,CAAA;IAClB,SAAS,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IACzC,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;IACzB,SAAS,CAAC,IAAI,CAAC,EAAE,OAAO,CAAA;IACxB,SAAS,CAAC,kBAAkB,UAAQ;IACpC,SAAS,CAAC,MAAM,CAAC,EAAE,WAAW,CAAA;IAC9B,SAAS,CAAC,KAAK,EAAE,KAAK,CAAA;IACtB,SAAS,CAAC,aAAa,EAAE,OAAO,CAAA;gBAEpB,OAAO,EAAE,gBAAgB,CAAC,MAAM,CAAC;IAmB7C;;;;;OAKG;IACH,YAAY,IAAI,IAAI;IAKpB,IAAI,CAAC,QAAQ,GAAG,uBAAuB,CAAC,MAAM,CAAC,EAAE,QAAQ,GAAG,KAAK,EAC/D,WAAW,CAAC,EACR,CAAC,CAAC,KAAK,EAAE,uBAAuB,CAAC,MAAM,CAAC,KAAK,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC,GAC9E,SAAS,GACT,IAAI,EACR,UAAU,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,GAAG,KAAK,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC,GAAG,SAAS,GAAG,IAAI,GAClF,WAAW,CAAC,QAAQ,GAAG,QAAQ,CAAC;CAuIpC"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestBuilder.js b/node_modules/@supabase/postgrest-js/dist/main/PostgrestBuilder.js new file mode 100644 index 0000000..c976547 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestBuilder.js @@ -0,0 +1,176 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const cross_fetch_1 = __importDefault(require("cross-fetch")); +class PostgrestBuilder { + constructor(builder) { + this.shouldThrowOnError = false; + this.method = builder.method; + this.url = builder.url; + this.headers = builder.headers; + this.schema = builder.schema; + this.body = builder.body; + this.shouldThrowOnError = builder.shouldThrowOnError; + this.signal = builder.signal; + this.isMaybeSingle = builder.isMaybeSingle; + if (builder.fetch) { + this.fetch = builder.fetch; + } + else if (typeof fetch === 'undefined') { + this.fetch = cross_fetch_1.default; + } + else { + this.fetch = fetch; + } + } + /** + * If there's an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + * + * {@link https://github.com/supabase/supabase-js/issues/92} + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + then(onfulfilled, onrejected) { + // https://postgrest.org/en/stable/api.html#switching-schemas + if (this.schema === undefined) { + // skip + } + else if (['GET', 'HEAD'].includes(this.method)) { + this.headers['Accept-Profile'] = this.schema; + } + else { + this.headers['Content-Profile'] = this.schema; + } + if (this.method !== 'GET' && this.method !== 'HEAD') { + this.headers['Content-Type'] = 'application/json'; + } + // NOTE: Invoke w/o `this` to avoid illegal invocation error. + // https://github.com/supabase/postgrest-js/pull/247 + const _fetch = this.fetch; + let res = _fetch(this.url.toString(), { + method: this.method, + headers: this.headers, + body: JSON.stringify(this.body), + signal: this.signal, + }).then(async (res) => { + var _a, _b, _c; + let error = null; + let data = null; + let count = null; + let status = res.status; + let statusText = res.statusText; + if (res.ok) { + if (this.method !== 'HEAD') { + const body = await res.text(); + if (body === '') { + // Prefer: return=minimal + } + else if (this.headers['Accept'] === 'text/csv') { + data = body; + } + else if (this.headers['Accept'] && + this.headers['Accept'].includes('application/vnd.pgrst.plan+text')) { + data = body; + } + else { + data = JSON.parse(body); + } + } + const countHeader = (_a = this.headers['Prefer']) === null || _a === void 0 ? void 0 : _a.match(/count=(exact|planned|estimated)/); + const contentRange = (_b = res.headers.get('content-range')) === null || _b === void 0 ? void 0 : _b.split('/'); + if (countHeader && contentRange && contentRange.length > 1) { + count = parseInt(contentRange[1]); + } + // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 + // Issue persists e.g. for `.insert([...]).select().maybeSingle()` + if (this.isMaybeSingle && this.method === 'GET' && Array.isArray(data)) { + if (data.length > 1) { + error = { + // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553 + code: 'PGRST116', + details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`, + hint: null, + message: 'JSON object requested, multiple (or no) rows returned', + }; + data = null; + count = null; + status = 406; + statusText = 'Not Acceptable'; + } + else if (data.length === 1) { + data = data[0]; + } + else { + data = null; + } + } + } + else { + const body = await res.text(); + try { + error = JSON.parse(body); + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (Array.isArray(error) && res.status === 404) { + data = []; + error = null; + status = 200; + statusText = 'OK'; + } + } + catch (_d) { + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (res.status === 404 && body === '') { + status = 204; + statusText = 'No Content'; + } + else { + error = { + message: body, + }; + } + } + if (error && this.isMaybeSingle && ((_c = error === null || error === void 0 ? void 0 : error.details) === null || _c === void 0 ? void 0 : _c.includes('Results contain 0 rows'))) { + error = null; + status = 200; + statusText = 'OK'; + } + if (error && this.shouldThrowOnError) { + throw error; + } + } + const postgrestResponse = { + error, + data, + count, + status, + statusText, + }; + return postgrestResponse; + }); + if (!this.shouldThrowOnError) { + res = res.catch((fetchError) => { + var _a, _b, _c; + return ({ + error: { + message: `${(_a = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _a !== void 0 ? _a : 'FetchError'}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`, + details: `${(_b = fetchError === null || fetchError === void 0 ? void 0 : fetchError.stack) !== null && _b !== void 0 ? _b : ''}`, + hint: '', + code: `${(_c = fetchError === null || fetchError === void 0 ? void 0 : fetchError.code) !== null && _c !== void 0 ? _c : ''}`, + }, + data: null, + count: null, + status: 0, + statusText: '', + }); + }); + } + return res.then(onfulfilled, onrejected); + } +} +exports.default = PostgrestBuilder; +//# sourceMappingURL=PostgrestBuilder.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestBuilder.js.map b/node_modules/@supabase/postgrest-js/dist/main/PostgrestBuilder.js.map new file mode 100644 index 0000000..082c981 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestBuilder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestBuilder.js","sourceRoot":"","sources":["../../src/PostgrestBuilder.ts"],"names":[],"mappings":";;;;;AAAA,8DAAoC;AAIpC,MAA8B,gBAAgB;IAa5C,YAAY,OAAiC;QALnC,uBAAkB,GAAG,KAAK,CAAA;QAMlC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAA;QAC5B,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAA;QACtB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAA;QAC9B,IAAI,CAAC,MAAM,G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BAAV,UAAU,CAAE,IAAI,mCAAI,EAAE,EAAE;qBAClC;oBACD,IAAI,EAAE,IAAI;oBACV,KAAK,EAAE,IAAI;oBACX,MAAM,EAAE,CAAC;oBACT,UAAU,EAAE,EAAE;iBACf,CAAC,CAAA;aAAA,CAAC,CAAA;SACJ;QAED,OAAO,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,UAAU,CAAC,CAAA;IAC1C,CAAC;CACF;AAxLD,mCAwLC"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestClient.d.ts b/node_modules/@supabase/postgrest-js/dist/main/PostgrestClient.d.ts new file mode 100644 index 0000000..bc2e06d --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestClient.d.ts @@ -0,0 +1,62 @@ +import PostgrestQueryBuilder from './PostgrestQueryBuilder'; +import PostgrestFilterBuilder from './PostgrestFilterBuilder'; +import { Fetch, GenericSchema } from './types'; +/** + * PostgREST client. + * + * @typeParam Database - Types for the schema from the [type + * generator](https://supabase.com/docs/reference/javascript/next/typescript-support) + * + * @typeParam SchemaName - Postgres schema to switch to. Must be a string + * literal, the same one passed to the constructor. If the schema is not + * `"public"`, this must be supplied manually. + */ +export default class PostgrestClient { + url: string; + headers: Record; + schema?: SchemaName; + fetch?: Fetch; + /** + * Creates a PostgREST client. + * + * @param url - URL of the PostgREST endpoint + * @param options - Named parameters + * @param options.headers - Custom headers + * @param options.schema - Postgres schema to switch to + * @param options.fetch - Custom fetch + */ + constructor(url: string, { headers, schema, fetch, }?: { + headers?: Record; + schema?: SchemaName; + fetch?: Fetch; + }); + from(relation: TableName): PostgrestQueryBuilder; + from(relation: ViewName): PostgrestQueryBuilder; + from(relation: string): PostgrestQueryBuilder; + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn: FunctionName, args?: Function_['Args'], { head, count, }?: { + head?: boolean; + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder ? Function_['Returns'][number] : never : never, Function_['Returns']>; +} +//# sourceMappingURL=PostgrestClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestClient.d.ts.map b/node_modules/@supabase/postgrest-js/dist/main/PostgrestClient.d.ts.map new file mode 100644 index 0000000..5a12fdd --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestClient.d.ts","sourceRoot":"","sources":["../../src/PostgrestClient.ts"],"names":[],"mappings":"AAAA,OAAO,qBAAqB,MAAM,yBAAyB,CAAA;AAC3D,OAAO,sBAAsB,MAAM,0BAA0B,CAAA;AAG7D,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAE9C;;;;;;;;;GASG;AACH,MAAM,CAAC,OAAO,OAAO,eAAe,CAClC,QAAQ,GAAG,GAAG,EACd,UAAU,SAAS,MAAM,GAAG,MAAM,QAAQ,GAAG,QAAQ,SAAS,MAAM,QAAQ,GACxE,QAAQ,GACR,MAAM,GAAG,MAAM,QAAQ,EAC3B,MAAM,SAAS,aAAa,GAAG,QAAQ,CAAC,UAAU,CAAC,SAAS,aAAa,GACrE,QAAQ,CAAC,UAAU,CAAC,GACpB,GAAG;IAEP,GAAG,EAAE,MAAM,CAAA;IACX,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC/B,MAAM,CAAC,EAAE,UAAU,CAAA;IACnB,KAAK,CAAC,E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AAM,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC1D,SAAS,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,GAC5B,KAAK,GACP,KAAK,EACT,SAAS,CAAC,SAAS,CAAC,CACrB;CA6BF"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestClient.js b/node_modules/@supabase/postgrest-js/dist/main/PostgrestClient.js new file mode 100644 index 0000000..b385b62 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestClient.js @@ -0,0 +1,100 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const PostgrestQueryBuilder_1 = __importDefault(require("./PostgrestQueryBuilder")); +const PostgrestFilterBuilder_1 = __importDefault(require("./PostgrestFilterBuilder")); +const constants_1 = require("./constants"); +/** + * PostgREST client. + * + * @typeParam Database - Types for the schema from the [type + * generator](https://supabase.com/docs/reference/javascript/next/typescript-support) + * + * @typeParam SchemaName - Postgres schema to switch to. Must be a string + * literal, the same one passed to the constructor. If the schema is not + * `"public"`, this must be supplied manually. + */ +class PostgrestClient { + // TODO: Add back shouldThrowOnError once we figure out the typings + /** + * Creates a PostgREST client. + * + * @param url - URL of the PostgREST endpoint + * @param options - Named parameters + * @param options.headers - Custom headers + * @param options.schema - Postgres schema to switch to + * @param options.fetch - Custom fetch + */ + constructor(url, { headers = {}, schema, fetch, } = {}) { + this.url = url; + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.schema = schema; + this.fetch = fetch; + } + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + const url = new URL(`${this.url}/${relation}`); + return new PostgrestQueryBuilder_1.default(url, { + headers: Object.assign({}, this.headers), + schema: this.schema, + fetch: this.fetch, + }); + } + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn, args = {}, { head = false, count, } = {}) { + let method; + const url = new URL(`${this.url}/rpc/${fn}`); + let body; + if (head) { + method = 'HEAD'; + Object.entries(args).forEach(([name, value]) => { + url.searchParams.append(name, `${value}`); + }); + } + else { + method = 'POST'; + body = args; + } + const headers = Object.assign({}, this.headers); + if (count) { + headers['Prefer'] = `count=${count}`; + } + return new PostgrestFilterBuilder_1.default({ + method, + url, + headers, + schema: this.schema, + body, + fetch: this.fetch, + allowEmpty: false, + }); + } +} +exports.default = PostgrestClient; +//# sourceMappingURL=PostgrestClient.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestClient.js.map b/node_modules/@supabase/postgrest-js/dist/main/PostgrestClient.js.map new file mode 100644 index 0000000..64f3c16 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestClient.js","sourceRoot":"","sources":["../../src/PostgrestClient.ts"],"names":[],"mappings":";;;;;AAAA,oFAA2D;AAC3D,sFAA6D;AAE7D,2CAA6C;AAG7C;;;;;;;;;GASG;AACH,MAAqB,eAAe;IAclC,mEAAmE;IACnE;;;;;;;;OAQG;IACH,YACE,GAAW,EACX,EACE,OAAO,GAAG,EAAE,EACZ,MAAM,EACN,KAAK,MAKH,EAAE;QAEN,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,OAAO,mCAAQ,2BAAe,GAAK,OAAO,CAAE,CAAA;QACjD,IAAI,CAA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,GAAG;YACH,OAAO;YACP,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,IAAI;YACJ,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,UAAU,EAAE,KAAK;SACmC,CAAC,CAAA;IACzD,CAAC;CACF;AAvID,kCAuIC"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestFilterBuilder.d.ts b/node_modules/@supabase/postgrest-js/dist/main/PostgrestFilterBuilder.d.ts new file mode 100644 index 0000000..f6487ee --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestFilterBuilder.d.ts @@ -0,0 +1,81 @@ +import PostgrestTransformBuilder from './PostgrestTransformBuilder'; +import { GenericSchema } from './types'; +declare type FilterOperator = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'like' | 'ilike' | 'is' | 'in' | 'cs' | 'cd' | 'sl' | 'sr' | 'nxl' | 'nxr' | 'adj' | 'ov' | 'fts' | 'plfts' | 'phfts' | 'wfts'; +export default class PostgrestFilterBuilder, Result, Relationships = unknown> extends PostgrestTransformBuilder { + eq(column: ColumnName, value: Row[ColumnName]): this; + eq(column: string, value: unknown): this; + neq(column: ColumnName, value: Row[ColumnName]): this; + neq(column: string, value: unknown): this; + gt(column: ColumnName, value: Row[ColumnName]): this; + gt(column: string, value: unknown): this; + gte(column: ColumnName, value: Row[ColumnName]): this; + gte(column: string, value: unknown): this; + lt(column: ColumnName, value: Row[ColumnName]): this; + lt(column: string, value: unknown): this; + lte(column: ColumnName, value: Row[ColumnName]): this; + lte(column: string, value: unknown): this; + like(column: ColumnName, pattern: string): this; + like(column: string, pattern: string): this; + likeAllOf(column: ColumnName, patterns: string[]): this; + likeAllOf(column: string, patterns: string[]): this; + likeAnyOf(column: ColumnName, patterns: string[]): this; + likeAnyOf(column: string, patterns: string[]): this; + ilike(column: ColumnName, pattern: string): this; + ilike(column: string, pattern: string): this; + ilikeAllOf(column: ColumnName, patterns: string[]): this; + ilikeAllOf(column: string, patterns: string[]): this; + ilikeAnyOf(column: ColumnName, patterns: string[]): this; + ilikeAnyOf(column: string, patterns: string[]): this; + is(column: ColumnName, value: Row[ColumnName] & (boolean | null)): this; + is(column: string, value: boolean | null): this; + in(column: ColumnName, values: Row[ColumnName][]): this; + in(column: string, values: unknown[]): this; + contains(column: ColumnName, value: string | Row[ColumnName][] | Record): this; + contains(column: string, value: string | unknown[] | Record): this; + containedBy(column: ColumnName, value: string | Row[ColumnName][] | Record): this; + containedBy(column: string, value: string | unknown[] | Record): this; + rangeGt(column: ColumnName, range: string): this; + rangeGt(column: string, range: string): this; + rangeGte(column: ColumnName, range: string): this; + rangeGte(column: string, range: string): this; + rangeLt(column: ColumnName, range: string): this; + rangeLt(column: string, range: string): this; + rangeLte(column: ColumnName, range: string): this; + rangeLte(column: string, range: string): this; + rangeAdjacent(column: ColumnName, range: string): this; + rangeAdjacent(column: string, range: string): this; + overlaps(column: ColumnName, value: string | Row[ColumnName][]): this; + overlaps(column: string, value: string | unknown[]): this; + textSearch(column: ColumnName, query: string, options?: { + config?: string; + type?: 'plain' | 'phrase' | 'websearch'; + }): this; + textSearch(column: string, query: string, options?: { + config?: string; + type?: 'plain' | 'phrase' | 'websearch'; + }): this; + match(query: Record): this; + match(query: Record): this; + not(column: ColumnName, operator: FilterOperator, value: Row[ColumnName]): this; + not(column: string, operator: string, value: unknown): this; + /** + * Match only rows which satisfy at least one of the filters. + * + * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure it's properly sanitized. + * + * It's currently not possible to do an `.or()` filter across multiple tables. + * + * @param filters - The filters to use, following PostgREST syntax + * @param foreignTable - Set this to filter on foreign tables instead of the + * current table + */ + or(filters: string, { foreignTable }?: { + foreignTable?: string; + }): this; + filter(column: ColumnName, operator: `${'' | 'not.'}${FilterOperator}`, value: unknown): this; + filter(column: string, operator: string, value: unknown): this; +} +export {}; +//# sourceMappingURL=PostgrestFilterBuilder.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestFilterBuilder.d.ts.map b/node_modules/@supabase/postgrest-js/dist/main/PostgrestFilterBuilder.d.ts.map new file mode 100644 index 0000000..62a0da7 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestFilterBuilder.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestFilterBuilder.d.ts","sourceRoot":"","sources":["../../src/PostgrestFilterBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,yBAAyB,MAAM,6BAA6B,CAAA;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAEvC,aAAK,cAAc,GACf,IAAI,GACJ,KAAK,GACL,IAAI,GACJ,KAAK,GACL,IAAI,GACJ,KAAK,GACL,MAAM,GACN,OAAO,GACP,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,IAAI,GACJ,KAAK,GACL,KAAK,GACL,KAAK,GACL,IAAI,GACJ,KAAK,GACL,OAAO,GACP,OAAO,GACP,MAAM,CAAA;AAEV,MAAM,CAAC,OAAO,OAAO,sBAAsB,CACzC,MAAM,SAAS,aAAa,EAC5B,GAAG,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACnC,MAAM,EACN,aAAa,GAAG,OAAO,CACvB,SAAQ,yBAAyB,CAAC,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,aAAa,CAAC;IACrE,EAAE,CAAC,UAAU,SAAS,MAAM,GAAG,MAAM,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,CAAC,UAAU,CAAC,GAAG,IAAI;IAC3F,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAcxC,GAAG,CAAC,UAAU,SAAS,MAAM,GAAG,MAAM,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,CAAC,UAAU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E,KAAK,EAAE,MAAM,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC,GAAG,IAAI;IAC9F,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;IAe3C,GAAG,CAAC,UAAU,SAAS,MAAM,GAAG,MAAM,GAAG,EACvC,MAAM,EAAE,UAAU,EAClB,QAAQ,EAAE,cAAc,EACxB,KAAK,EAAE,GAAG,CAAC,UAAU,CAAC,GACrB,IAAI;IACP,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;IAmB3D;;;;;;;;;;;;OAYG;IACH,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,YAAY,EAAE,GAAE;QAAE,YAAY,CAAC,EAAE,MAAM,CAAA;KAAO,GAAG,IAAI;IAM3E,MAAM,CAAC,UAAU,SAAS,MAAM,GAAG,MAAM,GAAG,EAC1C,MAAM,EAAE,UAAU,EAClB,QAAQ,EAAE,GAAG,EAAE,GAAG,MAAM,GAAG,cAAc,EAAE,EAC3C,KAAK,EAAE,OAAO,GACb,IAAI;IACP,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;CAkB/D"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestFilterBuilder.js b/node_modules/@supabase/postgrest-js/dist/main/PostgrestFilterBuilder.js new file mode 100644 index 0000000..755e95d --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestFilterBuilder.js @@ -0,0 +1,379 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const PostgrestTransformBuilder_1 = __importDefault(require("./PostgrestTransformBuilder")); +class PostgrestFilterBuilder extends PostgrestTransformBuilder_1.default { + /** + * Match only rows where `column` is equal to `value`. + * + * To check if the value of `column` is NULL, you should use `.is()` instead. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + eq(column, value) { + this.url.searchParams.append(column, `eq.${value}`); + return this; + } + /** + * Match only rows where `column` is not equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + neq(column, value) { + this.url.searchParams.append(column, `neq.${value}`); + return this; + } + /** + * Match only rows where `column` is greater than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gt(column, value) { + this.url.searchParams.append(column, `gt.${value}`); + return this; + } + /** + * Match only rows where `column` is greater than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gte(column, value) { + this.url.searchParams.append(column, `gte.${value}`); + return this; + } + /** + * Match only rows where `column` is less than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lt(column, value) { + this.url.searchParams.append(column, `lt.${value}`); + return this; + } + /** + * Match only rows where `column` is less than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lte(column, value) { + this.url.searchParams.append(column, `lte.${value}`); + return this; + } + /** + * Match only rows where `column` matches `pattern` case-sensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + like(column, pattern) { + this.url.searchParams.append(column, `like.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches all of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAllOf(column, patterns) { + this.url.searchParams.append(column, `like(all).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches any of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAnyOf(column, patterns) { + this.url.searchParams.append(column, `like(any).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches `pattern` case-insensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + ilike(column, pattern) { + this.url.searchParams.append(column, `ilike.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches all of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAllOf(column, patterns) { + this.url.searchParams.append(column, `ilike(all).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches any of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAnyOf(column, patterns) { + this.url.searchParams.append(column, `ilike(any).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` IS `value`. + * + * For non-boolean columns, this is only relevant for checking if the value of + * `column` is NULL by setting `value` to `null`. + * + * For boolean columns, you can also set `value` to `true` or `false` and it + * will behave the same way as `.eq()`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + is(column, value) { + this.url.searchParams.append(column, `is.${value}`); + return this; + } + /** + * Match only rows where `column` is included in the `values` array. + * + * @param column - The column to filter on + * @param values - The values array to filter with + */ + in(column, values) { + const cleanedValues = values + .map((s) => { + // handle postgrest reserved characters + // https://postgrest.org/en/v7.0.0/api.html#reserved-characters + if (typeof s === 'string' && new RegExp('[,()]').test(s)) + return `"${s}"`; + else + return `${s}`; + }) + .join(','); + this.url.searchParams.append(column, `in.(${cleanedValues})`); + return this; + } + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * `column` contains every element appearing in `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + contains(column, value) { + if (typeof value === 'string') { + // range types can be inclusive '[', ']' or exclusive '(', ')' so just + // keep it simple and accept a string + this.url.searchParams.append(column, `cs.${value}`); + } + else if (Array.isArray(value)) { + // array + this.url.searchParams.append(column, `cs.{${value.join(',')}}`); + } + else { + // json + this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`); + } + return this; + } + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * every element appearing in `column` is contained by `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + containedBy(column, value) { + if (typeof value === 'string') { + // range + this.url.searchParams.append(column, `cd.${value}`); + } + else if (Array.isArray(value)) { + // array + this.url.searchParams.append(column, `cd.{${value.join(',')}}`); + } + else { + // json + this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`); + } + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is greater than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGt(column, range) { + this.url.searchParams.append(column, `sr.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or greater than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGte(column, range) { + this.url.searchParams.append(column, `nxl.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is less than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLt(column, range) { + this.url.searchParams.append(column, `sl.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or less than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLte(column, range) { + this.url.searchParams.append(column, `nxr.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where `column` is + * mutually exclusive to `range` and there can be no element between the two + * ranges. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeAdjacent(column, range) { + this.url.searchParams.append(column, `adj.${range}`); + return this; + } + /** + * Only relevant for array and range columns. Match only rows where + * `column` and `value` have an element in common. + * + * @param column - The array or range column to filter on + * @param value - The array or range value to filter with + */ + overlaps(column, value) { + if (typeof value === 'string') { + // range + this.url.searchParams.append(column, `ov.${value}`); + } + else { + // array + this.url.searchParams.append(column, `ov.{${value.join(',')}}`); + } + return this; + } + /** + * Only relevant for text and tsvector columns. Match only rows where + * `column` matches the query string in `query`. + * + * @param column - The text or tsvector column to filter on + * @param query - The query text to match with + * @param options - Named parameters + * @param options.config - The text search configuration to use + * @param options.type - Change how the `query` text is interpreted + */ + textSearch(column, query, { config, type } = {}) { + let typePart = ''; + if (type === 'plain') { + typePart = 'pl'; + } + else if (type === 'phrase') { + typePart = 'ph'; + } + else if (type === 'websearch') { + typePart = 'w'; + } + const configPart = config === undefined ? '' : `(${config})`; + this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`); + return this; + } + /** + * Match only rows where each column in `query` keys is equal to its + * associated value. Shorthand for multiple `.eq()`s. + * + * @param query - The object to filter with, with column names as keys mapped + * to their filter values + */ + match(query) { + Object.entries(query).forEach(([column, value]) => { + this.url.searchParams.append(column, `eq.${value}`); + }); + return this; + } + /** + * Match only rows which doesn't satisfy the filter. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to be negated to filter with, following + * PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + not(column, operator, value) { + this.url.searchParams.append(column, `not.${operator}.${value}`); + return this; + } + /** + * Match only rows which satisfy at least one of the filters. + * + * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure it's properly sanitized. + * + * It's currently not possible to do an `.or()` filter across multiple tables. + * + * @param filters - The filters to use, following PostgREST syntax + * @param foreignTable - Set this to filter on foreign tables instead of the + * current table + */ + or(filters, { foreignTable } = {}) { + const key = foreignTable ? `${foreignTable}.or` : 'or'; + this.url.searchParams.append(key, `(${filters})`); + return this; + } + /** + * Match only rows which satisfy the filter. This is an escape hatch - you + * should use the specific filter methods wherever possible. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to filter with, following PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + filter(column, operator, value) { + this.url.searchParams.append(column, `${operator}.${value}`); + return this; + } +} +exports.default = PostgrestFilterBuilder; +//# sourceMappingURL=PostgrestFilterBuilder.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestFilterBuilder.js.map b/node_modules/@supabase/postgrest-js/dist/main/PostgrestFilterBuilder.js.map new file mode 100644 index 0000000..584a5ad --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestFilterBuilder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestFilterBuilder.js","sourceRoot":"","sources":["../../src/PostgrestFilterBuilder.ts"],"names":[],"mappings":";;;;;AAAA,4FAAmE;AA2BnE,MAAqB,sBAKnB,SAAQ,mCAA6D;IAGrE;;;;;;;OAOG;IACH,EAAE,CAAC,MAAc,EAAE,KAAc;QAC/B,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,KAAK,EAAE,CAAC,CAAA;QACnD,OAAO,IAAI,CAAA;IACb,CAAC;IAID;;;;;OAKG;IACH,GAAG,CAAC,MAAc,EAAE,KAAc;QAChC,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,KAAK,EAAE,CAAC,CAAA;QACpD,OAAO,IAAI,CAAA;IACb,CAAC;IAID;;;;;OAKG;IACH,EAAE,CAAC,MAAc,EAAE,KAAc;QAC/B,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,KAAK,EAAE,CAAC,CAAA;QACnD,OAAO,IAAI,CAAA;IACb,CAAC;IAID;;;;;OAKG;IACH,GAAG,CAAC,MAAc,EAAE,KAAc;QAChC,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,KAAK,EAAE,CAAC,CAAA;QACpD,OAAO,IAAI,CAAA;IACb,CAAC;IAID;;;;;OAKG;IACH,EAAE,CAAC,MAAc,EAAE,KAAc;QAC/B,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,MA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b,CAAC;IAQD;;;;;;;;;;;;OAYG;IACH,MAAM,CAAC,MAAc,EAAE,QAAgB,EAAE,KAAc;QACrD,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,QAAQ,IAAI,KAAK,EAAE,CAAC,CAAA;QAC5D,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AA5dD,yCA4dC"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestQueryBuilder.d.ts b/node_modules/@supabase/postgrest-js/dist/main/PostgrestQueryBuilder.d.ts new file mode 100644 index 0000000..ca107a8 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestQueryBuilder.d.ts @@ -0,0 +1,168 @@ +import PostgrestFilterBuilder from './PostgrestFilterBuilder'; +import { GetResult } from './select-query-parser'; +import { Fetch, GenericSchema, GenericTable, GenericView } from './types'; +export default class PostgrestQueryBuilder { + url: URL; + headers: Record; + schema?: string; + signal?: AbortSignal; + fetch?: Fetch; + constructor(url: URL, { headers, schema, fetch, }: { + headers?: Record; + schema?: string; + fetch?: Fetch; + }); + /** + * Perform a SELECT query on the table or view. + * + * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` + * + * @param options - Named parameters + * + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * + * @param options.count - Count algorithm to use to count rows in the table or view. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + select>(columns?: Query, { head, count, }?: { + head?: boolean; + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder; + /** + * Perform an INSERT into the table or view. + * + * By default, inserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to insert. Pass an object to insert a single row + * or an array to insert multiple rows. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count inserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. + */ + insert(values: Row | Row[], { count, defaultToNull, }?: { + count?: 'exact' | 'planned' | 'estimated'; + defaultToNull?: boolean; + }): PostgrestFilterBuilder; + /** + * Perform an UPSERT on the table or view. Depending on the column(s) passed + * to `onConflict`, `.upsert()` allows you to perform the equivalent of + * `.insert()` if a row with the corresponding `onConflict` columns doesn't + * exist, or if it does exist, perform an alternative action depending on + * `ignoreDuplicates`. + * + * By default, upserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to upsert with. Pass an object to upsert a + * single row or an array to upsert multiple rows. + * + * @param options - Named parameters + * + * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how + * duplicate rows are determined. Two rows are duplicates if all the + * `onConflict` columns are equal. + * + * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If + * `false`, duplicate rows are merged with existing rows. + * + * @param options.count - Count algorithm to use to count upserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. This only applies when + * inserting new rows, not when merging with existing rows under + * `ignoreDuplicates: false`. + */ + upsert(values: Row | Row[], { onConflict, ignoreDuplicates, count, defaultToNull, }?: { + onConflict?: string; + ignoreDuplicates?: boolean; + count?: 'exact' | 'planned' | 'estimated'; + defaultToNull?: boolean; + }): PostgrestFilterBuilder; + /** + * Perform an UPDATE on the table or view. + * + * By default, updated rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param values - The values to update with + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count updated rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + update(values: Row, { count, }?: { + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder; + /** + * Perform a DELETE on the table or view. + * + * By default, deleted rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count deleted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + delete({ count, }?: { + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder; +} +//# sourceMappingURL=PostgrestQueryBuilder.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestQueryBuilder.d.ts.map b/node_modules/@supabase/postgrest-js/dist/main/PostgrestQueryBuilder.d.ts.map new file mode 100644 index 0000000..df9c193 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestQueryBuilder.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestQueryBuilder.d.ts","sourceRoot":"","sources":["../../src/PostgrestQueryBuilder.ts"],"names":[],"mappings":"AACA,OAAO,sBAAsB,MAAM,0BAA0B,CAAA;AAC7D,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAA;AACjD,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAEzE,MAAM,CAAC,OAAO,OAAO,qBAAqB,CACxC,MAAM,SAAS,aAAa,EAC5B,QAAQ,SAAS,YAAY,GAAG,WAAW,EAC3C,aAAa,GA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E,QAAQ,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,aAAa,CAAC;CAoB9E"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestQueryBuilder.js b/node_modules/@supabase/postgrest-js/dist/main/PostgrestQueryBuilder.js new file mode 100644 index 0000000..ff75e86 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestQueryBuilder.js @@ -0,0 +1,270 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const PostgrestFilterBuilder_1 = __importDefault(require("./PostgrestFilterBuilder")); +class PostgrestQueryBuilder { + constructor(url, { headers = {}, schema, fetch, }) { + this.url = url; + this.headers = headers; + this.schema = schema; + this.fetch = fetch; + } + /** + * Perform a SELECT query on the table or view. + * + * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` + * + * @param options - Named parameters + * + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * + * @param options.count - Count algorithm to use to count rows in the table or view. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + select(columns, { head = false, count, } = {}) { + const method = head ? 'HEAD' : 'GET'; + // Remove whitespaces except when quoted + let quoted = false; + const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') + .split('') + .map((c) => { + if (/\s/.test(c) && !quoted) { + return ''; + } + if (c === '"') { + quoted = !quoted; + } + return c; + }) + .join(''); + this.url.searchParams.set('select', cleanedColumns); + if (count) { + this.headers['Prefer'] = `count=${count}`; + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: this.fetch, + allowEmpty: false, + }); + } + /** + * Perform an INSERT into the table or view. + * + * By default, inserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to insert. Pass an object to insert a single row + * or an array to insert multiple rows. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count inserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. + */ + insert(values, { count, defaultToNull = true, } = {}) { + const method = 'POST'; + const prefersHeaders = []; + if (this.headers['Prefer']) { + prefersHeaders.push(this.headers['Prefer']); + } + if (count) { + prefersHeaders.push(`count=${count}`); + } + if (!defaultToNull) { + prefersHeaders.push('missing=default'); + } + this.headers['Prefer'] = prefersHeaders.join(','); + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); + this.url.searchParams.set('columns', uniqueColumns.join(',')); + } + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: this.fetch, + allowEmpty: false, + }); + } + /** + * Perform an UPSERT on the table or view. Depending on the column(s) passed + * to `onConflict`, `.upsert()` allows you to perform the equivalent of + * `.insert()` if a row with the corresponding `onConflict` columns doesn't + * exist, or if it does exist, perform an alternative action depending on + * `ignoreDuplicates`. + * + * By default, upserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to upsert with. Pass an object to upsert a + * single row or an array to upsert multiple rows. + * + * @param options - Named parameters + * + * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how + * duplicate rows are determined. Two rows are duplicates if all the + * `onConflict` columns are equal. + * + * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If + * `false`, duplicate rows are merged with existing rows. + * + * @param options.count - Count algorithm to use to count upserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. This only applies when + * inserting new rows, not when merging with existing rows under + * `ignoreDuplicates: false`. + */ + upsert(values, { onConflict, ignoreDuplicates = false, count, defaultToNull = true, } = {}) { + const method = 'POST'; + const prefersHeaders = [`resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates`]; + if (onConflict !== undefined) + this.url.searchParams.set('on_conflict', onConflict); + if (this.headers['Prefer']) { + prefersHeaders.push(this.headers['Prefer']); + } + if (count) { + prefersHeaders.push(`count=${count}`); + } + if (!defaultToNull) { + prefersHeaders.push('missing=default'); + } + this.headers['Prefer'] = prefersHeaders.join(','); + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); + this.url.searchParams.set('columns', uniqueColumns.join(',')); + } + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: this.fetch, + allowEmpty: false, + }); + } + /** + * Perform an UPDATE on the table or view. + * + * By default, updated rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param values - The values to update with + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count updated rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + update(values, { count, } = {}) { + const method = 'PATCH'; + const prefersHeaders = []; + if (this.headers['Prefer']) { + prefersHeaders.push(this.headers['Prefer']); + } + if (count) { + prefersHeaders.push(`count=${count}`); + } + this.headers['Prefer'] = prefersHeaders.join(','); + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: this.fetch, + allowEmpty: false, + }); + } + /** + * Perform a DELETE on the table or view. + * + * By default, deleted rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count deleted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + delete({ count, } = {}) { + const method = 'DELETE'; + const prefersHeaders = []; + if (count) { + prefersHeaders.push(`count=${count}`); + } + if (this.headers['Prefer']) { + prefersHeaders.unshift(this.headers['Prefer']); + } + this.headers['Prefer'] = prefersHeaders.join(','); + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: this.fetch, + allowEmpty: false, + }); + } +} +exports.default = PostgrestQueryBuilder; +//# sourceMappingURL=PostgrestQueryBuilder.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestQueryBuilder.js.map b/node_modules/@supabase/postgrest-js/dist/main/PostgrestQueryBuilder.js.map new file mode 100644 index 0000000..0b1c393 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestQueryBuilder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestQueryBuilder.js","sourceRoot":"","sources":["../../src/PostgrestQueryBuilder.ts"],"names":[],"mappings":";;;;;AACA,sFAA6D;AAI7D,MAAqB,qBAAqB;IAWxC,YACE,GAAQ,EACR,EACE,OAAO,GAAG,EAAE,EACZ,MAAM,EACN,KAAK,GAKN;QAED,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,KAAK,GAAG,KAAK,CAA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AED;;;;;;;;;;;;;;;;;;OAkBG;IACH,MAAM,CAAC,EACL,KAAK,MAGH,EAAE;QACJ,MAAM,MAAM,GAAG,QAAQ,CAAA;QACvB,MAAM,cAAc,GAAG,EAAE,CAAA;QACzB,IAAI,KAAK,EAAE;YACT,cAAc,CAAC,IAAI,CAAC,SAAS,KAAK,EAAE,CAAC,CAAA;SACtC;QACD,IAAI,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;YAC1B,cAAc,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAA;SAC/C;QACD,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;QAEjD,OAAO,IAAI,gCAAsB,CAAC;YAChC,MAAM;YACN,GAAG,EAAE,IAAI,CAAC,GAAG;YACb,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,UAAU,EAAE,KAAK;SACmB,CAAC,CAAA;IACzC,CAAC;CACF;AArVD,wCAqVC"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestTransformBuilder.d.ts b/node_modules/@supabase/postgrest-js/dist/main/PostgrestTransformBuilder.d.ts new file mode 100644 index 0000000..6ff34ee --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestTransformBuilder.d.ts @@ -0,0 +1,122 @@ +import PostgrestBuilder from './PostgrestBuilder'; +import { GetResult } from './select-query-parser'; +import { GenericSchema } from './types'; +export default class PostgrestTransformBuilder, Result, Relationships = unknown> extends PostgrestBuilder { + /** + * Perform a SELECT on the query result. + * + * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not + * return modified rows. By calling this method, modified rows are returned in + * `data`. + * + * @param columns - The columns to retrieve, separated by commas + */ + select>(columns?: Query): PostgrestTransformBuilder; + order(column: ColumnName, options?: { + ascending?: boolean; + nullsFirst?: boolean; + foreignTable?: undefined; + }): this; + order(column: string, options?: { + ascending?: boolean; + nullsFirst?: boolean; + foreignTable?: string; + }): this; + /** + * Limit the query result by `count`. + * + * @param count - The maximum number of rows to return + * @param options - Named parameters + * @param options.foreignTable - Set this to limit rows of foreign tables + * instead of the current table + */ + limit(count: number, { foreignTable }?: { + foreignTable?: string; + }): this; + /** + * Limit the query result by starting at an offset (`from`) and ending at the offset (`from + to`). + * Only records within this range are returned. + * This respects the query order and if there is no order clause the range could behave unexpectedly. + * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third + * and fourth rows of the query. + * + * @param from - The starting index from which to limit the result + * @param to - The last index to which to limit the result + * @param options - Named parameters + * @param options.foreignTable - Set this to limit rows of foreign tables + * instead of the current table + */ + range(from: number, to: number, { foreignTable }?: { + foreignTable?: string; + }): this; + /** + * Set the AbortSignal for the fetch request. + * + * @param signal - The AbortSignal to use for the fetch request + */ + abortSignal(signal: AbortSignal): this; + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be one row (e.g. using `.limit(1)`), otherwise this + * returns an error. + */ + single(): PostgrestBuilder; + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise + * this returns an error. + */ + maybeSingle(): PostgrestBuilder; + /** + * Return `data` as a string in CSV format. + */ + csv(): PostgrestBuilder; + /** + * Return `data` as an object in [GeoJSON](https://geojson.org) format. + */ + geojson(): PostgrestBuilder>; + /** + * Return `data` as the EXPLAIN plan for the query. + * + * @param options - Named parameters + * + * @param options.analyze - If `true`, the query will be executed and the + * actual run time will be returned + * + * @param options.verbose - If `true`, the query identifier will be returned + * and `data` will include the output columns of the query + * + * @param options.settings - If `true`, include information on configuration + * parameters that affect query planning + * + * @param options.buffers - If `true`, include information on buffer usage + * + * @param options.wal - If `true`, include information on WAL record generation + * + * @param options.format - The format of the output, can be `"text"` (default) + * or `"json"` + */ + explain({ analyze, verbose, settings, buffers, wal, format, }?: { + analyze?: boolean; + verbose?: boolean; + settings?: boolean; + buffers?: boolean; + wal?: boolean; + format?: 'json' | 'text'; + }): PostgrestBuilder[]> | PostgrestBuilder; + /** + * Rollback the query. + * + * `data` will still be returned, but the query is not committed. + */ + rollback(): this; + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + */ + returns(): PostgrestTransformBuilder; +} +//# sourceMappingURL=PostgrestTransformBuilder.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestTransformBuilder.d.ts.map b/node_modules/@supabase/postgrest-js/dist/main/PostgrestTransformBuilder.d.ts.map new file mode 100644 index 0000000..52f1323 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestTransformBuilder.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestTransformBuilder.d.ts","sourceRoot":"","sources":["../../src/PostgrestTransformBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,gBAAgB,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAA;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAEvC,MAAM,CAAC,OAAO,OAAO,yBAAyB,CAC5C,MAAM,SAAS,aAAa,EAC5B,GAAG,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACnC,MAAM,EACN,aAAa,GAAG,OAAO,CACvB,SAAQ,gBAAgB,CAAC,MAAM,CAAC;IAChC;;;;;;;;OAQG;IACH,MAAM,CAAC,KAAK,SAAS,MAAM,GAAG,GAAG,EAAE,YAAY,GAAG,SAAS,CAAC,MAAM,EAAE,GAAG,EAAE,aAAa,EAAE,KAAK,CAAC,EAC5F,OAAO,CAAC,EAAE,KAAK,GACd,yBAAyB,CAAC,MAAM,EAAE,GAAG,EAAE,YAAY,EAAE,EAAE,aAAa,CAAC;IAuBxE,KAAK,CAAC,UAAU,SAAS,MAAM,GAAG,M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,OAAO,CAAC,EACN,OAAe,EACf,OAAe,EACf,QAAgB,EAChB,OAAe,EACf,GAAW,EACX,MAAe,GAChB,GAAE;QACD,OAAO,CAAC,EAAE,OAAO,CAAA;QACjB,OAAO,CAAC,EAAE,OAAO,CAAA;QACjB,QAAQ,CAAC,EAAE,OAAO,CAAA;QAClB,OAAO,CAAC,EAAE,OAAO,CAAA;QACjB,GAAG,CAAC,EAAE,OAAO,CAAA;QACb,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;KACpB,GAAG,gBAAgB,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,GAAG,gBAAgB,CAAC,MAAM,CAAC;IAmB/E;;;;OAIG;IACH,QAAQ,IAAI,IAAI;IAShB;;;;OAIG;IACH,OAAO,CAAC,SAAS,KAAK,yBAAyB,CAAC,MAAM,EAAE,GAAG,EAAE,SAAS,EAAE,aAAa,CAAC;CAGvF"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestTransformBuilder.js b/node_modules/@supabase/postgrest-js/dist/main/PostgrestTransformBuilder.js new file mode 100644 index 0000000..0d93abd --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestTransformBuilder.js @@ -0,0 +1,210 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const PostgrestBuilder_1 = __importDefault(require("./PostgrestBuilder")); +class PostgrestTransformBuilder extends PostgrestBuilder_1.default { + /** + * Perform a SELECT on the query result. + * + * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not + * return modified rows. By calling this method, modified rows are returned in + * `data`. + * + * @param columns - The columns to retrieve, separated by commas + */ + select(columns) { + // Remove whitespaces except when quoted + let quoted = false; + const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') + .split('') + .map((c) => { + if (/\s/.test(c) && !quoted) { + return ''; + } + if (c === '"') { + quoted = !quoted; + } + return c; + }) + .join(''); + this.url.searchParams.set('select', cleanedColumns); + if (this.headers['Prefer']) { + this.headers['Prefer'] += ','; + } + this.headers['Prefer'] += 'return=representation'; + return this; + } + /** + * Order the query result by `column`. + * + * You can call this method multiple times to order by multiple columns. + * + * You can order foreign tables, but it doesn't affect the ordering of the + * current table. + * + * @param column - The column to order by + * @param options - Named parameters + * @param options.ascending - If `true`, the result will be in ascending order + * @param options.nullsFirst - If `true`, `null`s appear first. If `false`, + * `null`s appear last. + * @param options.foreignTable - Set this to order a foreign table by foreign + * columns + */ + order(column, { ascending = true, nullsFirst, foreignTable, } = {}) { + const key = foreignTable ? `${foreignTable}.order` : 'order'; + const existingOrder = this.url.searchParams.get(key); + this.url.searchParams.set(key, `${existingOrder ? `${existingOrder},` : ''}${column}.${ascending ? 'asc' : 'desc'}${nullsFirst === undefined ? '' : nullsFirst ? '.nullsfirst' : '.nullslast'}`); + return this; + } + /** + * Limit the query result by `count`. + * + * @param count - The maximum number of rows to return + * @param options - Named parameters + * @param options.foreignTable - Set this to limit rows of foreign tables + * instead of the current table + */ + limit(count, { foreignTable } = {}) { + const key = typeof foreignTable === 'undefined' ? 'limit' : `${foreignTable}.limit`; + this.url.searchParams.set(key, `${count}`); + return this; + } + /** + * Limit the query result by starting at an offset (`from`) and ending at the offset (`from + to`). + * Only records within this range are returned. + * This respects the query order and if there is no order clause the range could behave unexpectedly. + * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third + * and fourth rows of the query. + * + * @param from - The starting index from which to limit the result + * @param to - The last index to which to limit the result + * @param options - Named parameters + * @param options.foreignTable - Set this to limit rows of foreign tables + * instead of the current table + */ + range(from, to, { foreignTable } = {}) { + const keyOffset = typeof foreignTable === 'undefined' ? 'offset' : `${foreignTable}.offset`; + const keyLimit = typeof foreignTable === 'undefined' ? 'limit' : `${foreignTable}.limit`; + this.url.searchParams.set(keyOffset, `${from}`); + // Range is inclusive, so add 1 + this.url.searchParams.set(keyLimit, `${to - from + 1}`); + return this; + } + /** + * Set the AbortSignal for the fetch request. + * + * @param signal - The AbortSignal to use for the fetch request + */ + abortSignal(signal) { + this.signal = signal; + return this; + } + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be one row (e.g. using `.limit(1)`), otherwise this + * returns an error. + */ + single() { + this.headers['Accept'] = 'application/vnd.pgrst.object+json'; + return this; + } + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise + * this returns an error. + */ + maybeSingle() { + // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 + // Issue persists e.g. for `.insert([...]).select().maybeSingle()` + if (this.method === 'GET') { + this.headers['Accept'] = 'application/json'; + } + else { + this.headers['Accept'] = 'application/vnd.pgrst.object+json'; + } + this.isMaybeSingle = true; + return this; + } + /** + * Return `data` as a string in CSV format. + */ + csv() { + this.headers['Accept'] = 'text/csv'; + return this; + } + /** + * Return `data` as an object in [GeoJSON](https://geojson.org) format. + */ + geojson() { + this.headers['Accept'] = 'application/geo+json'; + return this; + } + /** + * Return `data` as the EXPLAIN plan for the query. + * + * @param options - Named parameters + * + * @param options.analyze - If `true`, the query will be executed and the + * actual run time will be returned + * + * @param options.verbose - If `true`, the query identifier will be returned + * and `data` will include the output columns of the query + * + * @param options.settings - If `true`, include information on configuration + * parameters that affect query planning + * + * @param options.buffers - If `true`, include information on buffer usage + * + * @param options.wal - If `true`, include information on WAL record generation + * + * @param options.format - The format of the output, can be `"text"` (default) + * or `"json"` + */ + explain({ analyze = false, verbose = false, settings = false, buffers = false, wal = false, format = 'text', } = {}) { + const options = [ + analyze ? 'analyze' : null, + verbose ? 'verbose' : null, + settings ? 'settings' : null, + buffers ? 'buffers' : null, + wal ? 'wal' : null, + ] + .filter(Boolean) + .join('|'); + // An Accept header can carry multiple media types but postgrest-js always sends one + const forMediatype = this.headers['Accept']; + this.headers['Accept'] = `application/vnd.pgrst.plan+${format}; for="${forMediatype}"; options=${options};`; + if (format === 'json') + return this; + else + return this; + } + /** + * Rollback the query. + * + * `data` will still be returned, but the query is not committed. + */ + rollback() { + var _a; + if (((_a = this.headers['Prefer']) !== null && _a !== void 0 ? _a : '').trim().length > 0) { + this.headers['Prefer'] += ',tx=rollback'; + } + else { + this.headers['Prefer'] = 'tx=rollback'; + } + return this; + } + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + */ + returns() { + return this; + } +} +exports.default = PostgrestTransformBuilder; +//# sourceMappingURL=PostgrestTransformBuilder.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/PostgrestTransformBuilder.js.map b/node_modules/@supabase/postgrest-js/dist/main/PostgrestTransformBuilder.js.map new file mode 100644 index 0000000..82cbc33 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/PostgrestTransformBuilder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestTransformBuilder.js","sourceRoot":"","sources":["../../src/PostgrestTransformBuilder.ts"],"names":[],"mappings":";;;;;AAAA,0EAAiD;AAIjD,MAAqB,yBAKnB,SAAQ,0BAAwB;IAChC;;;;;;;;OAQG;IACH,MAAM,CACJ,OAAe;QAEf,wCAAwC;QACxC,IAAI,MAAM,GAAG,KAAK,CAAA;QAClB,MAAM,cAAc,GAAG,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,GAAG,CAAC;aACpC,KAAK,CAAC,EAAE,CAAC;aACT,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;YACT,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE;gBAC3B,OAAO,EAAE,CAAA;aACV;YACD,IAAI,CAAC,KAAK,GAAG,EAAE;gBACb,MAAM,GAAG,CAAC,MAAM,CAAA;aACjB;YACD,OAAO,CAAC,CAAA;QACV,CAAC,CAAC;aACD,IAAI,CAAC,EAAE,CAAC,CAAA;QACX,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC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,GAAG,CAAC,EAAE;YACpD,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,cAAc,CAAA;SACzC;aAAM;YACL,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,aAAa,CAAA;SACvC;QACD,OAAO,IAAI,CAAA;IACb,CAAC;IAED;;;;OAIG;IACH,OAAO;QACL,OAAO,IAAmF,CAAA;IAC5F,CAAC;CACF;AA/PD,4CA+PC"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/constants.d.ts b/node_modules/@supabase/postgrest-js/dist/main/constants.d.ts new file mode 100644 index 0000000..12eb562 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/constants.d.ts @@ -0,0 +1,4 @@ +export declare const DEFAULT_HEADERS: { + 'X-Client-Info': string; +}; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/constants.d.ts.map b/node_modules/@supabase/postgrest-js/dist/main/constants.d.ts.map new file mode 100644 index 0000000..68e5791 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,eAAe;;CAAiD,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/constants.js b/node_modules/@supabase/postgrest-js/dist/main/constants.js new file mode 100644 index 0000000..c4ddfc0 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/constants.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_HEADERS = void 0; +const version_1 = require("./version"); +exports.DEFAULT_HEADERS = { 'X-Client-Info': `postgrest-js/${version_1.version}` }; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/constants.js.map b/node_modules/@supabase/postgrest-js/dist/main/constants.js.map new file mode 100644 index 0000000..5c6b50a --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":";;;AAAA,uCAAmC;AACtB,QAAA,eAAe,GAAG,EAAE,eAAe,EAAE,gBAAgB,iBAAO,EAAE,EAAE,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/index.d.ts b/node_modules/@supabase/postgrest-js/dist/main/index.d.ts new file mode 100644 index 0000000..8400a73 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/index.d.ts @@ -0,0 +1,7 @@ +export { default as PostgrestClient } from './PostgrestClient'; +export { default as PostgrestQueryBuilder } from './PostgrestQueryBuilder'; +export { default as PostgrestFilterBuilder } from './PostgrestFilterBuilder'; +export { default as PostgrestTransformBuilder } from './PostgrestTransformBuilder'; +export { default as PostgrestBuilder } from './PostgrestBuilder'; +export { PostgrestResponse, PostgrestResponseFailure, PostgrestResponseSuccess, PostgrestSingleResponse, PostgrestMaybeSingleResponse, PostgrestError, } from './types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/index.d.ts.map b/node_modules/@supabase/postgrest-js/dist/main/index.d.ts.map new file mode 100644 index 0000000..96ed024 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAC9D,OAAO,EAAE,OAAO,IAAI,qBAAqB,EAAE,MAAM,yBAAyB,CAAA;AAC1E,OAAO,EAAE,OAAO,IAAI,sBAAsB,EAAE,MAAM,0BAA0B,CAAA;AAC5E,OAAO,EAAE,OAAO,IAAI,yBAAyB,EAAE,MAAM,6BAA6B,CAAA;AAClF,OAAO,EAAE,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AAChE,OAAO,EACL,iBAAiB,EACjB,wBAAwB,EACxB,wBAAwB,EACxB,uBAAuB,EACvB,4BAA4B,EAC5B,cAAc,GACf,MAAM,SAAS,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/index.js b/node_modules/@supabase/postgrest-js/dist/main/index.js new file mode 100644 index 0000000..f5b3126 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/index.js @@ -0,0 +1,17 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PostgrestBuilder = exports.PostgrestTransformBuilder = exports.PostgrestFilterBuilder = exports.PostgrestQueryBuilder = exports.PostgrestClient = void 0; +var PostgrestClient_1 = require("./PostgrestClient"); +Object.defineProperty(exports, "PostgrestClient", { enumerable: true, get: function () { return __importDefault(PostgrestClient_1).default; } }); +var PostgrestQueryBuilder_1 = require("./PostgrestQueryBuilder"); +Object.defineProperty(exports, "PostgrestQueryBuilder", { enumerable: true, get: function () { return __importDefault(PostgrestQueryBuilder_1).default; } }); +var PostgrestFilterBuilder_1 = require("./PostgrestFilterBuilder"); +Object.defineProperty(exports, "PostgrestFilterBuilder", { enumerable: true, get: function () { return __importDefault(PostgrestFilterBuilder_1).default; } }); +var PostgrestTransformBuilder_1 = require("./PostgrestTransformBuilder"); +Object.defineProperty(exports, "PostgrestTransformBuilder", { enumerable: true, get: function () { return __importDefault(PostgrestTransformBuilder_1).default; } }); +var PostgrestBuilder_1 = require("./PostgrestBuilder"); +Object.defineProperty(exports, "PostgrestBuilder", { enumerable: true, get: function () { return __importDefault(PostgrestBuilder_1).default; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/index.js.map b/node_modules/@supabase/postgrest-js/dist/main/index.js.map new file mode 100644 index 0000000..11bbf29 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;AAAA,qDAA8D;AAArD,mIAAA,OAAO,OAAmB;AACnC,iEAA0E;AAAjE,+IAAA,OAAO,OAAyB;AACzC,mEAA4E;AAAnE,iJAAA,OAAO,OAA0B;AAC1C,yEAAkF;AAAzE,uJAAA,OAAO,OAA6B;AAC7C,uDAAgE;AAAvD,qIAAA,OAAO,OAAoB"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/select-query-parser.d.ts b/node_modules/@supabase/postgrest-js/dist/main/select-query-parser.d.ts new file mode 100644 index 0000000..f1733bc --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/select-query-parser.d.ts @@ -0,0 +1,272 @@ +import { GenericSchema, Prettify } from './types'; +declare type Whitespace = ' ' | '\n' | '\t'; +declare type LowerAlphabet = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z'; +declare type Alphabet = LowerAlphabet | Uppercase; +declare type Digit = '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '0'; +declare type Letter = Alphabet | Digit | '_'; +declare type Json = string | number | boolean | null | { + [key: string]: Json; +} | Json[]; +/** + * Parser errors. + */ +declare type ParserError = { + error: true; +} & Message; +declare type GenericStringError = ParserError<'Received a generic string'>; +export declare type SelectQueryError = { + error: true; +} & Message; +/** + * Trims whitespace from the left of the input. + */ +declare type EatWhitespace = string extends Input ? GenericStringError : Input extends `${Whitespace}${infer Remainder}` ? EatWhitespace : Input; +declare type HasFKey = Relationships extends [infer R] ? R extends { + foreignKeyName: FKeyName; +} ? true : false : Relationships extends [infer R, ...infer Rest] ? HasFKey extends true ? true : HasFKey : false; +declare type HasFKeyToFRel = Relationships extends [infer R] ? R extends { + referencedRelation: FRelName; +} ? true : false : Relationships extends [infer R, ...infer Rest] ? HasFKeyToFRel extends true ? true : HasFKeyToFRel : false; +/** + * Constructs a type definition for a single field of an object. + * + * @param Definitions Record of definitions, possibly generated from PostgREST's OpenAPI spec. + * @param Name Name of the table being queried. + * @param Field Single field parsed by `ParseQuery`. + */ +declare type ConstructFieldDefinition, Relationships, Field> = Field extends { + star: true; +} ? Row : Field extends { + name: string; + original: string; + hint: string; + children: unknown[]; +} ? { + [_ in Field['name']]: GetResultHelper extends infer Child ? Relationships extends unknown[] ? HasFKey extends true ? Child | null : Child[] : Child[] : never; +} : Field extends { + name: string; + original: string; + children: unknown[]; +} ? { + [_ in Field['name']]: GetResultHelper extends infer Child ? Relationships extends unknown[] ? HasFKeyToFRel extends true ? Child | null : Child[] : Child[] : never; +} : Field extends { + name: string; + original: string; +} ? Field['original'] extends keyof Row ? { + [K in Field['name']]: Row[Field['original']]; +} : SelectQueryError<`Referencing missing column \`${Field['original']}\``> : Field extends { + name: string; + type: infer T; +} ? { + [K in Field['name']]: T; +} : Record; +/** + * Notes: all `Parse*` types assume that their input strings have their whitespace + * removed. They return tuples of ["Return Value", "Remainder of text"] or + * a `ParserError`. + */ +/** + * Reads a consecutive sequence of more than 1 letter, + * where letters are `[0-9a-zA-Z_]`. + */ +declare type ReadLetters = string extends Input ? GenericStringError : ReadLettersHelper extends [`${infer Letters}`, `${infer Remainder}`] ? Letters extends '' ? ParserError<`Expected letter at \`${Input}\``> : [Letters, Remainder] : ReadLettersHelper; +declare type ReadLettersHelper = string extends Input ? GenericStringError : Input extends `${infer L}${infer Remainder}` ? L extends Letter ? ReadLettersHelper : [Acc, Input] : [Acc, '']; +/** + * Reads a consecutive sequence of more than 1 double-quoted letters, + * where letters are `[^"]`. + */ +declare type ReadQuotedLetters = string extends Input ? GenericStringError : Input extends `"${infer Remainder}` ? ReadQuotedLettersHelper extends [`${infer Letters}`, `${infer Remainder}`] ? Letters extends '' ? ParserError<`Expected string at \`${Remainder}\``> : [Letters, Remainder] : ReadQuotedLettersHelper : ParserError<`Not a double-quoted string at \`${Input}\``>; +declare type ReadQuotedLettersHelper = string extends Input ? GenericStringError : Input extends `${infer L}${infer Remainder}` ? L extends '"' ? [Acc, Remainder] : ReadQuotedLettersHelper : ParserError<`Missing closing double-quote in \`"${Acc}${Input}\``>; +/** + * Parses a (possibly double-quoted) identifier. + * For now, identifiers are just sequences of more than 1 letter. + */ +declare type ParseIdentifier = ReadLetters extends [ + infer Name, + `${infer Remainder}` +] ? [Name, `${Remainder}`] : ReadQuotedLetters extends [infer Name, `${infer Remainder}`] ? [Name, `${Remainder}`] : ParserError<`No (possibly double-quoted) identifier at \`${Input}\``>; +/** + * Parses a node. + * A node is one of the following: + * - `*` + * - `field` + * - `field->json...` + * - `field(nodes)` + * - `field!hint(nodes)` + * - `field!inner(nodes)` + * - `field!hint!inner(nodes)` + * - `renamed_field:field` + * - `renamed_field:field->json...` + * - `renamed_field:field(nodes)` + * - `renamed_field:field!hint(nodes)` + * - `renamed_field:field!inner(nodes)` + * - `renamed_field:field!hint!inner(nodes)` + * + * TODO: casting operators `::text`, more support for JSON operators `->`, `->>`. + */ +declare type ParseNode = Input extends '' ? ParserError<'Empty string'> : Input extends `*${infer Remainder}` ? [{ + star: true; +}, EatWhitespace] : ParseIdentifier extends [infer Name, `${infer Remainder}`] ? EatWhitespace extends `!inner${infer Remainder}` ? ParseEmbeddedResource> extends [infer Fields, `${infer Remainder}`] ? [ + { + name: Name; + original: Name; + children: Fields; + }, + EatWhitespace +] : ParseEmbeddedResource> extends ParserError ? ParseEmbeddedResource> : ParserError<'Expected embedded resource after `!inner`'> : EatWhitespace extends `!${infer Remainder}` ? ParseIdentifier> extends [infer Hint, `${infer Remainder}`] ? EatWhitespace extends `!inner${infer Remainder}` ? ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` +] ? [ + { + name: Name; + original: Name; + hint: Hint; + children: Fields; + }, + EatWhitespace +] : ParseEmbeddedResource> extends ParserError ? ParseEmbeddedResource> : ParserError<'Expected embedded resource after `!inner`'> : ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` +] ? [ + { + name: Name; + original: Name; + hint: Hint; + children: Fields; + }, + EatWhitespace +] : ParseEmbeddedResource> extends ParserError ? ParseEmbeddedResource> : ParserError<'Expected embedded resource after `!hint`'> : ParserError<'Expected identifier after `!`'> : EatWhitespace extends `:${infer Remainder}` ? ParseIdentifier> extends [infer OriginalName, `${infer Remainder}`] ? EatWhitespace extends `!inner${infer Remainder}` ? ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` +] ? [ + { + name: Name; + original: OriginalName; + children: Fields; + }, + EatWhitespace +] : ParseEmbeddedResource> extends ParserError ? ParseEmbeddedResource> : ParserError<'Expected embedded resource after `!inner`'> : EatWhitespace extends `!${infer Remainder}` ? ParseIdentifier> extends [infer Hint, `${infer Remainder}`] ? EatWhitespace extends `!inner${infer Remainder}` ? ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` +] ? [ + { + name: Name; + original: OriginalName; + hint: Hint; + children: Fields; + }, + EatWhitespace +] : ParseEmbeddedResource> extends ParserError ? ParseEmbeddedResource> : ParserError<'Expected embedded resource after `!inner`'> : ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` +] ? [ + { + name: Name; + original: OriginalName; + hint: Hint; + children: Fields; + }, + EatWhitespace +] : ParseEmbeddedResource> extends ParserError ? ParseEmbeddedResource> : ParserError<'Expected embedded resource after `!hint`'> : ParserError<'Expected identifier after `!`'> : ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` +] ? [ + { + name: Name; + original: OriginalName; + children: Fields; + }, + EatWhitespace +] : ParseJsonAccessor> extends [ + infer _PropertyName, + infer PropertyType, + `${infer Remainder}` +] ? [ + { + name: Name; + type: PropertyType; + }, + EatWhitespace +] : ParseEmbeddedResource> extends ParserError ? ParseEmbeddedResource> : [ + { + name: Name; + original: OriginalName; + }, + EatWhitespace +] : ParseIdentifier> : ParseEmbeddedResource> extends [infer Fields, `${infer Remainder}`] ? [ + { + name: Name; + original: Name; + children: Fields; + }, + EatWhitespace +] : ParseJsonAccessor> extends [ + infer PropertyName, + infer PropertyType, + `${infer Remainder}` +] ? [ + { + name: PropertyName; + type: PropertyType; + }, + EatWhitespace +] : ParseEmbeddedResource> extends ParserError ? ParseEmbeddedResource> : [ + { + name: Name; + original: Name; + }, + EatWhitespace +] : ParserError<`Expected identifier at \`${Input}\``>; +/** + * Parses a JSON property accessor of the shape `->a->b->c`. The last accessor in + * the series may convert to text by using the ->> operator instead of ->. + * + * Returns a tuple of ["Last property name", "Last property type", "Remainder of text"] + * or the original string input indicating that no opening `->` was found. + */ +declare type ParseJsonAccessor = Input extends `->${infer Remainder}` ? Remainder extends `>${infer Remainder}` ? ParseIdentifier extends [infer Name, `${infer Remainder}`] ? [Name, string, EatWhitespace] : ParserError<'Expected property name after `->>`'> : ParseIdentifier extends [infer Name, `${infer Remainder}`] ? ParseJsonAccessor extends [ + infer PropertyName, + infer PropertyType, + `${infer Remainder}` +] ? [PropertyName, PropertyType, EatWhitespace] : [Name, Json, EatWhitespace] : ParserError<'Expected property name after `->`'> : Input; +/** + * Parses an embedded resource, which is an opening `(`, followed by a sequence of + * nodes, separated by `,`, then a closing `)`. + * + * Returns a tuple of ["Parsed fields", "Remainder of text"], an error, + * or the original string input indicating that no opening `(` was found. + */ +declare type ParseEmbeddedResource = Input extends `(${infer Remainder}` ? ParseNodes> extends [infer Fields, `${infer Remainder}`] ? EatWhitespace extends `)${infer Remainder}` ? Fields extends [] ? ParserError<'Expected fields after `(`'> : [Fields, EatWhitespace] : ParserError<`Expected ")"`> : ParseNodes> : Input; +/** + * Parses a sequence of nodes, separated by `,`. + * + * Returns a tuple of ["Parsed fields", "Remainder of text"] or an error. + */ +declare type ParseNodes = string extends Input ? GenericStringError : ParseNodesHelper; +declare type ParseNodesHelper = ParseNode extends [ + infer Field, + `${infer Remainder}` +] ? EatWhitespace extends `,${infer Remainder}` ? ParseNodesHelper, [Field, ...Fields]> : [[Field, ...Fields], EatWhitespace] : ParseNode; +/** + * Parses a query. + * A query is a sequence of nodes, separated by `,`, ensuring that there is + * no remaining input after all nodes have been parsed. + * + * Returns an array of parsed nodes, or an error. + */ +declare type ParseQuery = string extends Query ? GenericStringError : ParseNodes> extends [infer Fields, `${infer Remainder}`] ? EatWhitespace extends '' ? Fields : ParserError<`Unexpected input: ${Remainder}`> : ParseNodes>; +declare type GetResultHelper, Relationships, Fields extends unknown[], Acc> = Fields extends [infer R] ? ConstructFieldDefinition extends SelectQueryError ? SelectQueryError : GetResultHelper & Acc> : Fields extends [infer R, ...infer Rest] ? ConstructFieldDefinition extends SelectQueryError ? SelectQueryError : GetResultHelper & Acc> : Prettify; +/** + * Constructs a type definition for an object based on a given PostgREST query. + * + * @param Row Record. + * @param Query Select query string literal to parse. + */ +export declare type GetResult, Relationships, Query extends string> = ParseQuery extends unknown[] ? GetResultHelper, unknown> : ParseQuery; +export {}; +//# sourceMappingURL=select-query-parser.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/select-query-parser.d.ts.map b/node_modules/@supabase/postgrest-js/dist/main/select-query-parser.d.ts.map new file mode 100644 index 0000000..8a02daf --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/select-query-parser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"select-query-parser.d.ts","sourceRoot":"","sources":["../../src/select-query-parser.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAEjD,aAAK,UAAU,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,CAAA;AAEnC,aAAK,aAAa,GACd,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,G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-query-parser.js b/node_modules/@supabase/postgrest-js/dist/main/select-query-parser.js new file mode 100644 index 0000000..30ede19 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/select-query-parser.js @@ -0,0 +1,4 @@ +"use strict"; +// Credits to @bnjmnt4n (https://www.npmjs.com/package/postgrest-query) +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=select-query-parser.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/select-query-parser.js.map b/node_modules/@supabase/postgrest-js/dist/main/select-query-parser.js.map new file mode 100644 index 0000000..d9cdd75 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/select-query-parser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"select-query-parser.js","sourceRoot":"","sources":["../../src/select-query-parser.ts"],"names":[],"mappings":";AAAA,uEAAuE"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/types.d.ts b/node_modules/@supabase/postgrest-js/dist/main/types.d.ts new file mode 100644 index 0000000..e239789 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/types.d.ts @@ -0,0 +1,62 @@ +export declare type Fetch = typeof fetch; +/** + * Error format + * + * {@link https://postgrest.org/en/stable/api.html?highlight=options#errors-and-http-status-codes} + */ +export declare type PostgrestError = { + message: string; + details: string; + hint: string; + code: string; +}; +/** + * Response format + * + * {@link https://github.com/supabase/supabase-js/issues/32} + */ +interface PostgrestResponseBase { + status: number; + statusText: string; +} +export interface PostgrestResponseSuccess extends PostgrestResponseBase { + error: null; + data: T; + count: number | null; +} +export interface PostgrestResponseFailure extends PostgrestResponseBase { + error: PostgrestError; + data: null; + count: null; +} +export declare type PostgrestSingleResponse = PostgrestResponseSuccess | PostgrestResponseFailure; +export declare type PostgrestMaybeSingleResponse = PostgrestSingleResponse; +export declare type PostgrestResponse = PostgrestSingleResponse; +export declare type GenericTable = { + Row: Record; + Insert: Record; + Update: Record; +}; +export declare type GenericUpdatableView = { + Row: Record; + Insert: Record; + Update: Record; +}; +export declare type GenericNonUpdatableView = { + Row: Record; +}; +export declare type GenericView = GenericUpdatableView | GenericNonUpdatableView; +export declare type GenericFunction = { + Args: Record; + Returns: unknown; +}; +export declare type GenericSchema = { + Tables: Record; + Views: Record; + Functions: Record; +}; +export declare type Prettify = { + [K in keyof T]: T[K]; +} & {}; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/types.d.ts.map b/node_modules/@supabase/postgrest-js/dist/main/types.d.ts.map new file mode 100644 index 0000000..18ed300 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,oBAAY,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC;;;;GAIG;AACH,oBAAY,cAAc,GAAG;IAC3B,OAAO,EAAE,MAAM,CAAA;IACf,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;CACb,CAAA;AAED;;;;GAIG;AACH,UAAU,qBAAqB;IAC7B,MAAM,EAAE,MAAM,CAAA;IACd,UAAU,EAAE,MAAM,CAAA;CACnB;AACD,MAAM,WAAW,wBAAwB,CAAC,CAAC,CAAE,SAAQ,qBAAqB;IACxE,KAAK,EAAE,IAAI,CAAA;IACX,IAAI,EAAE,CAAC,CAAA;IACP,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;CACrB;AACD,MAAM,WAAW,wBAAyB,SAAQ,qBAAqB;IACrE,KAAK,EAAE,cAAc,CAAA;IACrB,IAAI,EAAE,IAAI,CAAA;IACV,KAAK,EAAE,IAAI,CAAA;CACZ;AAKD,oBAAY,uBAAuB,CAAC,CAAC,IAAI,wBAAwB,CAAC,CAAC,CAAC,GAAG,wBAAwB,CAAA;AAC/F,oBAAY,4BAA4B,CAAC,CAAC,IAAI,uB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main/types.js b/node_modules/@supabase/postgrest-js/dist/main/types.js new file mode 100644 index 0000000..11e638d --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/types.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/types.js.map b/node_modules/@supabase/postgrest-js/dist/main/types.js.map new file mode 100644 index 0000000..7b5fff8 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/version.d.ts b/node_modules/@supabase/postgrest-js/dist/main/version.d.ts new file mode 100644 index 0000000..d4bb081 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "1.7.2"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/version.d.ts.map b/node_modules/@supabase/postgrest-js/dist/main/version.d.ts.map new file mode 100644 index 0000000..1f88a46 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,oBAAoB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/version.js b/node_modules/@supabase/postgrest-js/dist/main/version.js new file mode 100644 index 0000000..b77f2f9 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/version.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.version = void 0; +exports.version = '1.7.2'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/main/version.js.map b/node_modules/@supabase/postgrest-js/dist/main/version.js.map new file mode 100644 index 0000000..bf41d70 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/main/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";;;AAAa,QAAA,OAAO,GAAG,iBAAiB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestBuilder.d.ts b/node_modules/@supabase/postgrest-js/dist/module/PostgrestBuilder.d.ts new file mode 100644 index 0000000..e19cbb2 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestBuilder.d.ts @@ -0,0 +1,22 @@ +import type { Fetch, PostgrestSingleResponse } from './types'; +export default abstract class PostgrestBuilder implements PromiseLike> { + protected method: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE'; + protected url: URL; + protected headers: Record; + protected schema?: string; + protected body?: unknown; + protected shouldThrowOnError: boolean; + protected signal?: AbortSignal; + protected fetch: Fetch; + protected isMaybeSingle: boolean; + constructor(builder: PostgrestBuilder); + /** + * If there's an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + * + * {@link https://github.com/supabase/supabase-js/issues/92} + */ + throwOnError(): this; + then, TResult2 = never>(onfulfilled?: ((value: PostgrestSingleResponse) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): PromiseLike; +} +//# sourceMappingURL=PostgrestBuilder.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestBuilder.d.ts.map b/node_modules/@supabase/postgrest-js/dist/module/PostgrestBuilder.d.ts.map new file mode 100644 index 0000000..6528224 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestBuilder.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestBuilder.d.ts","sourceRoot":"","sources":["../../src/PostgrestBuilder.ts"],"names":[],"mappings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ules/@supabase/postgrest-js/dist/module/PostgrestBuilder.js new file mode 100644 index 0000000..623a74d --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestBuilder.js @@ -0,0 +1,170 @@ +import crossFetch from 'cross-fetch'; +export default class PostgrestBuilder { + constructor(builder) { + this.shouldThrowOnError = false; + this.method = builder.method; + this.url = builder.url; + this.headers = builder.headers; + this.schema = builder.schema; + this.body = builder.body; + this.shouldThrowOnError = builder.shouldThrowOnError; + this.signal = builder.signal; + this.isMaybeSingle = builder.isMaybeSingle; + if (builder.fetch) { + this.fetch = builder.fetch; + } + else if (typeof fetch === 'undefined') { + this.fetch = crossFetch; + } + else { + this.fetch = fetch; + } + } + /** + * If there's an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + * + * {@link https://github.com/supabase/supabase-js/issues/92} + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + then(onfulfilled, onrejected) { + // https://postgrest.org/en/stable/api.html#switching-schemas + if (this.schema === undefined) { + // skip + } + else if (['GET', 'HEAD'].includes(this.method)) { + this.headers['Accept-Profile'] = this.schema; + } + else { + this.headers['Content-Profile'] = this.schema; + } + if (this.method !== 'GET' && this.method !== 'HEAD') { + this.headers['Content-Type'] = 'application/json'; + } + // NOTE: Invoke w/o `this` to avoid illegal invocation error. + // https://github.com/supabase/postgrest-js/pull/247 + const _fetch = this.fetch; + let res = _fetch(this.url.toString(), { + method: this.method, + headers: this.headers, + body: JSON.stringify(this.body), + signal: this.signal, + }).then(async (res) => { + var _a, _b, _c; + let error = null; + let data = null; + let count = null; + let status = res.status; + let statusText = res.statusText; + if (res.ok) { + if (this.method !== 'HEAD') { + const body = await res.text(); + if (body === '') { + // Prefer: return=minimal + } + else if (this.headers['Accept'] === 'text/csv') { + data = body; + } + else if (this.headers['Accept'] && + this.headers['Accept'].includes('application/vnd.pgrst.plan+text')) { + data = body; + } + else { + data = JSON.parse(body); + } + } + const countHeader = (_a = this.headers['Prefer']) === null || _a === void 0 ? void 0 : _a.match(/count=(exact|planned|estimated)/); + const contentRange = (_b = res.headers.get('content-range')) === null || _b === void 0 ? void 0 : _b.split('/'); + if (countHeader && contentRange && contentRange.length > 1) { + count = parseInt(contentRange[1]); + } + // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 + // Issue persists e.g. for `.insert([...]).select().maybeSingle()` + if (this.isMaybeSingle && this.method === 'GET' && Array.isArray(data)) { + if (data.length > 1) { + error = { + // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553 + code: 'PGRST116', + details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`, + hint: null, + message: 'JSON object requested, multiple (or no) rows returned', + }; + data = null; + count = null; + status = 406; + statusText = 'Not Acceptable'; + } + else if (data.length === 1) { + data = data[0]; + } + else { + data = null; + } + } + } + else { + const body = await res.text(); + try { + error = JSON.parse(body); + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (Array.isArray(error) && res.status === 404) { + data = []; + error = null; + status = 200; + statusText = 'OK'; + } + } + catch (_d) { + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (res.status === 404 && body === '') { + status = 204; + statusText = 'No Content'; + } + else { + error = { + message: body, + }; + } + } + if (error && this.isMaybeSingle && ((_c = error === null || error === void 0 ? void 0 : error.details) === null || _c === void 0 ? void 0 : _c.includes('Results contain 0 rows'))) { + error = null; + status = 200; + statusText = 'OK'; + } + if (error && this.shouldThrowOnError) { + throw error; + } + } + const postgrestResponse = { + error, + data, + count, + status, + statusText, + }; + return postgrestResponse; + }); + if (!this.shouldThrowOnError) { + res = res.catch((fetchError) => { + var _a, _b, _c; + return ({ + error: { + message: `${(_a = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _a !== void 0 ? _a : 'FetchError'}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`, + details: `${(_b = fetchError === null || fetchError === void 0 ? void 0 : fetchError.stack) !== null && _b !== void 0 ? _b : ''}`, + hint: '', + code: `${(_c = fetchError === null || fetchError === void 0 ? void 0 : fetchError.code) !== null && _c !== void 0 ? _c : ''}`, + }, + data: null, + count: null, + status: 0, + statusText: '', + }); + }); + } + return res.then(onfulfilled, onrejected); + } +} +//# sourceMappingURL=PostgrestBuilder.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestBuilder.js.map b/node_modules/@supabase/postgrest-js/dist/module/PostgrestBuilder.js.map new file mode 100644 index 0000000..470b4ad --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestBuilder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestBuilder.js","sourceRoot":"","sources":["../../src/PostgrestBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,UAAU,MAAM,aAAa,CAAA;AAIpC,MAAM,CAAC,OAAO,OAAgB,gBAAgB;IAa5C,YAAY,OAAiC;QALnC,uBAAkB,GAAG,KAAK,CAAA;QAMlC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAA;QAC5B,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAA;QACtB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAA;QAC9B,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAA;QAC5B,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAA;QACxB,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAA;QACpD,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAA;QAC5B,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa,CAAA;QAE1C,IAAI,OAAO,CAAC,KAAK,EAAE;YACjB,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAA;SAC3B;aAAM,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;YACvC,IAAI,CAAC,KAAK,GAAG,UAAU,CAAA;SACx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AAK,GAAG,IAAI,CAAA;oBACZ,MAAM,GAAG,GAAG,CAAA;oBACZ,UAAU,GAAG,IAAI,CAAA;iBAClB;gBAED,IAAI,KAAK,IAAI,IAAI,CAAC,kBAAkB,EAAE;oBACpC,MAAM,KAAK,CAAA;iBACZ;aACF;YAED,MAAM,iBAAiB,GAAG;gBACxB,KAAK;gBACL,IAAI;gBACJ,KAAK;gBACL,MAAM;gBACN,UAAU;aACX,CAAA;YAED,OAAO,iBAAiB,CAAA;QAC1B,CAAC,CAAC,CAAA;QACF,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE;YAC5B,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,UAAU,EAAE,EAAE;;gBAAC,OAAA,CAAC;oBAC/B,KAAK,EAAE;wBACL,OAAO,EAAE,GAAG,MAAA,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,IAAI,mCAAI,YAAY,KAAK,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,OAAO,EAAE;wBACtE,OAAO,EAAE,GAAG,MAAA,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,KAAK,mCAAI,EAAE,EAAE;wBACrC,IAAI,EAAE,EAAE;wBACR,IAAI,EAAE,GAAG,MAAA,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,IAAI,mCAAI,EAAE,EAAE;qBAClC;oBACD,IAAI,EAAE,IAAI;oBACV,KAAK,EAAE,IAAI;oBACX,MAAM,EAAE,CAAC;oBACT,UAAU,EAAE,EAAE;iBACf,CAAC,CAAA;aAAA,CAAC,CAAA;SACJ;QAED,OAAO,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,UAAU,CAAC,CAAA;IAC1C,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestClient.d.ts b/node_modules/@supabase/postgrest-js/dist/module/PostgrestClient.d.ts new file mode 100644 index 0000000..bc2e06d --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestClient.d.ts @@ -0,0 +1,62 @@ +import PostgrestQueryBuilder from './PostgrestQueryBuilder'; +import PostgrestFilterBuilder from './PostgrestFilterBuilder'; +import { Fetch, GenericSchema } from './types'; +/** + * PostgREST client. + * + * @typeParam Database - Types for the schema from the [type + * generator](https://supabase.com/docs/reference/javascript/next/typescript-support) + * + * @typeParam SchemaName - Postgres schema to switch to. Must be a string + * literal, the same one passed to the constructor. If the schema is not + * `"public"`, this must be supplied manually. + */ +export default class PostgrestClient { + url: string; + headers: Record; + schema?: SchemaName; + fetch?: Fetch; + /** + * Creates a PostgREST client. + * + * @param url - URL of the PostgREST endpoint + * @param options - Named parameters + * @param options.headers - Custom headers + * @param options.schema - Postgres schema to switch to + * @param options.fetch - Custom fetch + */ + constructor(url: string, { headers, schema, fetch, }?: { + headers?: Record; + schema?: SchemaName; + fetch?: Fetch; + }); + from(relation: TableName): PostgrestQueryBuilder; + from(relation: ViewName): PostgrestQueryBuilder; + from(relation: string): PostgrestQueryBuilder; + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn: FunctionName, args?: Function_['Args'], { head, count, }?: { + head?: boolean; + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder ? Function_['Returns'][number] : never : never, Function_['Returns']>; +} +//# sourceMappingURL=PostgrestClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestClient.d.ts.map b/node_modules/@supabase/postgrest-js/dist/module/PostgrestClient.d.ts.map new file mode 100644 index 0000000..5a12fdd --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestClient.d.ts","sourceRoot":"","sources":["../../src/PostgrestClient.ts"],"names":[],"mappings":"AAAA,OAAO,qBAAqB,MAAM,yBAAyB,CAAA;AAC3D,OAAO,sBAAsB,MAAM,0BAA0B,CAAA;AAG7D,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAE9C;;;;;;;;;GASG;AACH,MAAM,CAAC,OAAO,OAAO,eAAe,CAClC,QAAQ,GAAG,GAAG,EACd,UAAU,SAAS,MAAM,GAAG,MAAM,QAAQ,GAAG,QAAQ,SAAS,MAAM,QAAQ,GACxE,QAAQ,GACR,MAAM,GAAG,MAAM,QAAQ,EAC3B,MAAM,SAAS,aAAa,GAAG,QAAQ,CAAC,UAAU,CAAC,SAAS,aAAa,GACrE,QAAQ,CAAC,UAAU,CAAC,GACpB,GAAG;IAEP,GAAG,EAAE,MAAM,CAAA;IACX,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC/B,MAAM,CAAC,EAAE,UAAU,CAAA;IACnB,KAAK,CAAC,EAAE,KAAK,CAAA;IAGb;;;;;;;;OAQG;gBAED,GAAG,EAAE,MAAM,EACX,EACE,OAAY,EACZ,MAAM,EACN,KAAK,GACN,GAAE;QACD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QAChC,MAAM,CAAC,EAAE,UAAU,CAAA;QACnB,KAAK,CAAC,EAAE,KAAK,CAAA;KACT;IAQR,IAAI,CACF,SAAS,SAAS,MAAM,GAAG,MAAM,MAAM,CAAC,QAAQ,CAAC,EACjD,KAAK,SAAS,MAAM,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,EACzC,QAAQ,EAAE,SAAS,GAAG,qBAAqB,CAAC,MAAM,EAAE,KAAK,CAAC;IAC5D,IAAI,CAAC,QAAQ,SAAS,MAAM,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,EAAE,IAAI,SAAS,MAAM,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,EAC1F,QAAQ,EAAE,QAAQ,GACjB,qBAAqB,CAAC,MAAM,EAAE,IAAI,CAAC;IACtC,IAAI,CAAC,QAAQ,EAAE,MAAM,GAAG,qBAAqB,CAAC,MAAM,EAAE,GAAG,CAAC;IAe1D;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,GAAG,CACD,YAAY,SAAS,MAAM,GAAG,MAAM,MAAM,CAAC,WAAW,CAAC,EACvD,SAAS,SAAS,MAAM,CAAC,WAAW,CAAC,CAAC,YAAY,CAAC,EAEnD,EAAE,EAAE,YAAY,EAChB,IAAI,GAAE,SAAS,CAAC,MAAM,CAAM,EAC5B,EACE,IAAY,EACZ,KAAK,GACN,GAAE;QACD,IAAI,CAAC,EAAE,OAAO,CAAA;QACd,KAAK,CAAC,EAAE,OAAO,GAAG,SAAS,GAAG,WAAW,CAAA;KACrC,GACL,sBAAsB,CACvB,MAAM,EACN,SAAS,CAAC,SAAS,CAAC,SAAS,GAAG,EAAE,GAC9B,SAAS,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC1D,SAAS,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,GAC5B,KAAK,GACP,KAAK,EACT,SAAS,CAAC,SAAS,CAAC,CACrB;CA6BF"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestClient.js b/node_modules/@supabase/postgrest-js/dist/module/PostgrestClient.js new file mode 100644 index 0000000..305ae3a --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestClient.js @@ -0,0 +1,94 @@ +import PostgrestQueryBuilder from './PostgrestQueryBuilder'; +import PostgrestFilterBuilder from './PostgrestFilterBuilder'; +import { DEFAULT_HEADERS } from './constants'; +/** + * PostgREST client. + * + * @typeParam Database - Types for the schema from the [type + * generator](https://supabase.com/docs/reference/javascript/next/typescript-support) + * + * @typeParam SchemaName - Postgres schema to switch to. Must be a string + * literal, the same one passed to the constructor. If the schema is not + * `"public"`, this must be supplied manually. + */ +export default class PostgrestClient { + // TODO: Add back shouldThrowOnError once we figure out the typings + /** + * Creates a PostgREST client. + * + * @param url - URL of the PostgREST endpoint + * @param options - Named parameters + * @param options.headers - Custom headers + * @param options.schema - Postgres schema to switch to + * @param options.fetch - Custom fetch + */ + constructor(url, { headers = {}, schema, fetch, } = {}) { + this.url = url; + this.headers = Object.assign(Object.assign({}, DEFAULT_HEADERS), headers); + this.schema = schema; + this.fetch = fetch; + } + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + const url = new URL(`${this.url}/${relation}`); + return new PostgrestQueryBuilder(url, { + headers: Object.assign({}, this.headers), + schema: this.schema, + fetch: this.fetch, + }); + } + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn, args = {}, { head = false, count, } = {}) { + let method; + const url = new URL(`${this.url}/rpc/${fn}`); + let body; + if (head) { + method = 'HEAD'; + Object.entries(args).forEach(([name, value]) => { + url.searchParams.append(name, `${value}`); + }); + } + else { + method = 'POST'; + body = args; + } + const headers = Object.assign({}, this.headers); + if (count) { + headers['Prefer'] = `count=${count}`; + } + return new PostgrestFilterBuilder({ + method, + url, + headers, + schema: this.schema, + body, + fetch: this.fetch, + allowEmpty: false, + }); + } +} +//# sourceMappingURL=PostgrestClient.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestClient.js.map b/node_modules/@supabase/postgrest-js/dist/module/PostgrestClient.js.map new file mode 100644 index 0000000..1568c87 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestClient.js","sourceRoot":"","sources":["../../src/PostgrestClient.ts"],"names":[],"mappings":"AAAA,OAAO,qBAAqB,MAAM,yBAAyB,CAAA;AAC3D,OAAO,sBAAsB,MAAM,0BAA0B,CAAA;AAE7D,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAG7C;;;;;;;;;GASG;AACH,MAAM,CAAC,OAAO,OAAO,eAAe;IAclC,mEAAmE;IACnE;;;;;;;;OAQG;IACH,YACE,GAAW,EACX,EACE,OAAO,GAAG,EAAE,EACZ,MAAM,EACN,KAAK,MAKH,EAAE;QAEN,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,OAAO,mCAAQ,eAAe,GAAK,OAAO,CAAE,CAAA;QACjD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;IAUD;;;;OAIG;IACH,IAAI,CAAC,QAAgB;QACnB,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,QAAQ,EAAE,CAAC,CAAA;QAC9C,OAAO,IAAI,qBAAqB,CAAc,GAAG,EAAE;YACjD,OAAO,oBAAO,IAAI,CAAC,OAAO,CAAE;YAC5B,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC,CAAA;IACJ,CAAC;IAED;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,GAAG,CAID,EAAgB,EAChB,OAA0B,EAAE,EAC5B,EACE,IAAI,GAAG,KAAK,EACZ,KAAK,MAIH,EAAE;QAUN,IAAI,MAAuB,CAAA;QAC3B,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,QAAQ,EAAE,EAAE,CAAC,CAAA;QAC5C,IAAI,IAAyB,CAAA;QAC7B,IAAI,IAAI,EAAE;YACR,MAAM,GAAG,MAAM,CAAA;YACf,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE,EAAE;gBAC7C,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,KAAK,EAAE,CAAC,CAAA;YAC3C,CAAC,CAAC,CAAA;SACH;aAAM;YACL,MAAM,GAAG,MAAM,CAAA;YACf,IAAI,GAAG,IAAI,CAAA;SACZ;QAED,MAAM,OAAO,qBAAQ,IAAI,CAAC,OAAO,CAAE,CAAA;QACnC,IAAI,KAAK,EAAE;YACT,OAAO,CAAC,QAAQ,CAAC,GAAG,SAAS,KAAK,EAAE,CAAA;SACrC;QAED,OAAO,IAAI,sBAAsB,CAAC;YAChC,MAAM;YACN,GAAG;YACH,OAAO;YACP,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,IAAI;YACJ,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,UAAU,EAAE,KAAK;SACmC,CAAC,CAAA;IACzD,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestFilterBuilder.d.ts b/node_modules/@supabase/postgrest-js/dist/module/PostgrestFilterBuilder.d.ts new file mode 100644 index 0000000..f6487ee --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestFilterBuilder.d.ts @@ -0,0 +1,81 @@ +import PostgrestTransformBuilder from './PostgrestTransformBuilder'; +import { GenericSchema } from './types'; +declare type FilterOperator = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'like' | 'ilike' | 'is' | 'in' | 'cs' | 'cd' | 'sl' | 'sr' | 'nxl' | 'nxr' | 'adj' | 'ov' | 'fts' | 'plfts' | 'phfts' | 'wfts'; +export default class PostgrestFilterBuilder, Result, Relationships = unknown> extends PostgrestTransformBuilder { + eq(column: ColumnName, value: Row[ColumnName]): this; + eq(column: string, value: unknown): this; + neq(column: ColumnName, value: Row[ColumnName]): this; + neq(column: string, value: unknown): this; + gt(column: ColumnName, value: Row[ColumnName]): this; + gt(column: string, value: unknown): this; + gte(column: ColumnName, value: Row[ColumnName]): this; + gte(column: string, value: unknown): this; + lt(column: ColumnName, value: Row[ColumnName]): this; + lt(column: string, value: unknown): this; + lte(column: ColumnName, value: Row[ColumnName]): this; + lte(column: string, value: unknown): this; + like(column: ColumnName, pattern: string): this; + like(column: string, pattern: string): this; + likeAllOf(column: ColumnName, patterns: string[]): this; + likeAllOf(column: string, patterns: string[]): this; + likeAnyOf(column: ColumnName, patterns: string[]): this; + likeAnyOf(column: string, patterns: string[]): this; + ilike(column: ColumnName, pattern: string): this; + ilike(column: string, pattern: string): this; + ilikeAllOf(column: ColumnName, patterns: string[]): this; + ilikeAllOf(column: string, patterns: string[]): this; + ilikeAnyOf(column: ColumnName, patterns: string[]): this; + ilikeAnyOf(column: string, patterns: string[]): this; + is(column: ColumnName, value: Row[ColumnName] & (boolean | null)): this; + is(column: string, value: boolean | null): this; + in(column: ColumnName, values: Row[ColumnName][]): this; + in(column: string, values: unknown[]): this; + contains(column: ColumnName, value: string | Row[ColumnName][] | Record): this; + contains(column: string, value: string | unknown[] | Record): this; + containedBy(column: ColumnName, value: string | Row[ColumnName][] | Record): this; + containedBy(column: string, value: string | unknown[] | Record): this; + rangeGt(column: ColumnName, range: string): this; + rangeGt(column: string, range: string): this; + rangeGte(column: ColumnName, range: string): this; + rangeGte(column: string, range: string): this; + rangeLt(column: ColumnName, range: string): this; + rangeLt(column: string, range: string): this; + rangeLte(column: ColumnName, range: string): this; + rangeLte(column: string, range: string): this; + rangeAdjacent(column: ColumnName, range: string): this; + rangeAdjacent(column: string, range: string): this; + overlaps(column: ColumnName, value: string | Row[ColumnName][]): this; + overlaps(column: string, value: string | unknown[]): this; + textSearch(column: ColumnName, query: string, options?: { + config?: string; + type?: 'plain' | 'phrase' | 'websearch'; + }): this; + textSearch(column: string, query: string, options?: { + config?: string; + type?: 'plain' | 'phrase' | 'websearch'; + }): this; + match(query: Record): this; + match(query: Record): this; + not(column: ColumnName, operator: FilterOperator, value: Row[ColumnName]): this; + not(column: string, operator: string, value: unknown): this; + /** + * Match only rows which satisfy at least one of the filters. + * + * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure it's properly sanitized. + * + * It's currently not possible to do an `.or()` filter across multiple tables. + * + * @param filters - The filters to use, following PostgREST syntax + * @param foreignTable - Set this to filter on foreign tables instead of the + * current table + */ + or(filters: string, { foreignTable }?: { + foreignTable?: string; + }): this; + filter(column: ColumnName, operator: `${'' | 'not.'}${FilterOperator}`, value: unknown): this; + filter(column: string, operator: string, value: unknown): this; +} +export {}; +//# sourceMappingURL=PostgrestFilterBuilder.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestFilterBuilder.d.ts.map b/node_modules/@supabase/postgrest-js/dist/module/PostgrestFilterBuilder.d.ts.map new file mode 100644 index 0000000..62a0da7 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestFilterBuilder.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestFilterBuilder.d.ts","sourceRoot":"","sources":["../../src/PostgrestFilterBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,yBAAyB,MAAM,6BAA6B,CAAA;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAEvC,aAAK,cAAc,GACf,IAAI,GACJ,KAAK,GACL,IAAI,GACJ,KAAK,GACL,IAAI,GACJ,KAAK,GACL,MAAM,GACN,OAAO,GACP,IAAI,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AE,MAAM,CAAA;KAAO,GAAG,IAAI;IAM3E,MAAM,CAAC,UAAU,SAAS,MAAM,GAAG,MAAM,GAAG,EAC1C,MAAM,EAAE,UAAU,EAClB,QAAQ,EAAE,GAAG,EAAE,GAAG,MAAM,GAAG,cAAc,EAAE,EAC3C,KAAK,EAAE,OAAO,GACb,IAAI;IACP,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI;CAkB/D"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestFilterBuilder.js b/node_modules/@supabase/postgrest-js/dist/module/PostgrestFilterBuilder.js new file mode 100644 index 0000000..cdc11da --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestFilterBuilder.js @@ -0,0 +1,373 @@ +import PostgrestTransformBuilder from './PostgrestTransformBuilder'; +export default class PostgrestFilterBuilder extends PostgrestTransformBuilder { + /** + * Match only rows where `column` is equal to `value`. + * + * To check if the value of `column` is NULL, you should use `.is()` instead. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + eq(column, value) { + this.url.searchParams.append(column, `eq.${value}`); + return this; + } + /** + * Match only rows where `column` is not equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + neq(column, value) { + this.url.searchParams.append(column, `neq.${value}`); + return this; + } + /** + * Match only rows where `column` is greater than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gt(column, value) { + this.url.searchParams.append(column, `gt.${value}`); + return this; + } + /** + * Match only rows where `column` is greater than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gte(column, value) { + this.url.searchParams.append(column, `gte.${value}`); + return this; + } + /** + * Match only rows where `column` is less than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lt(column, value) { + this.url.searchParams.append(column, `lt.${value}`); + return this; + } + /** + * Match only rows where `column` is less than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lte(column, value) { + this.url.searchParams.append(column, `lte.${value}`); + return this; + } + /** + * Match only rows where `column` matches `pattern` case-sensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + like(column, pattern) { + this.url.searchParams.append(column, `like.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches all of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAllOf(column, patterns) { + this.url.searchParams.append(column, `like(all).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches any of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAnyOf(column, patterns) { + this.url.searchParams.append(column, `like(any).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches `pattern` case-insensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + ilike(column, pattern) { + this.url.searchParams.append(column, `ilike.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches all of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAllOf(column, patterns) { + this.url.searchParams.append(column, `ilike(all).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches any of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAnyOf(column, patterns) { + this.url.searchParams.append(column, `ilike(any).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` IS `value`. + * + * For non-boolean columns, this is only relevant for checking if the value of + * `column` is NULL by setting `value` to `null`. + * + * For boolean columns, you can also set `value` to `true` or `false` and it + * will behave the same way as `.eq()`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + is(column, value) { + this.url.searchParams.append(column, `is.${value}`); + return this; + } + /** + * Match only rows where `column` is included in the `values` array. + * + * @param column - The column to filter on + * @param values - The values array to filter with + */ + in(column, values) { + const cleanedValues = values + .map((s) => { + // handle postgrest reserved characters + // https://postgrest.org/en/v7.0.0/api.html#reserved-characters + if (typeof s === 'string' && new RegExp('[,()]').test(s)) + return `"${s}"`; + else + return `${s}`; + }) + .join(','); + this.url.searchParams.append(column, `in.(${cleanedValues})`); + return this; + } + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * `column` contains every element appearing in `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + contains(column, value) { + if (typeof value === 'string') { + // range types can be inclusive '[', ']' or exclusive '(', ')' so just + // keep it simple and accept a string + this.url.searchParams.append(column, `cs.${value}`); + } + else if (Array.isArray(value)) { + // array + this.url.searchParams.append(column, `cs.{${value.join(',')}}`); + } + else { + // json + this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`); + } + return this; + } + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * every element appearing in `column` is contained by `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + containedBy(column, value) { + if (typeof value === 'string') { + // range + this.url.searchParams.append(column, `cd.${value}`); + } + else if (Array.isArray(value)) { + // array + this.url.searchParams.append(column, `cd.{${value.join(',')}}`); + } + else { + // json + this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`); + } + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is greater than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGt(column, range) { + this.url.searchParams.append(column, `sr.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or greater than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGte(column, range) { + this.url.searchParams.append(column, `nxl.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is less than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLt(column, range) { + this.url.searchParams.append(column, `sl.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or less than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLte(column, range) { + this.url.searchParams.append(column, `nxr.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where `column` is + * mutually exclusive to `range` and there can be no element between the two + * ranges. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeAdjacent(column, range) { + this.url.searchParams.append(column, `adj.${range}`); + return this; + } + /** + * Only relevant for array and range columns. Match only rows where + * `column` and `value` have an element in common. + * + * @param column - The array or range column to filter on + * @param value - The array or range value to filter with + */ + overlaps(column, value) { + if (typeof value === 'string') { + // range + this.url.searchParams.append(column, `ov.${value}`); + } + else { + // array + this.url.searchParams.append(column, `ov.{${value.join(',')}}`); + } + return this; + } + /** + * Only relevant for text and tsvector columns. Match only rows where + * `column` matches the query string in `query`. + * + * @param column - The text or tsvector column to filter on + * @param query - The query text to match with + * @param options - Named parameters + * @param options.config - The text search configuration to use + * @param options.type - Change how the `query` text is interpreted + */ + textSearch(column, query, { config, type } = {}) { + let typePart = ''; + if (type === 'plain') { + typePart = 'pl'; + } + else if (type === 'phrase') { + typePart = 'ph'; + } + else if (type === 'websearch') { + typePart = 'w'; + } + const configPart = config === undefined ? '' : `(${config})`; + this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`); + return this; + } + /** + * Match only rows where each column in `query` keys is equal to its + * associated value. Shorthand for multiple `.eq()`s. + * + * @param query - The object to filter with, with column names as keys mapped + * to their filter values + */ + match(query) { + Object.entries(query).forEach(([column, value]) => { + this.url.searchParams.append(column, `eq.${value}`); + }); + return this; + } + /** + * Match only rows which doesn't satisfy the filter. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to be negated to filter with, following + * PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + not(column, operator, value) { + this.url.searchParams.append(column, `not.${operator}.${value}`); + return this; + } + /** + * Match only rows which satisfy at least one of the filters. + * + * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure it's properly sanitized. + * + * It's currently not possible to do an `.or()` filter across multiple tables. + * + * @param filters - The filters to use, following PostgREST syntax + * @param foreignTable - Set this to filter on foreign tables instead of the + * current table + */ + or(filters, { foreignTable } = {}) { + const key = foreignTable ? `${foreignTable}.or` : 'or'; + this.url.searchParams.append(key, `(${filters})`); + return this; + } + /** + * Match only rows which satisfy the filter. This is an escape hatch - you + * should use the specific filter methods wherever possible. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to filter with, following PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + filter(column, operator, value) { + this.url.searchParams.append(column, `${operator}.${value}`); + return this; + } +} +//# sourceMappingURL=PostgrestFilterBuilder.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestFilterBuilder.js.map b/node_modules/@supabase/postgrest-js/dist/module/PostgrestFilterBuilder.js.map new file mode 100644 index 0000000..93d2e7a --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestFilterBuilder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestFilterBuilder.js","sourceRoot":"","sources":["../../src/PostgrestFilterBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,yBAAyB,MAAM,6BAA6B,CAAA;AA2BnE,MAAM,CAAC,OAAO,OAAO,sBAKnB,SAAQ,yBAA6D;IAGrE;;;;;;;OAOG;IACH,EAAE,CAAC,MAAc,EAAE,KAAc;QAC/B,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,KAAK,EAAE,CAAC,CAAA;QACnD,OAAO,IAAI,CAAA;IACb,CAAC;IAID;;;;;OAKG;IACH,GAAG,CAAC,MAAc,EAAE,KAAc;QACh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AM,KAAK,EAAE,CAAC,CAAA;QACrD,CAAC,CAAC,CAAA;QACF,OAAO,IAAI,CAAA;IACb,CAAC;IAQD;;;;;;;;;;;;OAYG;IACH,GAAG,CAAC,MAAc,EAAE,QAAgB,EAAE,KAAc;QAClD,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,QAAQ,IAAI,KAAK,EAAE,CAAC,CAAA;QAChE,OAAO,IAAI,CAAA;IACb,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,EAAE,CAAC,OAAe,EAAE,EAAE,YAAY,KAAgC,EAAE;QAClE,MAAM,GAAG,GAAG,YAAY,CAAC,CAAC,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,IAAI,CAAA;QACtD,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,OAAO,GAAG,CAAC,CAAA;QACjD,OAAO,IAAI,CAAA;IACb,CAAC;IAQD;;;;;;;;;;;;OAYG;IACH,MAAM,CAAC,MAAc,EAAE,QAAgB,EAAE,KAAc;QACrD,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,QAAQ,IAAI,KAAK,EAAE,CAAC,CAAA;QAC5D,OAAO,IAAI,CAAA;IACb,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestQueryBuilder.d.ts b/node_modules/@supabase/postgrest-js/dist/module/PostgrestQueryBuilder.d.ts new file mode 100644 index 0000000..ca107a8 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestQueryBuilder.d.ts @@ -0,0 +1,168 @@ +import PostgrestFilterBuilder from './PostgrestFilterBuilder'; +import { GetResult } from './select-query-parser'; +import { Fetch, GenericSchema, GenericTable, GenericView } from './types'; +export default class PostgrestQueryBuilder { + url: URL; + headers: Record; + schema?: string; + signal?: AbortSignal; + fetch?: Fetch; + constructor(url: URL, { headers, schema, fetch, }: { + headers?: Record; + schema?: string; + fetch?: Fetch; + }); + /** + * Perform a SELECT query on the table or view. + * + * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` + * + * @param options - Named parameters + * + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * + * @param options.count - Count algorithm to use to count rows in the table or view. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + select>(columns?: Query, { head, count, }?: { + head?: boolean; + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder; + /** + * Perform an INSERT into the table or view. + * + * By default, inserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to insert. Pass an object to insert a single row + * or an array to insert multiple rows. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count inserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. + */ + insert(values: Row | Row[], { count, defaultToNull, }?: { + count?: 'exact' | 'planned' | 'estimated'; + defaultToNull?: boolean; + }): PostgrestFilterBuilder; + /** + * Perform an UPSERT on the table or view. Depending on the column(s) passed + * to `onConflict`, `.upsert()` allows you to perform the equivalent of + * `.insert()` if a row with the corresponding `onConflict` columns doesn't + * exist, or if it does exist, perform an alternative action depending on + * `ignoreDuplicates`. + * + * By default, upserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to upsert with. Pass an object to upsert a + * single row or an array to upsert multiple rows. + * + * @param options - Named parameters + * + * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how + * duplicate rows are determined. Two rows are duplicates if all the + * `onConflict` columns are equal. + * + * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If + * `false`, duplicate rows are merged with existing rows. + * + * @param options.count - Count algorithm to use to count upserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. This only applies when + * inserting new rows, not when merging with existing rows under + * `ignoreDuplicates: false`. + */ + upsert(values: Row | Row[], { onConflict, ignoreDuplicates, count, defaultToNull, }?: { + onConflict?: string; + ignoreDuplicates?: boolean; + count?: 'exact' | 'planned' | 'estimated'; + defaultToNull?: boolean; + }): PostgrestFilterBuilder; + /** + * Perform an UPDATE on the table or view. + * + * By default, updated rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param values - The values to update with + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count updated rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + update(values: Row, { count, }?: { + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder; + /** + * Perform a DELETE on the table or view. + * + * By default, deleted rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count deleted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + delete({ count, }?: { + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder; +} +//# sourceMappingURL=PostgrestQueryBuilder.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestQueryBuilder.d.ts.map b/node_modules/@supabase/postgrest-js/dist/module/PostgrestQueryBuilder.d.ts.map new file mode 100644 index 0000000..df9c193 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestQueryBuilder.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestQueryBuilder.d.ts","sourceRoot":"","sources":["../../src/PostgrestQueryBuilder.ts"],"names":[],"mappings":"AACA,OAAO,sBAAsB,MAAM,0BAA0B,CAAA;AAC7D,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAA;AACjD,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAEzE,MAAM,CAAC,OAAO,OAAO,qBAAqB,CACxC,MAAM,SAAS,aAAa,EAC5B,QAAQ,SAAS,YAAY,GAAG,WAAW,EAC3C,aAAa,GAAG,QAAQ,SAAS;IAAE,aAAa,EAAE,MAAM,CAAC,CAAA;CAAE,GAAG,CAAC,GAAG,OAAO;IAEzE,GAAG,EAAE,GAAG,CAAA;IACR,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,KAAK,CAAC,EAAE,KAAK,CAAA;gBAGX,GAAG,EAAE,GAAG,EACR,EACE,OAAY,EACZ,MAAM,EACN,KAAK,GACN,EAAE;QACD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QAChC,MAAM,CAAC,EAAE,MAAM,CAAA;QACf,KAAK,CAAC,EAAE,KAAK,CAAA;KACd;IAQH;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,MAAM,CACJ,KAAK,SAAS,MAAM,GAAG,GAAG,EAC1B,SAAS,GAAG,SAAS,CAAC,MAAM,EAAE,QAAQ,CAAC,KAAK,CAAC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Q,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,aAAa,CAAC;IAoCvE;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,MAAM,CAAC,GAAG,SAAS,QAAQ,SAAS;QAAE,MAAM,EAAE,OAAO,CAAA;KAAE,GAAG,QAAQ,CAAC,QAAQ,CAAC,GAAG,KAAK,EAClF,MAAM,EAAE,GAAG,EACX,EACE,KAAK,GACN,GAAE;QACD,KAAK,CAAC,EAAE,OAAO,GAAG,SAAS,GAAG,WAAW,CAAA;KACrC,GACL,sBAAsB,CAAC,MAAM,EAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,aAAa,CAAC;IAsBvE;;;;;;;;;;;;;;;;;;OAkBG;IACH,MAAM,CAAC,EACL,KAAK,GACN,GAAE;QACD,KAAK,CAAC,EAAE,OAAO,GAAG,SAAS,GAAG,WAAW,CAAA;KACrC,GAAG,sBAAsB,CAAC,MAAM,EAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,aAAa,CAAC;CAoB9E"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestQueryBuilder.js b/node_modules/@supabase/postgrest-js/dist/module/PostgrestQueryBuilder.js new file mode 100644 index 0000000..c4c54b5 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestQueryBuilder.js @@ -0,0 +1,264 @@ +import PostgrestFilterBuilder from './PostgrestFilterBuilder'; +export default class PostgrestQueryBuilder { + constructor(url, { headers = {}, schema, fetch, }) { + this.url = url; + this.headers = headers; + this.schema = schema; + this.fetch = fetch; + } + /** + * Perform a SELECT query on the table or view. + * + * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` + * + * @param options - Named parameters + * + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * + * @param options.count - Count algorithm to use to count rows in the table or view. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + select(columns, { head = false, count, } = {}) { + const method = head ? 'HEAD' : 'GET'; + // Remove whitespaces except when quoted + let quoted = false; + const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') + .split('') + .map((c) => { + if (/\s/.test(c) && !quoted) { + return ''; + } + if (c === '"') { + quoted = !quoted; + } + return c; + }) + .join(''); + this.url.searchParams.set('select', cleanedColumns); + if (count) { + this.headers['Prefer'] = `count=${count}`; + } + return new PostgrestFilterBuilder({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: this.fetch, + allowEmpty: false, + }); + } + /** + * Perform an INSERT into the table or view. + * + * By default, inserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to insert. Pass an object to insert a single row + * or an array to insert multiple rows. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count inserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. + */ + insert(values, { count, defaultToNull = true, } = {}) { + const method = 'POST'; + const prefersHeaders = []; + if (this.headers['Prefer']) { + prefersHeaders.push(this.headers['Prefer']); + } + if (count) { + prefersHeaders.push(`count=${count}`); + } + if (!defaultToNull) { + prefersHeaders.push('missing=default'); + } + this.headers['Prefer'] = prefersHeaders.join(','); + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); + this.url.searchParams.set('columns', uniqueColumns.join(',')); + } + } + return new PostgrestFilterBuilder({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: this.fetch, + allowEmpty: false, + }); + } + /** + * Perform an UPSERT on the table or view. Depending on the column(s) passed + * to `onConflict`, `.upsert()` allows you to perform the equivalent of + * `.insert()` if a row with the corresponding `onConflict` columns doesn't + * exist, or if it does exist, perform an alternative action depending on + * `ignoreDuplicates`. + * + * By default, upserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to upsert with. Pass an object to upsert a + * single row or an array to upsert multiple rows. + * + * @param options - Named parameters + * + * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how + * duplicate rows are determined. Two rows are duplicates if all the + * `onConflict` columns are equal. + * + * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If + * `false`, duplicate rows are merged with existing rows. + * + * @param options.count - Count algorithm to use to count upserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. This only applies when + * inserting new rows, not when merging with existing rows under + * `ignoreDuplicates: false`. + */ + upsert(values, { onConflict, ignoreDuplicates = false, count, defaultToNull = true, } = {}) { + const method = 'POST'; + const prefersHeaders = [`resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates`]; + if (onConflict !== undefined) + this.url.searchParams.set('on_conflict', onConflict); + if (this.headers['Prefer']) { + prefersHeaders.push(this.headers['Prefer']); + } + if (count) { + prefersHeaders.push(`count=${count}`); + } + if (!defaultToNull) { + prefersHeaders.push('missing=default'); + } + this.headers['Prefer'] = prefersHeaders.join(','); + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); + this.url.searchParams.set('columns', uniqueColumns.join(',')); + } + } + return new PostgrestFilterBuilder({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: this.fetch, + allowEmpty: false, + }); + } + /** + * Perform an UPDATE on the table or view. + * + * By default, updated rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param values - The values to update with + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count updated rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + update(values, { count, } = {}) { + const method = 'PATCH'; + const prefersHeaders = []; + if (this.headers['Prefer']) { + prefersHeaders.push(this.headers['Prefer']); + } + if (count) { + prefersHeaders.push(`count=${count}`); + } + this.headers['Prefer'] = prefersHeaders.join(','); + return new PostgrestFilterBuilder({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: this.fetch, + allowEmpty: false, + }); + } + /** + * Perform a DELETE on the table or view. + * + * By default, deleted rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count deleted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + delete({ count, } = {}) { + const method = 'DELETE'; + const prefersHeaders = []; + if (count) { + prefersHeaders.push(`count=${count}`); + } + if (this.headers['Prefer']) { + prefersHeaders.unshift(this.headers['Prefer']); + } + this.headers['Prefer'] = prefersHeaders.join(','); + return new PostgrestFilterBuilder({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: this.fetch, + allowEmpty: false, + }); + } +} +//# sourceMappingURL=PostgrestQueryBuilder.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestQueryBuilder.js.map b/node_modules/@supabase/postgrest-js/dist/module/PostgrestQueryBuilder.js.map new file mode 100644 index 0000000..ce259d1 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestQueryBuilder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestQueryBuilder.js","sourceRoot":"","sources":["../../src/PostgrestQueryBuilder.ts"],"names":[],"mappings":"AACA,OAAO,sBAAsB,MAAM,0BAA0B,CAAA;AAI7D,MAAM,CAAC,OAAO,OAAO,qBAAqB;IAWxC,YACE,GAAQ,EACR,EACE,OAAO,GAAG,EAAE,EACZ,MAAM,EACN,KAAK,GAKN;QAED,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;IAED;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,MAAM,CAIJ,OAAe,EACf,EACE,IAAI,GAAG,KAAK,EACZ,KAAK,MAIH,EAAE;QAEN,MAAM,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAA;QACpC,wCAAwC;QACxC,IAAI,MAAM,GAAG,KAAK,CAAA;QAClB,MAAM,cAAc,GAAG,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,GAAG,CAAC;aACpC,KAAK,CAAC,EAAE,CAAC;aACT,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;YACT,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE;gBAC3B,OAAO,EAAE,CAAA;aACV;YACD,IAAI,CAAC,KAAK,GAAG,EAAE;gBACb,MAAM,GAAG,CAAC,MAAM,CAAA;aACjB;YACD,OAAO,CAAC,CAAA;QACV,CAAC,CAAC;aACD,IAAI,CAAC,EAAE,CAAC,CAAA;QACX,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAA;QACnD,IAAI,KAAK,EAAE;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der.d.ts b/node_modules/@supabase/postgrest-js/dist/module/PostgrestTransformBuilder.d.ts new file mode 100644 index 0000000..6ff34ee --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestTransformBuilder.d.ts @@ -0,0 +1,122 @@ +import PostgrestBuilder from './PostgrestBuilder'; +import { GetResult } from './select-query-parser'; +import { GenericSchema } from './types'; +export default class PostgrestTransformBuilder, Result, Relationships = unknown> extends PostgrestBuilder { + /** + * Perform a SELECT on the query result. + * + * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not + * return modified rows. By calling this method, modified rows are returned in + * `data`. + * + * @param columns - The columns to retrieve, separated by commas + */ + select>(columns?: Query): PostgrestTransformBuilder; + order(column: ColumnName, options?: { + ascending?: boolean; + nullsFirst?: boolean; + foreignTable?: undefined; + }): this; + order(column: string, options?: { + ascending?: boolean; + nullsFirst?: boolean; + foreignTable?: string; + }): this; + /** + * Limit the query result by `count`. + * + * @param count - The maximum number of rows to return + * @param options - Named parameters + * @param options.foreignTable - Set this to limit rows of foreign tables + * instead of the current table + */ + limit(count: number, { foreignTable }?: { + foreignTable?: string; + }): this; + /** + * Limit the query result by starting at an offset (`from`) and ending at the offset (`from + to`). + * Only records within this range are returned. + * This respects the query order and if there is no order clause the range could behave unexpectedly. + * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third + * and fourth rows of the query. + * + * @param from - The starting index from which to limit the result + * @param to - The last index to which to limit the result + * @param options - Named parameters + * @param options.foreignTable - Set this to limit rows of foreign tables + * instead of the current table + */ + range(from: number, to: number, { foreignTable }?: { + foreignTable?: string; + }): this; + /** + * Set the AbortSignal for the fetch request. + * + * @param signal - The AbortSignal to use for the fetch request + */ + abortSignal(signal: AbortSignal): this; + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be one row (e.g. using `.limit(1)`), otherwise this + * returns an error. + */ + single(): PostgrestBuilder; + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise + * this returns an error. + */ + maybeSingle(): PostgrestBuilder; + /** + * Return `data` as a string in CSV format. + */ + csv(): PostgrestBuilder; + /** + * Return `data` as an object in [GeoJSON](https://geojson.org) format. + */ + geojson(): PostgrestBuilder>; + /** + * Return `data` as the EXPLAIN plan for the query. + * + * @param options - Named parameters + * + * @param options.analyze - If `true`, the query will be executed and the + * actual run time will be returned + * + * @param options.verbose - If `true`, the query identifier will be returned + * and `data` will include the output columns of the query + * + * @param options.settings - If `true`, include information on configuration + * parameters that affect query planning + * + * @param options.buffers - If `true`, include information on buffer usage + * + * @param options.wal - If `true`, include information on WAL record generation + * + * @param options.format - The format of the output, can be `"text"` (default) + * or `"json"` + */ + explain({ analyze, verbose, settings, buffers, wal, format, }?: { + analyze?: boolean; + verbose?: boolean; + settings?: boolean; + buffers?: boolean; + wal?: boolean; + format?: 'json' | 'text'; + }): PostgrestBuilder[]> | PostgrestBuilder; + /** + * Rollback the query. + * + * `data` will still be returned, but the query is not committed. + */ + rollback(): this; + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + */ + returns(): PostgrestTransformBuilder; +} +//# sourceMappingURL=PostgrestTransformBuilder.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestTransformBuilder.d.ts.map b/node_modules/@supabase/postgrest-js/dist/module/PostgrestTransformBuilder.d.ts.map new file mode 100644 index 0000000..52f1323 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestTransformBuilder.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestTransformBuilder.d.ts","sourceRoot":"","sources":["../../src/PostgrestTransformBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,gBAAgB,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAA;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAEvC,MAAM,CAAC,OAAO,OAAO,yBAAyB,CAC5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G,MAAM,SAAS,CAAC,MAAM,SAAS,CAAC,EAAE,GAAG,SAAS,GAAG,KAAK,KAC/D,gBAAgB,CAAC,SAAS,CAAC;IAKhC;;;;;OAKG;IACH,WAAW,CACT,SAAS,GAAG,MAAM,SAAS,CAAC,MAAM,SAAS,CAAC,EAAE,GAAG,SAAS,GAAG,KAAK,KAC/D,gBAAgB,CAAC,SAAS,GAAG,IAAI,CAAC;IAYvC;;OAEG;IACH,GAAG,IAAI,gBAAgB,CAAC,MAAM,CAAC;IAK/B;;OAEG;IACH,OAAO,IAAI,gBAAgB,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAKpD;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,OAAO,CAAC,EACN,OAAe,EACf,OAAe,EACf,QAAgB,EAChB,OAAe,EACf,GAAW,EACX,MAAe,GAChB,GAAE;QACD,OAAO,CAAC,EAAE,OAAO,CAAA;QACjB,OAAO,CAAC,EAAE,OAAO,CAAA;QACjB,QAAQ,CAAC,EAAE,OAAO,CAAA;QAClB,OAAO,CAAC,EAAE,OAAO,CAAA;QACjB,GAAG,CAAC,EAAE,OAAO,CAAA;QACb,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;KACpB,GAAG,gBAAgB,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,GAAG,gBAAgB,CAAC,MAAM,CAAC;IAmB/E;;;;OAIG;IACH,QAAQ,IAAI,IAAI;IAShB;;;;OAIG;IACH,OAAO,CAAC,SAAS,KAAK,yBAAyB,CAAC,MAAM,EAAE,GAAG,EAAE,SAAS,EAAE,aAAa,CAAC;CAGvF"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestTransformBuilder.js b/node_modules/@supabase/postgrest-js/dist/module/PostgrestTransformBuilder.js new file mode 100644 index 0000000..1c28b7f --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestTransformBuilder.js @@ -0,0 +1,204 @@ +import PostgrestBuilder from './PostgrestBuilder'; +export default class PostgrestTransformBuilder extends PostgrestBuilder { + /** + * Perform a SELECT on the query result. + * + * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not + * return modified rows. By calling this method, modified rows are returned in + * `data`. + * + * @param columns - The columns to retrieve, separated by commas + */ + select(columns) { + // Remove whitespaces except when quoted + let quoted = false; + const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') + .split('') + .map((c) => { + if (/\s/.test(c) && !quoted) { + return ''; + } + if (c === '"') { + quoted = !quoted; + } + return c; + }) + .join(''); + this.url.searchParams.set('select', cleanedColumns); + if (this.headers['Prefer']) { + this.headers['Prefer'] += ','; + } + this.headers['Prefer'] += 'return=representation'; + return this; + } + /** + * Order the query result by `column`. + * + * You can call this method multiple times to order by multiple columns. + * + * You can order foreign tables, but it doesn't affect the ordering of the + * current table. + * + * @param column - The column to order by + * @param options - Named parameters + * @param options.ascending - If `true`, the result will be in ascending order + * @param options.nullsFirst - If `true`, `null`s appear first. If `false`, + * `null`s appear last. + * @param options.foreignTable - Set this to order a foreign table by foreign + * columns + */ + order(column, { ascending = true, nullsFirst, foreignTable, } = {}) { + const key = foreignTable ? `${foreignTable}.order` : 'order'; + const existingOrder = this.url.searchParams.get(key); + this.url.searchParams.set(key, `${existingOrder ? `${existingOrder},` : ''}${column}.${ascending ? 'asc' : 'desc'}${nullsFirst === undefined ? '' : nullsFirst ? '.nullsfirst' : '.nullslast'}`); + return this; + } + /** + * Limit the query result by `count`. + * + * @param count - The maximum number of rows to return + * @param options - Named parameters + * @param options.foreignTable - Set this to limit rows of foreign tables + * instead of the current table + */ + limit(count, { foreignTable } = {}) { + const key = typeof foreignTable === 'undefined' ? 'limit' : `${foreignTable}.limit`; + this.url.searchParams.set(key, `${count}`); + return this; + } + /** + * Limit the query result by starting at an offset (`from`) and ending at the offset (`from + to`). + * Only records within this range are returned. + * This respects the query order and if there is no order clause the range could behave unexpectedly. + * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third + * and fourth rows of the query. + * + * @param from - The starting index from which to limit the result + * @param to - The last index to which to limit the result + * @param options - Named parameters + * @param options.foreignTable - Set this to limit rows of foreign tables + * instead of the current table + */ + range(from, to, { foreignTable } = {}) { + const keyOffset = typeof foreignTable === 'undefined' ? 'offset' : `${foreignTable}.offset`; + const keyLimit = typeof foreignTable === 'undefined' ? 'limit' : `${foreignTable}.limit`; + this.url.searchParams.set(keyOffset, `${from}`); + // Range is inclusive, so add 1 + this.url.searchParams.set(keyLimit, `${to - from + 1}`); + return this; + } + /** + * Set the AbortSignal for the fetch request. + * + * @param signal - The AbortSignal to use for the fetch request + */ + abortSignal(signal) { + this.signal = signal; + return this; + } + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be one row (e.g. using `.limit(1)`), otherwise this + * returns an error. + */ + single() { + this.headers['Accept'] = 'application/vnd.pgrst.object+json'; + return this; + } + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise + * this returns an error. + */ + maybeSingle() { + // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 + // Issue persists e.g. for `.insert([...]).select().maybeSingle()` + if (this.method === 'GET') { + this.headers['Accept'] = 'application/json'; + } + else { + this.headers['Accept'] = 'application/vnd.pgrst.object+json'; + } + this.isMaybeSingle = true; + return this; + } + /** + * Return `data` as a string in CSV format. + */ + csv() { + this.headers['Accept'] = 'text/csv'; + return this; + } + /** + * Return `data` as an object in [GeoJSON](https://geojson.org) format. + */ + geojson() { + this.headers['Accept'] = 'application/geo+json'; + return this; + } + /** + * Return `data` as the EXPLAIN plan for the query. + * + * @param options - Named parameters + * + * @param options.analyze - If `true`, the query will be executed and the + * actual run time will be returned + * + * @param options.verbose - If `true`, the query identifier will be returned + * and `data` will include the output columns of the query + * + * @param options.settings - If `true`, include information on configuration + * parameters that affect query planning + * + * @param options.buffers - If `true`, include information on buffer usage + * + * @param options.wal - If `true`, include information on WAL record generation + * + * @param options.format - The format of the output, can be `"text"` (default) + * or `"json"` + */ + explain({ analyze = false, verbose = false, settings = false, buffers = false, wal = false, format = 'text', } = {}) { + const options = [ + analyze ? 'analyze' : null, + verbose ? 'verbose' : null, + settings ? 'settings' : null, + buffers ? 'buffers' : null, + wal ? 'wal' : null, + ] + .filter(Boolean) + .join('|'); + // An Accept header can carry multiple media types but postgrest-js always sends one + const forMediatype = this.headers['Accept']; + this.headers['Accept'] = `application/vnd.pgrst.plan+${format}; for="${forMediatype}"; options=${options};`; + if (format === 'json') + return this; + else + return this; + } + /** + * Rollback the query. + * + * `data` will still be returned, but the query is not committed. + */ + rollback() { + var _a; + if (((_a = this.headers['Prefer']) !== null && _a !== void 0 ? _a : '').trim().length > 0) { + this.headers['Prefer'] += ',tx=rollback'; + } + else { + this.headers['Prefer'] = 'tx=rollback'; + } + return this; + } + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + */ + returns() { + return this; + } +} +//# sourceMappingURL=PostgrestTransformBuilder.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/PostgrestTransformBuilder.js.map b/node_modules/@supabase/postgrest-js/dist/module/PostgrestTransformBuilder.js.map new file mode 100644 index 0000000..01d88fd --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/PostgrestTransformBuilder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"PostgrestTransformBuilder.js","sourceRoot":"","sources":["../../src/PostgrestTransformBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,gBAAgB,MAAM,oBAAoB,CAAA;AAIjD,MAAM,CAAC,OAAO,OAAO,yBAKnB,SAAQ,gBAAwB;IAChC;;;;;;;;OAQG;IACH,MAAM,CACJ,OAAe;QAEf,wCAAwC;QACxC,IAAI,MAAM,GAAG,KAAK,CAAA;QAClB,MAAM,cAAc,GAAG,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,GAAG,CAAC;aACpC,KAAK,CAAC,EAAE,CAAC;aACT,G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AC,CAAA;QAC3C,IAAI,CAAC,OAAO,CACV,QAAQ,CACT,GAAG,8BAA8B,MAAM,UAAU,YAAY,cAAc,OAAO,GAAG,CAAA;QACtF,IAAI,MAAM,KAAK,MAAM;YAAE,OAAO,IAAmD,CAAA;;YAC5E,OAAO,IAAgC,CAAA;IAC9C,CAAC;IAED;;;;OAIG;IACH,QAAQ;;QACN,IAAI,CAAC,MAAA,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,mCAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,EAAE;YACpD,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,cAAc,CAAA;SACzC;aAAM;YACL,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,aAAa,CAAA;SACvC;QACD,OAAO,IAAI,CAAA;IACb,CAAC;IAED;;;;OAIG;IACH,OAAO;QACL,OAAO,IAAmF,CAAA;IAC5F,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/constants.d.ts b/node_modules/@supabase/postgrest-js/dist/module/constants.d.ts new file mode 100644 index 0000000..12eb562 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/constants.d.ts @@ -0,0 +1,4 @@ +export declare const DEFAULT_HEADERS: { + 'X-Client-Info': string; +}; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/constants.d.ts.map b/node_modules/@supabase/postgrest-js/dist/module/constants.d.ts.map new file mode 100644 index 0000000..68e5791 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,eAAe;;CAAiD,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/constants.js b/node_modules/@supabase/postgrest-js/dist/module/constants.js new file mode 100644 index 0000000..2dd1bb9 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/constants.js @@ -0,0 +1,3 @@ +import { version } from './version'; +export const DEFAULT_HEADERS = { 'X-Client-Info': `postgrest-js/${version}` }; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/constants.js.map b/node_modules/@supabase/postgrest-js/dist/module/constants.js.map new file mode 100644 index 0000000..beb92b0 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACnC,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,eAAe,EAAE,gBAAgB,OAAO,EAAE,EAAE,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/index.d.ts b/node_modules/@supabase/postgrest-js/dist/module/index.d.ts new file mode 100644 index 0000000..8400a73 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/index.d.ts @@ -0,0 +1,7 @@ +export { default as PostgrestClient } from './PostgrestClient'; +export { default as PostgrestQueryBuilder } from './PostgrestQueryBuilder'; +export { default as PostgrestFilterBuilder } from './PostgrestFilterBuilder'; +export { default as PostgrestTransformBuilder } from './PostgrestTransformBuilder'; +export { default as PostgrestBuilder } from './PostgrestBuilder'; +export { PostgrestResponse, PostgrestResponseFailure, PostgrestResponseSuccess, PostgrestSingleResponse, PostgrestMaybeSingleResponse, PostgrestError, } from './types'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/index.d.ts.map b/node_modules/@supabase/postgrest-js/dist/module/index.d.ts.map new file mode 100644 index 0000000..96ed024 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAC9D,OAAO,EAAE,OAAO,IAAI,qBAAqB,EAAE,MAAM,yBAAyB,CAAA;AAC1E,OAAO,EAAE,OAAO,IAAI,sBAAsB,EAAE,MAAM,0BAA0B,CAAA;AAC5E,OAAO,EAAE,OAAO,IAAI,yBAAyB,EAAE,MAAM,6BAA6B,CAAA;AAClF,OAAO,EAAE,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AAChE,OAAO,EACL,iBAAiB,EACjB,wBAAwB,EACxB,wBAAwB,EACxB,uBAAuB,EACvB,4BAA4B,EAC5B,cAAc,GACf,MAAM,SAAS,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/index.js b/node_modules/@supabase/postgrest-js/dist/module/index.js new file mode 100644 index 0000000..f4e8ee6 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/index.js @@ -0,0 +1,6 @@ +export { default as PostgrestClient } from './PostgrestClient'; +export { default as PostgrestQueryBuilder } from './PostgrestQueryBuilder'; +export { default as PostgrestFilterBuilder } from './PostgrestFilterBuilder'; +export { default as PostgrestTransformBuilder } from './PostgrestTransformBuilder'; +export { default as PostgrestBuilder } from './PostgrestBuilder'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/index.js.map b/node_modules/@supabase/postgrest-js/dist/module/index.js.map new file mode 100644 index 0000000..87e0795 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAC9D,OAAO,EAAE,OAAO,IAAI,qBAAqB,EAAE,MAAM,yBAAyB,CAAA;AAC1E,OAAO,EAAE,OAAO,IAAI,sBAAsB,EAAE,MAAM,0BAA0B,CAAA;AAC5E,OAAO,EAAE,OAAO,IAAI,yBAAyB,EAAE,MAAM,6BAA6B,CAAA;AAClF,OAAO,EAAE,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/select-query-parser.d.ts b/node_modules/@supabase/postgrest-js/dist/module/select-query-parser.d.ts new file mode 100644 index 0000000..f1733bc --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/select-query-parser.d.ts @@ -0,0 +1,272 @@ +import { GenericSchema, Prettify } from './types'; +declare type Whitespace = ' ' | '\n' | '\t'; +declare type LowerAlphabet = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z'; +declare type Alphabet = LowerAlphabet | Uppercase; +declare type Digit = '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '0'; +declare type Letter = Alphabet | Digit | '_'; +declare type Json = string | number | boolean | null | { + [key: string]: Json; +} | Json[]; +/** + * Parser errors. + */ +declare type ParserError = { + error: true; +} & Message; +declare type GenericStringError = ParserError<'Received a generic string'>; +export declare type SelectQueryError = { + error: true; +} & Message; +/** + * Trims whitespace from the left of the input. + */ +declare type EatWhitespace = string extends Input ? GenericStringError : Input extends `${Whitespace}${infer Remainder}` ? EatWhitespace : Input; +declare type HasFKey = Relationships extends [infer R] ? R extends { + foreignKeyName: FKeyName; +} ? true : false : Relationships extends [infer R, ...infer Rest] ? HasFKey extends true ? true : HasFKey : false; +declare type HasFKeyToFRel = Relationships extends [infer R] ? R extends { + referencedRelation: FRelName; +} ? true : false : Relationships extends [infer R, ...infer Rest] ? HasFKeyToFRel extends true ? true : HasFKeyToFRel : false; +/** + * Constructs a type definition for a single field of an object. + * + * @param Definitions Record of definitions, possibly generated from PostgREST's OpenAPI spec. + * @param Name Name of the table being queried. + * @param Field Single field parsed by `ParseQuery`. + */ +declare type ConstructFieldDefinition, Relationships, Field> = Field extends { + star: true; +} ? Row : Field extends { + name: string; + original: string; + hint: string; + children: unknown[]; +} ? { + [_ in Field['name']]: GetResultHelper extends infer Child ? Relationships extends unknown[] ? HasFKey extends true ? Child | null : Child[] : Child[] : never; +} : Field extends { + name: string; + original: string; + children: unknown[]; +} ? { + [_ in Field['name']]: GetResultHelper extends infer Child ? Relationships extends unknown[] ? HasFKeyToFRel extends true ? Child | null : Child[] : Child[] : never; +} : Field extends { + name: string; + original: string; +} ? Field['original'] extends keyof Row ? { + [K in Field['name']]: Row[Field['original']]; +} : SelectQueryError<`Referencing missing column \`${Field['original']}\``> : Field extends { + name: string; + type: infer T; +} ? { + [K in Field['name']]: T; +} : Record; +/** + * Notes: all `Parse*` types assume that their input strings have their whitespace + * removed. They return tuples of ["Return Value", "Remainder of text"] or + * a `ParserError`. + */ +/** + * Reads a consecutive sequence of more than 1 letter, + * where letters are `[0-9a-zA-Z_]`. + */ +declare type ReadLetters = string extends Input ? GenericStringError : ReadLettersHelper extends [`${infer Letters}`, `${infer Remainder}`] ? Letters extends '' ? ParserError<`Expected letter at \`${Input}\``> : [Letters, Remainder] : ReadLettersHelper; +declare type ReadLettersHelper = string extends Input ? GenericStringError : Input extends `${infer L}${infer Remainder}` ? L extends Letter ? ReadLettersHelper : [Acc, Input] : [Acc, '']; +/** + * Reads a consecutive sequence of more than 1 double-quoted letters, + * where letters are `[^"]`. + */ +declare type ReadQuotedLetters = string extends Input ? GenericStringError : Input extends `"${infer Remainder}` ? ReadQuotedLettersHelper extends [`${infer Letters}`, `${infer Remainder}`] ? Letters extends '' ? ParserError<`Expected string at \`${Remainder}\``> : [Letters, Remainder] : ReadQuotedLettersHelper : ParserError<`Not a double-quoted string at \`${Input}\``>; +declare type ReadQuotedLettersHelper = string extends Input ? GenericStringError : Input extends `${infer L}${infer Remainder}` ? L extends '"' ? [Acc, Remainder] : ReadQuotedLettersHelper : ParserError<`Missing closing double-quote in \`"${Acc}${Input}\``>; +/** + * Parses a (possibly double-quoted) identifier. + * For now, identifiers are just sequences of more than 1 letter. + */ +declare type ParseIdentifier = ReadLetters extends [ + infer Name, + `${infer Remainder}` +] ? [Name, `${Remainder}`] : ReadQuotedLetters extends [infer Name, `${infer Remainder}`] ? [Name, `${Remainder}`] : ParserError<`No (possibly double-quoted) identifier at \`${Input}\``>; +/** + * Parses a node. + * A node is one of the following: + * - `*` + * - `field` + * - `field->json...` + * - `field(nodes)` + * - `field!hint(nodes)` + * - `field!inner(nodes)` + * - `field!hint!inner(nodes)` + * - `renamed_field:field` + * - `renamed_field:field->json...` + * - `renamed_field:field(nodes)` + * - `renamed_field:field!hint(nodes)` + * - `renamed_field:field!inner(nodes)` + * - `renamed_field:field!hint!inner(nodes)` + * + * TODO: casting operators `::text`, more support for JSON operators `->`, `->>`. + */ +declare type ParseNode = Input extends '' ? ParserError<'Empty string'> : Input extends `*${infer Remainder}` ? [{ + star: true; +}, EatWhitespace] : ParseIdentifier extends [infer Name, `${infer Remainder}`] ? EatWhitespace extends `!inner${infer Remainder}` ? ParseEmbeddedResource> extends [infer Fields, `${infer Remainder}`] ? [ + { + name: Name; + original: Name; + children: Fields; + }, + EatWhitespace +] : ParseEmbeddedResource> extends ParserError ? ParseEmbeddedResource> : ParserError<'Expected embedded resource after `!inner`'> : EatWhitespace extends `!${infer Remainder}` ? ParseIdentifier> extends [infer Hint, `${infer Remainder}`] ? EatWhitespace extends `!inner${infer Remainder}` ? ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` +] ? [ + { + name: Name; + original: Name; + hint: Hint; + children: Fields; + }, + EatWhitespace +] : ParseEmbeddedResource> extends ParserError ? ParseEmbeddedResource> : ParserError<'Expected embedded resource after `!inner`'> : ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` +] ? [ + { + name: Name; + original: Name; + hint: Hint; + children: Fields; + }, + EatWhitespace +] : ParseEmbeddedResource> extends ParserError ? ParseEmbeddedResource> : ParserError<'Expected embedded resource after `!hint`'> : ParserError<'Expected identifier after `!`'> : EatWhitespace extends `:${infer Remainder}` ? ParseIdentifier> extends [infer OriginalName, `${infer Remainder}`] ? EatWhitespace extends `!inner${infer Remainder}` ? ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` +] ? [ + { + name: Name; + original: OriginalName; + children: Fields; + }, + EatWhitespace +] : ParseEmbeddedResource> extends ParserError ? ParseEmbeddedResource> : ParserError<'Expected embedded resource after `!inner`'> : EatWhitespace extends `!${infer Remainder}` ? ParseIdentifier> extends [infer Hint, `${infer Remainder}`] ? EatWhitespace extends `!inner${infer Remainder}` ? ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` +] ? [ + { + name: Name; + original: OriginalName; + hint: Hint; + children: Fields; + }, + EatWhitespace +] : ParseEmbeddedResource> extends ParserError ? ParseEmbeddedResource> : ParserError<'Expected embedded resource after `!inner`'> : ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` +] ? [ + { + name: Name; + original: OriginalName; + hint: Hint; + children: Fields; + }, + EatWhitespace +] : ParseEmbeddedResource> extends ParserError ? ParseEmbeddedResource> : ParserError<'Expected embedded resource after `!hint`'> : ParserError<'Expected identifier after `!`'> : ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` +] ? [ + { + name: Name; + original: OriginalName; + children: Fields; + }, + EatWhitespace +] : ParseJsonAccessor> extends [ + infer _PropertyName, + infer PropertyType, + `${infer Remainder}` +] ? [ + { + name: Name; + type: PropertyType; + }, + EatWhitespace +] : ParseEmbeddedResource> extends ParserError ? ParseEmbeddedResource> : [ + { + name: Name; + original: OriginalName; + }, + EatWhitespace +] : ParseIdentifier> : ParseEmbeddedResource> extends [infer Fields, `${infer Remainder}`] ? [ + { + name: Name; + original: Name; + children: Fields; + }, + EatWhitespace +] : ParseJsonAccessor> extends [ + infer PropertyName, + infer PropertyType, + `${infer Remainder}` +] ? [ + { + name: PropertyName; + type: PropertyType; + }, + EatWhitespace +] : ParseEmbeddedResource> extends ParserError ? ParseEmbeddedResource> : [ + { + name: Name; + original: Name; + }, + EatWhitespace +] : ParserError<`Expected identifier at \`${Input}\``>; +/** + * Parses a JSON property accessor of the shape `->a->b->c`. The last accessor in + * the series may convert to text by using the ->> operator instead of ->. + * + * Returns a tuple of ["Last property name", "Last property type", "Remainder of text"] + * or the original string input indicating that no opening `->` was found. + */ +declare type ParseJsonAccessor = Input extends `->${infer Remainder}` ? Remainder extends `>${infer Remainder}` ? ParseIdentifier extends [infer Name, `${infer Remainder}`] ? [Name, string, EatWhitespace] : ParserError<'Expected property name after `->>`'> : ParseIdentifier extends [infer Name, `${infer Remainder}`] ? ParseJsonAccessor extends [ + infer PropertyName, + infer PropertyType, + `${infer Remainder}` +] ? [PropertyName, PropertyType, EatWhitespace] : [Name, Json, EatWhitespace] : ParserError<'Expected property name after `->`'> : Input; +/** + * Parses an embedded resource, which is an opening `(`, followed by a sequence of + * nodes, separated by `,`, then a closing `)`. + * + * Returns a tuple of ["Parsed fields", "Remainder of text"], an error, + * or the original string input indicating that no opening `(` was found. + */ +declare type ParseEmbeddedResource = Input extends `(${infer Remainder}` ? ParseNodes> extends [infer Fields, `${infer Remainder}`] ? EatWhitespace extends `)${infer Remainder}` ? Fields extends [] ? ParserError<'Expected fields after `(`'> : [Fields, EatWhitespace] : ParserError<`Expected ")"`> : ParseNodes> : Input; +/** + * Parses a sequence of nodes, separated by `,`. + * + * Returns a tuple of ["Parsed fields", "Remainder of text"] or an error. + */ +declare type ParseNodes = string extends Input ? GenericStringError : ParseNodesHelper; +declare type ParseNodesHelper = ParseNode extends [ + infer Field, + `${infer Remainder}` +] ? EatWhitespace extends `,${infer Remainder}` ? ParseNodesHelper, [Field, ...Fields]> : [[Field, ...Fields], EatWhitespace] : ParseNode; +/** + * Parses a query. + * A query is a sequence of nodes, separated by `,`, ensuring that there is + * no remaining input after all nodes have been parsed. + * + * Returns an array of parsed nodes, or an error. + */ +declare type ParseQuery = string extends Query ? GenericStringError : ParseNodes> extends [infer Fields, `${infer Remainder}`] ? EatWhitespace extends '' ? Fields : ParserError<`Unexpected input: ${Remainder}`> : ParseNodes>; +declare type GetResultHelper, Relationships, Fields extends unknown[], Acc> = Fields extends [infer R] ? ConstructFieldDefinition extends SelectQueryError ? SelectQueryError : GetResultHelper & Acc> : Fields extends [infer R, ...infer Rest] ? ConstructFieldDefinition extends SelectQueryError ? SelectQueryError : GetResultHelper & Acc> : Prettify; +/** + * Constructs a type definition for an object based on a given PostgREST query. + * + * @param Row Record. + * @param Query Select query string literal to parse. + */ +export declare type GetResult, Relationships, Query extends string> = ParseQuery extends unknown[] ? GetResultHelper, unknown> : ParseQuery; +export {}; +//# sourceMappingURL=select-query-parser.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/select-query-parser.d.ts.map b/node_modules/@supabase/postgrest-js/dist/module/select-query-parser.d.ts.map new file mode 100644 index 0000000..8a02daf --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/select-query-parser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"select-query-parser.d.ts","sourceRoot":"","sources":["../../src/select-query-parser.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAEjD,aAAK,UAAU,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,CAAA;AAEnC,aAAK,aAAa,GACd,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,CAAA;A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AC,GACxB,wBAAwB,CAAC,MAAM,EAAE,GAAG,EAAE,aAAa,EAAE,CAAC,CAAC,SAAS,gBAAgB,CAAC,MAAM,CAAC,CAAC,GACvF,gBAAgB,CAAC,CAAC,CAAC,GACnB,eAAe,CACb,MAAM,EACN,GAAG,EACH,aAAa,EACb;CAAE,EACF,wBAAwB,CAAC,MAAM,EAAE,GAAG,EAAE,aAAa,EAAE,CAAC,CAAC,GAAG,GAAG,CAC9D,GACH,MAAM,SAAS,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,IAAI,CAAC,GACvC,wBAAwB,CAAC,MAAM,EAAE,GAAG,EAAE,aAAa,EAAE,CAAC,CAAC,SAAS,gBAAgB,CAAC,MAAM,CAAC,CAAC,GACvF,gBAAgB,CAAC,CAAC,CAAC,GACnB,eAAe,CACb,MAAM,EACN,GAAG,EACH,aAAa,EACb,IAAI,EACJ,wBAAwB,CAAC,MAAM,EAAE,GAAG,EAAE,aAAa,EAAE,CAAC,CAAC,GAAG,GAAG,CAC9D,GACH,QAAQ,CAAC,GAAG,CAAC,CAAA;AAEjB;;;;;GAKG;AACH,oBAAY,SAAS,CACnB,MAAM,SAAS,aAAa,EAC5B,GAAG,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACnC,aAAa,EACb,KAAK,SAAS,MAAM,IAClB,UAAU,CAAC,KAAK,CAAC,SAAS,OAAO,EAAE,GACnC,eAAe,CAAC,MAAM,EAAE,GAAG,EAAE,aAAa,EAAE,UAAU,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,GACvE,UAAU,CAAC,KAAK,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/select-query-parser.js b/node_modules/@supabase/postgrest-js/dist/module/select-query-parser.js new file mode 100644 index 0000000..65a4bcf --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/select-query-parser.js @@ -0,0 +1,3 @@ +// Credits to @bnjmnt4n (https://www.npmjs.com/package/postgrest-query) +export {}; +//# sourceMappingURL=select-query-parser.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/select-query-parser.js.map b/node_modules/@supabase/postgrest-js/dist/module/select-query-parser.js.map new file mode 100644 index 0000000..c1b1e15 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/select-query-parser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"select-query-parser.js","sourceRoot":"","sources":["../../src/select-query-parser.ts"],"names":[],"mappings":"AAAA,uEAAuE"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/types.d.ts b/node_modules/@supabase/postgrest-js/dist/module/types.d.ts new file mode 100644 index 0000000..e239789 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/types.d.ts @@ -0,0 +1,62 @@ +export declare type Fetch = typeof fetch; +/** + * Error format + * + * {@link https://postgrest.org/en/stable/api.html?highlight=options#errors-and-http-status-codes} + */ +export declare type PostgrestError = { + message: string; + details: string; + hint: string; + code: string; +}; +/** + * Response format + * + * {@link https://github.com/supabase/supabase-js/issues/32} + */ +interface PostgrestResponseBase { + status: number; + statusText: string; +} +export interface PostgrestResponseSuccess extends PostgrestResponseBase { + error: null; + data: T; + count: number | null; +} +export interface PostgrestResponseFailure extends PostgrestResponseBase { + error: PostgrestError; + data: null; + count: null; +} +export declare type PostgrestSingleResponse = PostgrestResponseSuccess | PostgrestResponseFailure; +export declare type PostgrestMaybeSingleResponse = PostgrestSingleResponse; +export declare type PostgrestResponse = PostgrestSingleResponse; +export declare type GenericTable = { + Row: Record; + Insert: Record; + Update: Record; +}; +export declare type GenericUpdatableView = { + Row: Record; + Insert: Record; + Update: Record; +}; +export declare type GenericNonUpdatableView = { + Row: Record; +}; +export declare type GenericView = GenericUpdatableView | GenericNonUpdatableView; +export declare type GenericFunction = { + Args: Record; + Returns: unknown; +}; +export declare type GenericSchema = { + Tables: Record; + Views: Record; + Functions: Record; +}; +export declare type Prettify = { + [K in keyof T]: T[K]; +} & {}; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/types.d.ts.map b/node_modules/@supabase/postgrest-js/dist/module/types.d.ts.map new file mode 100644 index 0000000..18ed300 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,oBAAY,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC;;;;GAIG;AACH,oBAAY,cAAc,GAAG;IAC3B,OAAO,EAAE,MAAM,CAAA;IACf,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;CACb,CAAA;AAED;;;;GAIG;AACH,UAAU,qBAAqB;IAC7B,MAAM,EAAE,MAAM,CAAA;IACd,UAAU,EAAE,MAAM,CAAA;CACnB;AACD,MAAM,WAAW,wBAAwB,CAAC,CAAC,CAAE,SAAQ,qBAAqB;IACxE,KAAK,EAAE,IAAI,CAAA;IACX,IAAI,EAAE,CAAC,CAAA;IACP,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;CACrB;AACD,MAAM,WAAW,wBAAyB,SAAQ,qBAAqB;IACrE,KAAK,EAAE,cAAc,CAAA;IACrB,IAAI,EAAE,IAAI,CAAA;IACV,KAAK,EAAE,IAAI,CAAA;CACZ;AAKD,oBAAY,uBAAuB,CAAC,CAAC,IAAI,wBAAwB,CAAC,CAAC,CAAC,GAAG,wBAAwB,CAAA;AAC/F,oBAAY,4BAA4B,CAAC,CAAC,IAAI,uBAAuB,CAAC,CAAC,GAAG,IAAI,CAAC,CAAA;AAC/E,oBAAY,iBAAiB,CAAC,CAAC,IAAI,uBAAuB,CAAC,CAAC,EAAE,CAAC,CAAA;AAE/D,oBAAY,YAAY,GAAG;IACzB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC5B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAChC,CAAA;AAED,oBAAY,oBAAoB,GAAG;IACjC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC5B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAChC,CAAA;AAED,oBAAY,uBAAuB,GAAG;IACpC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAC7B,CAAA;AAED,oBAAY,WAAW,GAAG,oBAAoB,GAAG,uBAAuB,CAAA;AAExE,oBAAY,eAAe,GAAG;IAC5B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC7B,OAAO,EAAE,OAAO,CAAA;CACjB,CAAA;AAED,oBAAY,aAAa,GAAG;IAC1B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAA;IACpC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAA;IAClC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAA;CAC3C,CAAA;AAGD,oBAAY,QAAQ,CAAC,CAAC,IAAI;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CAAE,GAAG,EAAE,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/types.js b/node_modules/@supabase/postgrest-js/dist/module/types.js new file mode 100644 index 0000000..718fd38 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/types.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/types.js.map b/node_modules/@supabase/postgrest-js/dist/module/types.js.map new file mode 100644 index 0000000..7b5fff8 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/version.d.ts b/node_modules/@supabase/postgrest-js/dist/module/version.d.ts new file mode 100644 index 0000000..d4bb081 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "1.7.2"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/version.d.ts.map b/node_modules/@supabase/postgrest-js/dist/module/version.d.ts.map new file mode 100644 index 0000000..1f88a46 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,oBAAoB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/version.js b/node_modules/@supabase/postgrest-js/dist/module/version.js new file mode 100644 index 0000000..a5d6a47 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/version.js @@ -0,0 +1,2 @@ +export const version = '1.7.2'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/dist/module/version.js.map b/node_modules/@supabase/postgrest-js/dist/module/version.js.map new file mode 100644 index 0000000..c32bfe4 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/dist/module/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,iBAAiB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/postgrest-js/package.json b/node_modules/@supabase/postgrest-js/package.json new file mode 100644 index 0000000..27a85ea --- /dev/null +++ b/node_modules/@supabase/postgrest-js/package.json @@ -0,0 +1,54 @@ +{ + "name": "@supabase/postgrest-js", + "version": "1.7.2", + "description": "Isomorphic PostgREST client", + "keywords": [ + "postgrest", + "supabase" + ], + "homepage": "https://github.com/supabase/postgrest-js", + "bugs": "https://github.com/supabase/postgrest-js/issues", + "license": "MIT", + "author": "Supabase", + "files": [ + "dist", + "src" + ], + "main": "dist/main/index.js", + "module": "dist/module/index.js", + "types": "dist/module/index.d.ts", + "repository": "supabase/postgrest-js", + "scripts": { + "clean": "rimraf dist docs/v2", + "format": "prettier --write \"{src,test}/**/*.ts\"", + "format:check": "prettier --check \"{src,test}/**/*.ts\"", + "build": "run-s clean format build:*", + "build:main": "tsc -p tsconfig.json", + "build:module": "tsc -p tsconfig.module.json", + "docs": "typedoc src/index.ts --out docs/v2", + "docs:json": "typedoc --json docs/v2/spec.json --excludeExternals src/index.ts", + "test": "run-s format:check test:types db:clean db:run test:run db:clean", + "test:run": "jest --runInBand", + "test:update": "run-s db:clean db:run && jest --runInBand --updateSnapshot && run-s db:clean", + "test:types": "run-s build:module && tsd --files test/*.test-d.ts", + "db:clean": "cd test/db && docker-compose down --volumes", + "db:run": "cd test/db && docker-compose up --detach && wait-for-localhost 3000" + }, + "dependencies": { + "cross-fetch": "^3.1.5" + }, + "devDependencies": { + "@types/jest": "^27.5.1", + "jest": "^28.1.0", + "node-abort-controller": "^3.0.1", + "npm-run-all": "^4.1.5", + "prettier": "^2.6.2", + "rimraf": "^3.0.2", + "semantic-release-plugin-update-version-in-files": "^1.1.0", + "ts-jest": "^28.0.3", + "tsd": "^0.24.1", + "typedoc": "^0.22.16", + "typescript": "~4.7", + "wait-for-localhost-cli": "^3.0.0" + } +} diff --git a/node_modules/@supabase/postgrest-js/src/PostgrestBuilder.ts b/node_modules/@supabase/postgrest-js/src/PostgrestBuilder.ts new file mode 100644 index 0000000..e48d69f --- /dev/null +++ b/node_modules/@supabase/postgrest-js/src/PostgrestBuilder.ts @@ -0,0 +1,189 @@ +import crossFetch from 'cross-fetch' + +import type { Fetch, PostgrestSingleResponse } from './types' + +export default abstract class PostgrestBuilder + implements PromiseLike> +{ + protected method: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE' + protected url: URL + protected headers: Record + protected schema?: string + protected body?: unknown + protected shouldThrowOnError = false + protected signal?: AbortSignal + protected fetch: Fetch + protected isMaybeSingle: boolean + + constructor(builder: PostgrestBuilder) { + this.method = builder.method + this.url = builder.url + this.headers = builder.headers + this.schema = builder.schema + this.body = builder.body + this.shouldThrowOnError = builder.shouldThrowOnError + this.signal = builder.signal + this.isMaybeSingle = builder.isMaybeSingle + + if (builder.fetch) { + this.fetch = builder.fetch + } else if (typeof fetch === 'undefined') { + this.fetch = crossFetch + } else { + this.fetch = fetch + } + } + + /** + * If there's an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + * + * {@link https://github.com/supabase/supabase-js/issues/92} + */ + throwOnError(): this { + this.shouldThrowOnError = true + return this + } + + then, TResult2 = never>( + onfulfilled?: + | ((value: PostgrestSingleResponse) => TResult1 | PromiseLike) + | undefined + | null, + onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null + ): PromiseLike { + // https://postgrest.org/en/stable/api.html#switching-schemas + if (this.schema === undefined) { + // skip + } else if (['GET', 'HEAD'].includes(this.method)) { + this.headers['Accept-Profile'] = this.schema + } else { + this.headers['Content-Profile'] = this.schema + } + if (this.method !== 'GET' && this.method !== 'HEAD') { + this.headers['Content-Type'] = 'application/json' + } + + // NOTE: Invoke w/o `this` to avoid illegal invocation error. + // https://github.com/supabase/postgrest-js/pull/247 + const _fetch = this.fetch + let res = _fetch(this.url.toString(), { + method: this.method, + headers: this.headers, + body: JSON.stringify(this.body), + signal: this.signal, + }).then(async (res) => { + let error = null + let data = null + let count: number | null = null + let status = res.status + let statusText = res.statusText + + if (res.ok) { + if (this.method !== 'HEAD') { + const body = await res.text() + if (body === '') { + // Prefer: return=minimal + } else if (this.headers['Accept'] === 'text/csv') { + data = body + } else if ( + this.headers['Accept'] && + this.headers['Accept'].includes('application/vnd.pgrst.plan+text') + ) { + data = body + } else { + data = JSON.parse(body) + } + } + + const countHeader = this.headers['Prefer']?.match(/count=(exact|planned|estimated)/) + const contentRange = res.headers.get('content-range')?.split('/') + if (countHeader && contentRange && contentRange.length > 1) { + count = parseInt(contentRange[1]) + } + + // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 + // Issue persists e.g. for `.insert([...]).select().maybeSingle()` + if (this.isMaybeSingle && this.method === 'GET' && Array.isArray(data)) { + if (data.length > 1) { + error = { + // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553 + code: 'PGRST116', + details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`, + hint: null, + message: 'JSON object requested, multiple (or no) rows returned', + } + data = null + count = null + status = 406 + statusText = 'Not Acceptable' + } else if (data.length === 1) { + data = data[0] + } else { + data = null + } + } + } else { + const body = await res.text() + + try { + error = JSON.parse(body) + + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (Array.isArray(error) && res.status === 404) { + data = [] + error = null + status = 200 + statusText = 'OK' + } + } catch { + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (res.status === 404 && body === '') { + status = 204 + statusText = 'No Content' + } else { + error = { + message: body, + } + } + } + + if (error && this.isMaybeSingle && error?.details?.includes('Results contain 0 rows')) { + error = null + status = 200 + statusText = 'OK' + } + + if (error && this.shouldThrowOnError) { + throw error + } + } + + const postgrestResponse = { + error, + data, + count, + status, + statusText, + } + + return postgrestResponse + }) + if (!this.shouldThrowOnError) { + res = res.catch((fetchError) => ({ + error: { + message: `${fetchError?.name ?? 'FetchError'}: ${fetchError?.message}`, + details: `${fetchError?.stack ?? ''}`, + hint: '', + code: `${fetchError?.code ?? ''}`, + }, + data: null, + count: null, + status: 0, + statusText: '', + })) + } + + return res.then(onfulfilled, onrejected) + } +} diff --git a/node_modules/@supabase/postgrest-js/src/PostgrestClient.ts b/node_modules/@supabase/postgrest-js/src/PostgrestClient.ts new file mode 100644 index 0000000..9e33110 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/src/PostgrestClient.ts @@ -0,0 +1,152 @@ +import PostgrestQueryBuilder from './PostgrestQueryBuilder' +import PostgrestFilterBuilder from './PostgrestFilterBuilder' +import PostgrestBuilder from './PostgrestBuilder' +import { DEFAULT_HEADERS } from './constants' +import { Fetch, GenericSchema } from './types' + +/** + * PostgREST client. + * + * @typeParam Database - Types for the schema from the [type + * generator](https://supabase.com/docs/reference/javascript/next/typescript-support) + * + * @typeParam SchemaName - Postgres schema to switch to. Must be a string + * literal, the same one passed to the constructor. If the schema is not + * `"public"`, this must be supplied manually. + */ +export default class PostgrestClient< + Database = any, + SchemaName extends string & keyof Database = 'public' extends keyof Database + ? 'public' + : string & keyof Database, + Schema extends GenericSchema = Database[SchemaName] extends GenericSchema + ? Database[SchemaName] + : any +> { + url: string + headers: Record + schema?: SchemaName + fetch?: Fetch + + // TODO: Add back shouldThrowOnError once we figure out the typings + /** + * Creates a PostgREST client. + * + * @param url - URL of the PostgREST endpoint + * @param options - Named parameters + * @param options.headers - Custom headers + * @param options.schema - Postgres schema to switch to + * @param options.fetch - Custom fetch + */ + constructor( + url: string, + { + headers = {}, + schema, + fetch, + }: { + headers?: Record + schema?: SchemaName + fetch?: Fetch + } = {} + ) { + this.url = url + this.headers = { ...DEFAULT_HEADERS, ...headers } + this.schema = schema + this.fetch = fetch + } + + from< + TableName extends string & keyof Schema['Tables'], + Table extends Schema['Tables'][TableName] + >(relation: TableName): PostgrestQueryBuilder + from( + relation: ViewName + ): PostgrestQueryBuilder + from(relation: string): PostgrestQueryBuilder + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation: string): PostgrestQueryBuilder { + const url = new URL(`${this.url}/${relation}`) + return new PostgrestQueryBuilder(url, { + headers: { ...this.headers }, + schema: this.schema, + fetch: this.fetch, + }) + } + + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc< + FunctionName extends string & keyof Schema['Functions'], + Function_ extends Schema['Functions'][FunctionName] + >( + fn: FunctionName, + args: Function_['Args'] = {}, + { + head = false, + count, + }: { + head?: boolean + count?: 'exact' | 'planned' | 'estimated' + } = {} + ): PostgrestFilterBuilder< + Schema, + Function_['Returns'] extends any[] + ? Function_['Returns'][number] extends Record + ? Function_['Returns'][number] + : never + : never, + Function_['Returns'] + > { + let method: 'HEAD' | 'POST' + const url = new URL(`${this.url}/rpc/${fn}`) + let body: unknown | undefined + if (head) { + method = 'HEAD' + Object.entries(args).forEach(([name, value]) => { + url.searchParams.append(name, `${value}`) + }) + } else { + method = 'POST' + body = args + } + + const headers = { ...this.headers } + if (count) { + headers['Prefer'] = `count=${count}` + } + + return new PostgrestFilterBuilder({ + method, + url, + headers, + schema: this.schema, + body, + fetch: this.fetch, + allowEmpty: false, + } as unknown as PostgrestBuilder) + } +} diff --git a/node_modules/@supabase/postgrest-js/src/PostgrestFilterBuilder.ts b/node_modules/@supabase/postgrest-js/src/PostgrestFilterBuilder.ts new file mode 100644 index 0000000..cb6beee --- /dev/null +++ b/node_modules/@supabase/postgrest-js/src/PostgrestFilterBuilder.ts @@ -0,0 +1,504 @@ +import PostgrestTransformBuilder from './PostgrestTransformBuilder' +import { GenericSchema } from './types' + +type FilterOperator = + | 'eq' + | 'neq' + | 'gt' + | 'gte' + | 'lt' + | 'lte' + | 'like' + | 'ilike' + | 'is' + | 'in' + | 'cs' + | 'cd' + | 'sl' + | 'sr' + | 'nxl' + | 'nxr' + | 'adj' + | 'ov' + | 'fts' + | 'plfts' + | 'phfts' + | 'wfts' + +export default class PostgrestFilterBuilder< + Schema extends GenericSchema, + Row extends Record, + Result, + Relationships = unknown +> extends PostgrestTransformBuilder { + eq(column: ColumnName, value: Row[ColumnName]): this + eq(column: string, value: unknown): this + /** + * Match only rows where `column` is equal to `value`. + * + * To check if the value of `column` is NULL, you should use `.is()` instead. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + eq(column: string, value: unknown): this { + this.url.searchParams.append(column, `eq.${value}`) + return this + } + + neq(column: ColumnName, value: Row[ColumnName]): this + neq(column: string, value: unknown): this + /** + * Match only rows where `column` is not equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + neq(column: string, value: unknown): this { + this.url.searchParams.append(column, `neq.${value}`) + return this + } + + gt(column: ColumnName, value: Row[ColumnName]): this + gt(column: string, value: unknown): this + /** + * Match only rows where `column` is greater than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gt(column: string, value: unknown): this { + this.url.searchParams.append(column, `gt.${value}`) + return this + } + + gte(column: ColumnName, value: Row[ColumnName]): this + gte(column: string, value: unknown): this + /** + * Match only rows where `column` is greater than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gte(column: string, value: unknown): this { + this.url.searchParams.append(column, `gte.${value}`) + return this + } + + lt(column: ColumnName, value: Row[ColumnName]): this + lt(column: string, value: unknown): this + /** + * Match only rows where `column` is less than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lt(column: string, value: unknown): this { + this.url.searchParams.append(column, `lt.${value}`) + return this + } + + lte(column: ColumnName, value: Row[ColumnName]): this + lte(column: string, value: unknown): this + /** + * Match only rows where `column` is less than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lte(column: string, value: unknown): this { + this.url.searchParams.append(column, `lte.${value}`) + return this + } + + like(column: ColumnName, pattern: string): this + like(column: string, pattern: string): this + /** + * Match only rows where `column` matches `pattern` case-sensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + like(column: string, pattern: string): this { + this.url.searchParams.append(column, `like.${pattern}`) + return this + } + + likeAllOf(column: ColumnName, patterns: string[]): this + likeAllOf(column: string, patterns: string[]): this + /** + * Match only rows where `column` matches all of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAllOf(column: string, patterns: string[]): this { + this.url.searchParams.append(column, `like(all).{${patterns.join(',')}}`) + return this + } + + likeAnyOf(column: ColumnName, patterns: string[]): this + likeAnyOf(column: string, patterns: string[]): this + /** + * Match only rows where `column` matches any of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAnyOf(column: string, patterns: string[]): this { + this.url.searchParams.append(column, `like(any).{${patterns.join(',')}}`) + return this + } + + ilike(column: ColumnName, pattern: string): this + ilike(column: string, pattern: string): this + /** + * Match only rows where `column` matches `pattern` case-insensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + ilike(column: string, pattern: string): this { + this.url.searchParams.append(column, `ilike.${pattern}`) + return this + } + + ilikeAllOf(column: ColumnName, patterns: string[]): this + ilikeAllOf(column: string, patterns: string[]): this + /** + * Match only rows where `column` matches all of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAllOf(column: string, patterns: string[]): this { + this.url.searchParams.append(column, `ilike(all).{${patterns.join(',')}}`) + return this + } + + ilikeAnyOf(column: ColumnName, patterns: string[]): this + ilikeAnyOf(column: string, patterns: string[]): this + /** + * Match only rows where `column` matches any of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAnyOf(column: string, patterns: string[]): this { + this.url.searchParams.append(column, `ilike(any).{${patterns.join(',')}}`) + return this + } + + is( + column: ColumnName, + value: Row[ColumnName] & (boolean | null) + ): this + is(column: string, value: boolean | null): this + /** + * Match only rows where `column` IS `value`. + * + * For non-boolean columns, this is only relevant for checking if the value of + * `column` is NULL by setting `value` to `null`. + * + * For boolean columns, you can also set `value` to `true` or `false` and it + * will behave the same way as `.eq()`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + is(column: string, value: boolean | null): this { + this.url.searchParams.append(column, `is.${value}`) + return this + } + + in(column: ColumnName, values: Row[ColumnName][]): this + in(column: string, values: unknown[]): this + /** + * Match only rows where `column` is included in the `values` array. + * + * @param column - The column to filter on + * @param values - The values array to filter with + */ + in(column: string, values: unknown[]): this { + const cleanedValues = values + .map((s) => { + // handle postgrest reserved characters + // https://postgrest.org/en/v7.0.0/api.html#reserved-characters + if (typeof s === 'string' && new RegExp('[,()]').test(s)) return `"${s}"` + else return `${s}` + }) + .join(',') + this.url.searchParams.append(column, `in.(${cleanedValues})`) + return this + } + + contains( + column: ColumnName, + value: string | Row[ColumnName][] | Record + ): this + contains(column: string, value: string | unknown[] | Record): this + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * `column` contains every element appearing in `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + contains(column: string, value: string | unknown[] | Record): this { + if (typeof value === 'string') { + // range types can be inclusive '[', ']' or exclusive '(', ')' so just + // keep it simple and accept a string + this.url.searchParams.append(column, `cs.${value}`) + } else if (Array.isArray(value)) { + // array + this.url.searchParams.append(column, `cs.{${value.join(',')}}`) + } else { + // json + this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`) + } + return this + } + + containedBy( + column: ColumnName, + value: string | Row[ColumnName][] | Record + ): this + containedBy(column: string, value: string | unknown[] | Record): this + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * every element appearing in `column` is contained by `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + containedBy(column: string, value: string | unknown[] | Record): this { + if (typeof value === 'string') { + // range + this.url.searchParams.append(column, `cd.${value}`) + } else if (Array.isArray(value)) { + // array + this.url.searchParams.append(column, `cd.{${value.join(',')}}`) + } else { + // json + this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`) + } + return this + } + + rangeGt(column: ColumnName, range: string): this + rangeGt(column: string, range: string): this + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is greater than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGt(column: string, range: string): this { + this.url.searchParams.append(column, `sr.${range}`) + return this + } + + rangeGte(column: ColumnName, range: string): this + rangeGte(column: string, range: string): this + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or greater than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGte(column: string, range: string): this { + this.url.searchParams.append(column, `nxl.${range}`) + return this + } + + rangeLt(column: ColumnName, range: string): this + rangeLt(column: string, range: string): this + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is less than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLt(column: string, range: string): this { + this.url.searchParams.append(column, `sl.${range}`) + return this + } + + rangeLte(column: ColumnName, range: string): this + rangeLte(column: string, range: string): this + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or less than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLte(column: string, range: string): this { + this.url.searchParams.append(column, `nxr.${range}`) + return this + } + + rangeAdjacent(column: ColumnName, range: string): this + rangeAdjacent(column: string, range: string): this + /** + * Only relevant for range columns. Match only rows where `column` is + * mutually exclusive to `range` and there can be no element between the two + * ranges. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeAdjacent(column: string, range: string): this { + this.url.searchParams.append(column, `adj.${range}`) + return this + } + + overlaps( + column: ColumnName, + value: string | Row[ColumnName][] + ): this + overlaps(column: string, value: string | unknown[]): this + /** + * Only relevant for array and range columns. Match only rows where + * `column` and `value` have an element in common. + * + * @param column - The array or range column to filter on + * @param value - The array or range value to filter with + */ + overlaps(column: string, value: string | unknown[]): this { + if (typeof value === 'string') { + // range + this.url.searchParams.append(column, `ov.${value}`) + } else { + // array + this.url.searchParams.append(column, `ov.{${value.join(',')}}`) + } + return this + } + + textSearch( + column: ColumnName, + query: string, + options?: { config?: string; type?: 'plain' | 'phrase' | 'websearch' } + ): this + textSearch( + column: string, + query: string, + options?: { config?: string; type?: 'plain' | 'phrase' | 'websearch' } + ): this + /** + * Only relevant for text and tsvector columns. Match only rows where + * `column` matches the query string in `query`. + * + * @param column - The text or tsvector column to filter on + * @param query - The query text to match with + * @param options - Named parameters + * @param options.config - The text search configuration to use + * @param options.type - Change how the `query` text is interpreted + */ + textSearch( + column: string, + query: string, + { config, type }: { config?: string; type?: 'plain' | 'phrase' | 'websearch' } = {} + ): this { + let typePart = '' + if (type === 'plain') { + typePart = 'pl' + } else if (type === 'phrase') { + typePart = 'ph' + } else if (type === 'websearch') { + typePart = 'w' + } + const configPart = config === undefined ? '' : `(${config})` + this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`) + return this + } + + match(query: Record): this + match(query: Record): this + /** + * Match only rows where each column in `query` keys is equal to its + * associated value. Shorthand for multiple `.eq()`s. + * + * @param query - The object to filter with, with column names as keys mapped + * to their filter values + */ + match(query: Record): this { + Object.entries(query).forEach(([column, value]) => { + this.url.searchParams.append(column, `eq.${value}`) + }) + return this + } + + not( + column: ColumnName, + operator: FilterOperator, + value: Row[ColumnName] + ): this + not(column: string, operator: string, value: unknown): this + /** + * Match only rows which doesn't satisfy the filter. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to be negated to filter with, following + * PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + not(column: string, operator: string, value: unknown): this { + this.url.searchParams.append(column, `not.${operator}.${value}`) + return this + } + + /** + * Match only rows which satisfy at least one of the filters. + * + * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure it's properly sanitized. + * + * It's currently not possible to do an `.or()` filter across multiple tables. + * + * @param filters - The filters to use, following PostgREST syntax + * @param foreignTable - Set this to filter on foreign tables instead of the + * current table + */ + or(filters: string, { foreignTable }: { foreignTable?: string } = {}): this { + const key = foreignTable ? `${foreignTable}.or` : 'or' + this.url.searchParams.append(key, `(${filters})`) + return this + } + + filter( + column: ColumnName, + operator: `${'' | 'not.'}${FilterOperator}`, + value: unknown + ): this + filter(column: string, operator: string, value: unknown): this + /** + * Match only rows which satisfy the filter. This is an escape hatch - you + * should use the specific filter methods wherever possible. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to filter with, following PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + filter(column: string, operator: string, value: unknown): this { + this.url.searchParams.append(column, `${operator}.${value}`) + return this + } +} diff --git a/node_modules/@supabase/postgrest-js/src/PostgrestQueryBuilder.ts b/node_modules/@supabase/postgrest-js/src/PostgrestQueryBuilder.ts new file mode 100644 index 0000000..d94c4c4 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/src/PostgrestQueryBuilder.ts @@ -0,0 +1,347 @@ +import PostgrestBuilder from './PostgrestBuilder' +import PostgrestFilterBuilder from './PostgrestFilterBuilder' +import { GetResult } from './select-query-parser' +import { Fetch, GenericSchema, GenericTable, GenericView } from './types' + +export default class PostgrestQueryBuilder< + Schema extends GenericSchema, + Relation extends GenericTable | GenericView, + Relationships = Relation extends { Relationships: infer R } ? R : unknown +> { + url: URL + headers: Record + schema?: string + signal?: AbortSignal + fetch?: Fetch + + constructor( + url: URL, + { + headers = {}, + schema, + fetch, + }: { + headers?: Record + schema?: string + fetch?: Fetch + } + ) { + this.url = url + this.headers = headers + this.schema = schema + this.fetch = fetch + } + + /** + * Perform a SELECT query on the table or view. + * + * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` + * + * @param options - Named parameters + * + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * + * @param options.count - Count algorithm to use to count rows in the table or view. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + select< + Query extends string = '*', + ResultOne = GetResult + >( + columns?: Query, + { + head = false, + count, + }: { + head?: boolean + count?: 'exact' | 'planned' | 'estimated' + } = {} + ): PostgrestFilterBuilder { + const method = head ? 'HEAD' : 'GET' + // Remove whitespaces except when quoted + let quoted = false + const cleanedColumns = (columns ?? '*') + .split('') + .map((c) => { + if (/\s/.test(c) && !quoted) { + return '' + } + if (c === '"') { + quoted = !quoted + } + return c + }) + .join('') + this.url.searchParams.set('select', cleanedColumns) + if (count) { + this.headers['Prefer'] = `count=${count}` + } + + return new PostgrestFilterBuilder({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: this.fetch, + allowEmpty: false, + } as unknown as PostgrestBuilder) + } + + /** + * Perform an INSERT into the table or view. + * + * By default, inserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to insert. Pass an object to insert a single row + * or an array to insert multiple rows. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count inserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. + */ + insert( + values: Row | Row[], + { + count, + defaultToNull = true, + }: { + count?: 'exact' | 'planned' | 'estimated' + defaultToNull?: boolean + } = {} + ): PostgrestFilterBuilder { + const method = 'POST' + + const prefersHeaders = [] + if (this.headers['Prefer']) { + prefersHeaders.push(this.headers['Prefer']) + } + if (count) { + prefersHeaders.push(`count=${count}`) + } + if (!defaultToNull) { + prefersHeaders.push('missing=default') + } + this.headers['Prefer'] = prefersHeaders.join(',') + + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), [] as string[]) + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`) + this.url.searchParams.set('columns', uniqueColumns.join(',')) + } + } + + return new PostgrestFilterBuilder({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: this.fetch, + allowEmpty: false, + } as unknown as PostgrestBuilder) + } + + /** + * Perform an UPSERT on the table or view. Depending on the column(s) passed + * to `onConflict`, `.upsert()` allows you to perform the equivalent of + * `.insert()` if a row with the corresponding `onConflict` columns doesn't + * exist, or if it does exist, perform an alternative action depending on + * `ignoreDuplicates`. + * + * By default, upserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to upsert with. Pass an object to upsert a + * single row or an array to upsert multiple rows. + * + * @param options - Named parameters + * + * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how + * duplicate rows are determined. Two rows are duplicates if all the + * `onConflict` columns are equal. + * + * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If + * `false`, duplicate rows are merged with existing rows. + * + * @param options.count - Count algorithm to use to count upserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. This only applies when + * inserting new rows, not when merging with existing rows under + * `ignoreDuplicates: false`. + */ + upsert( + values: Row | Row[], + { + onConflict, + ignoreDuplicates = false, + count, + defaultToNull = true, + }: { + onConflict?: string + ignoreDuplicates?: boolean + count?: 'exact' | 'planned' | 'estimated' + defaultToNull?: boolean + } = {} + ): PostgrestFilterBuilder { + const method = 'POST' + + const prefersHeaders = [`resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates`] + + if (onConflict !== undefined) this.url.searchParams.set('on_conflict', onConflict) + if (this.headers['Prefer']) { + prefersHeaders.push(this.headers['Prefer']) + } + if (count) { + prefersHeaders.push(`count=${count}`) + } + if (!defaultToNull) { + prefersHeaders.push('missing=default') + } + this.headers['Prefer'] = prefersHeaders.join(',') + + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), [] as string[]) + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`) + this.url.searchParams.set('columns', uniqueColumns.join(',')) + } + } + + return new PostgrestFilterBuilder({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: this.fetch, + allowEmpty: false, + } as unknown as PostgrestBuilder) + } + + /** + * Perform an UPDATE on the table or view. + * + * By default, updated rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param values - The values to update with + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count updated rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + update( + values: Row, + { + count, + }: { + count?: 'exact' | 'planned' | 'estimated' + } = {} + ): PostgrestFilterBuilder { + const method = 'PATCH' + const prefersHeaders = [] + if (this.headers['Prefer']) { + prefersHeaders.push(this.headers['Prefer']) + } + if (count) { + prefersHeaders.push(`count=${count}`) + } + this.headers['Prefer'] = prefersHeaders.join(',') + + return new PostgrestFilterBuilder({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: this.fetch, + allowEmpty: false, + } as unknown as PostgrestBuilder) + } + + /** + * Perform a DELETE on the table or view. + * + * By default, deleted rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count deleted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + delete({ + count, + }: { + count?: 'exact' | 'planned' | 'estimated' + } = {}): PostgrestFilterBuilder { + const method = 'DELETE' + const prefersHeaders = [] + if (count) { + prefersHeaders.push(`count=${count}`) + } + if (this.headers['Prefer']) { + prefersHeaders.unshift(this.headers['Prefer']) + } + this.headers['Prefer'] = prefersHeaders.join(',') + + return new PostgrestFilterBuilder({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: this.fetch, + allowEmpty: false, + } as unknown as PostgrestBuilder) + } +} diff --git a/node_modules/@supabase/postgrest-js/src/PostgrestTransformBuilder.ts b/node_modules/@supabase/postgrest-js/src/PostgrestTransformBuilder.ts new file mode 100644 index 0000000..8cbf87a --- /dev/null +++ b/node_modules/@supabase/postgrest-js/src/PostgrestTransformBuilder.ts @@ -0,0 +1,260 @@ +import PostgrestBuilder from './PostgrestBuilder' +import { GetResult } from './select-query-parser' +import { GenericSchema } from './types' + +export default class PostgrestTransformBuilder< + Schema extends GenericSchema, + Row extends Record, + Result, + Relationships = unknown +> extends PostgrestBuilder { + /** + * Perform a SELECT on the query result. + * + * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not + * return modified rows. By calling this method, modified rows are returned in + * `data`. + * + * @param columns - The columns to retrieve, separated by commas + */ + select>( + columns?: Query + ): PostgrestTransformBuilder { + // Remove whitespaces except when quoted + let quoted = false + const cleanedColumns = (columns ?? '*') + .split('') + .map((c) => { + if (/\s/.test(c) && !quoted) { + return '' + } + if (c === '"') { + quoted = !quoted + } + return c + }) + .join('') + this.url.searchParams.set('select', cleanedColumns) + if (this.headers['Prefer']) { + this.headers['Prefer'] += ',' + } + this.headers['Prefer'] += 'return=representation' + return this as unknown as PostgrestTransformBuilder + } + + order( + column: ColumnName, + options?: { ascending?: boolean; nullsFirst?: boolean; foreignTable?: undefined } + ): this + order( + column: string, + options?: { ascending?: boolean; nullsFirst?: boolean; foreignTable?: string } + ): this + /** + * Order the query result by `column`. + * + * You can call this method multiple times to order by multiple columns. + * + * You can order foreign tables, but it doesn't affect the ordering of the + * current table. + * + * @param column - The column to order by + * @param options - Named parameters + * @param options.ascending - If `true`, the result will be in ascending order + * @param options.nullsFirst - If `true`, `null`s appear first. If `false`, + * `null`s appear last. + * @param options.foreignTable - Set this to order a foreign table by foreign + * columns + */ + order( + column: string, + { + ascending = true, + nullsFirst, + foreignTable, + }: { ascending?: boolean; nullsFirst?: boolean; foreignTable?: string } = {} + ): this { + const key = foreignTable ? `${foreignTable}.order` : 'order' + const existingOrder = this.url.searchParams.get(key) + + this.url.searchParams.set( + key, + `${existingOrder ? `${existingOrder},` : ''}${column}.${ascending ? 'asc' : 'desc'}${ + nullsFirst === undefined ? '' : nullsFirst ? '.nullsfirst' : '.nullslast' + }` + ) + return this + } + + /** + * Limit the query result by `count`. + * + * @param count - The maximum number of rows to return + * @param options - Named parameters + * @param options.foreignTable - Set this to limit rows of foreign tables + * instead of the current table + */ + limit(count: number, { foreignTable }: { foreignTable?: string } = {}): this { + const key = typeof foreignTable === 'undefined' ? 'limit' : `${foreignTable}.limit` + this.url.searchParams.set(key, `${count}`) + return this + } + + /** + * Limit the query result by starting at an offset (`from`) and ending at the offset (`from + to`). + * Only records within this range are returned. + * This respects the query order and if there is no order clause the range could behave unexpectedly. + * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third + * and fourth rows of the query. + * + * @param from - The starting index from which to limit the result + * @param to - The last index to which to limit the result + * @param options - Named parameters + * @param options.foreignTable - Set this to limit rows of foreign tables + * instead of the current table + */ + range(from: number, to: number, { foreignTable }: { foreignTable?: string } = {}): this { + const keyOffset = typeof foreignTable === 'undefined' ? 'offset' : `${foreignTable}.offset` + const keyLimit = typeof foreignTable === 'undefined' ? 'limit' : `${foreignTable}.limit` + this.url.searchParams.set(keyOffset, `${from}`) + // Range is inclusive, so add 1 + this.url.searchParams.set(keyLimit, `${to - from + 1}`) + return this + } + + /** + * Set the AbortSignal for the fetch request. + * + * @param signal - The AbortSignal to use for the fetch request + */ + abortSignal(signal: AbortSignal): this { + this.signal = signal + return this + } + + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be one row (e.g. using `.limit(1)`), otherwise this + * returns an error. + */ + single< + ResultOne = Result extends (infer ResultOne)[] ? ResultOne : never + >(): PostgrestBuilder { + this.headers['Accept'] = 'application/vnd.pgrst.object+json' + return this as PostgrestBuilder + } + + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise + * this returns an error. + */ + maybeSingle< + ResultOne = Result extends (infer ResultOne)[] ? ResultOne : never + >(): PostgrestBuilder { + // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 + // Issue persists e.g. for `.insert([...]).select().maybeSingle()` + if (this.method === 'GET') { + this.headers['Accept'] = 'application/json' + } else { + this.headers['Accept'] = 'application/vnd.pgrst.object+json' + } + this.isMaybeSingle = true + return this as PostgrestBuilder + } + + /** + * Return `data` as a string in CSV format. + */ + csv(): PostgrestBuilder { + this.headers['Accept'] = 'text/csv' + return this as PostgrestBuilder + } + + /** + * Return `data` as an object in [GeoJSON](https://geojson.org) format. + */ + geojson(): PostgrestBuilder> { + this.headers['Accept'] = 'application/geo+json' + return this as PostgrestBuilder> + } + + /** + * Return `data` as the EXPLAIN plan for the query. + * + * @param options - Named parameters + * + * @param options.analyze - If `true`, the query will be executed and the + * actual run time will be returned + * + * @param options.verbose - If `true`, the query identifier will be returned + * and `data` will include the output columns of the query + * + * @param options.settings - If `true`, include information on configuration + * parameters that affect query planning + * + * @param options.buffers - If `true`, include information on buffer usage + * + * @param options.wal - If `true`, include information on WAL record generation + * + * @param options.format - The format of the output, can be `"text"` (default) + * or `"json"` + */ + explain({ + analyze = false, + verbose = false, + settings = false, + buffers = false, + wal = false, + format = 'text', + }: { + analyze?: boolean + verbose?: boolean + settings?: boolean + buffers?: boolean + wal?: boolean + format?: 'json' | 'text' + } = {}): PostgrestBuilder[]> | PostgrestBuilder { + const options = [ + analyze ? 'analyze' : null, + verbose ? 'verbose' : null, + settings ? 'settings' : null, + buffers ? 'buffers' : null, + wal ? 'wal' : null, + ] + .filter(Boolean) + .join('|') + // An Accept header can carry multiple media types but postgrest-js always sends one + const forMediatype = this.headers['Accept'] + this.headers[ + 'Accept' + ] = `application/vnd.pgrst.plan+${format}; for="${forMediatype}"; options=${options};` + if (format === 'json') return this as PostgrestBuilder[]> + else return this as PostgrestBuilder + } + + /** + * Rollback the query. + * + * `data` will still be returned, but the query is not committed. + */ + rollback(): this { + if ((this.headers['Prefer'] ?? '').trim().length > 0) { + this.headers['Prefer'] += ',tx=rollback' + } else { + this.headers['Prefer'] = 'tx=rollback' + } + return this + } + + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + */ + returns(): PostgrestTransformBuilder { + return this as unknown as PostgrestTransformBuilder + } +} diff --git a/node_modules/@supabase/postgrest-js/src/constants.ts b/node_modules/@supabase/postgrest-js/src/constants.ts new file mode 100644 index 0000000..9870d64 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/src/constants.ts @@ -0,0 +1,2 @@ +import { version } from './version' +export const DEFAULT_HEADERS = { 'X-Client-Info': `postgrest-js/${version}` } diff --git a/node_modules/@supabase/postgrest-js/src/index.ts b/node_modules/@supabase/postgrest-js/src/index.ts new file mode 100644 index 0000000..9fb4cb7 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/src/index.ts @@ -0,0 +1,13 @@ +export { default as PostgrestClient } from './PostgrestClient' +export { default as PostgrestQueryBuilder } from './PostgrestQueryBuilder' +export { default as PostgrestFilterBuilder } from './PostgrestFilterBuilder' +export { default as PostgrestTransformBuilder } from './PostgrestTransformBuilder' +export { default as PostgrestBuilder } from './PostgrestBuilder' +export { + PostgrestResponse, + PostgrestResponseFailure, + PostgrestResponseSuccess, + PostgrestSingleResponse, + PostgrestMaybeSingleResponse, + PostgrestError, +} from './types' diff --git a/node_modules/@supabase/postgrest-js/src/select-query-parser.ts b/node_modules/@supabase/postgrest-js/src/select-query-parser.ts new file mode 100644 index 0000000..f7580e8 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/src/select-query-parser.ts @@ -0,0 +1,455 @@ +// Credits to @bnjmnt4n (https://www.npmjs.com/package/postgrest-query) + +import { GenericSchema, Prettify } from './types' + +type Whitespace = ' ' | '\n' | '\t' + +type LowerAlphabet = + | 'a' + | 'b' + | 'c' + | 'd' + | 'e' + | 'f' + | 'g' + | 'h' + | 'i' + | 'j' + | 'k' + | 'l' + | 'm' + | 'n' + | 'o' + | 'p' + | 'q' + | 'r' + | 's' + | 't' + | 'u' + | 'v' + | 'w' + | 'x' + | 'y' + | 'z' + +type Alphabet = LowerAlphabet | Uppercase + +type Digit = '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '0' + +type Letter = Alphabet | Digit | '_' + +type Json = string | number | boolean | null | { [key: string]: Json } | Json[] + +// /** +// * Parsed node types. +// * Currently only `*` and all other fields. +// */ +// type ParsedNode = +// | { star: true } +// | { name: string; original: string } +// | { name: string; foreignTable: true } +// | { name: string; type: T }; + +/** + * Parser errors. + */ +type ParserError = { error: true } & Message +type GenericStringError = ParserError<'Received a generic string'> +export type SelectQueryError = { error: true } & Message + +/** + * Trims whitespace from the left of the input. + */ +type EatWhitespace = string extends Input + ? GenericStringError + : Input extends `${Whitespace}${infer Remainder}` + ? EatWhitespace + : Input + +type HasFKey = Relationships extends [infer R] + ? R extends { foreignKeyName: FKeyName } + ? true + : false + : Relationships extends [infer R, ...infer Rest] + ? HasFKey extends true + ? true + : HasFKey + : false + +type HasFKeyToFRel = Relationships extends [infer R] + ? R extends { referencedRelation: FRelName } + ? true + : false + : Relationships extends [infer R, ...infer Rest] + ? HasFKeyToFRel extends true + ? true + : HasFKeyToFRel + : false + +/** + * Constructs a type definition for a single field of an object. + * + * @param Definitions Record of definitions, possibly generated from PostgREST's OpenAPI spec. + * @param Name Name of the table being queried. + * @param Field Single field parsed by `ParseQuery`. + */ +type ConstructFieldDefinition< + Schema extends GenericSchema, + Row extends Record, + Relationships, + Field +> = Field extends { star: true } + ? Row + : Field extends { name: string; original: string; hint: string; children: unknown[] } + ? { + [_ in Field['name']]: GetResultHelper< + Schema, + (Schema['Tables'] & Schema['Views'])[Field['original']]['Row'], + (Schema['Tables'] & Schema['Views'])[Field['original']] extends { Relationships: infer R } + ? R + : unknown, + Field['children'], + unknown + > extends infer Child + ? Relationships extends unknown[] + ? HasFKey extends true + ? Child | null + : Child[] + : Child[] + : never + } + : Field extends { name: string; original: string; children: unknown[] } + ? { + [_ in Field['name']]: GetResultHelper< + Schema, + (Schema['Tables'] & Schema['Views'])[Field['original']]['Row'], + (Schema['Tables'] & Schema['Views'])[Field['original']] extends { Relationships: infer R } + ? R + : unknown, + Field['children'], + unknown + > extends infer Child + ? Relationships extends unknown[] + ? HasFKeyToFRel extends true + ? Child | null + : Child[] + : Child[] + : never + } + : Field extends { name: string; original: string } + ? Field['original'] extends keyof Row + ? { [K in Field['name']]: Row[Field['original']] } + : SelectQueryError<`Referencing missing column \`${Field['original']}\``> + : Field extends { name: string; type: infer T } + ? { [K in Field['name']]: T } + : Record + +/** + * Notes: all `Parse*` types assume that their input strings have their whitespace + * removed. They return tuples of ["Return Value", "Remainder of text"] or + * a `ParserError`. + */ + +/** + * Reads a consecutive sequence of more than 1 letter, + * where letters are `[0-9a-zA-Z_]`. + */ +type ReadLetters = string extends Input + ? GenericStringError + : ReadLettersHelper extends [`${infer Letters}`, `${infer Remainder}`] + ? Letters extends '' + ? ParserError<`Expected letter at \`${Input}\``> + : [Letters, Remainder] + : ReadLettersHelper + +type ReadLettersHelper = string extends Input + ? GenericStringError + : Input extends `${infer L}${infer Remainder}` + ? L extends Letter + ? ReadLettersHelper + : [Acc, Input] + : [Acc, ''] + +/** + * Reads a consecutive sequence of more than 1 double-quoted letters, + * where letters are `[^"]`. + */ +type ReadQuotedLetters = string extends Input + ? GenericStringError + : Input extends `"${infer Remainder}` + ? ReadQuotedLettersHelper extends [`${infer Letters}`, `${infer Remainder}`] + ? Letters extends '' + ? ParserError<`Expected string at \`${Remainder}\``> + : [Letters, Remainder] + : ReadQuotedLettersHelper + : ParserError<`Not a double-quoted string at \`${Input}\``> + +type ReadQuotedLettersHelper = string extends Input + ? GenericStringError + : Input extends `${infer L}${infer Remainder}` + ? L extends '"' + ? [Acc, Remainder] + : ReadQuotedLettersHelper + : ParserError<`Missing closing double-quote in \`"${Acc}${Input}\``> + +/** + * Parses a (possibly double-quoted) identifier. + * For now, identifiers are just sequences of more than 1 letter. + */ +type ParseIdentifier = ReadLetters extends [ + infer Name, + `${infer Remainder}` +] + ? [Name, `${Remainder}`] + : ReadQuotedLetters extends [infer Name, `${infer Remainder}`] + ? [Name, `${Remainder}`] + : ParserError<`No (possibly double-quoted) identifier at \`${Input}\``> + +/** + * Parses a node. + * A node is one of the following: + * - `*` + * - `field` + * - `field->json...` + * - `field(nodes)` + * - `field!hint(nodes)` + * - `field!inner(nodes)` + * - `field!hint!inner(nodes)` + * - `renamed_field:field` + * - `renamed_field:field->json...` + * - `renamed_field:field(nodes)` + * - `renamed_field:field!hint(nodes)` + * - `renamed_field:field!inner(nodes)` + * - `renamed_field:field!hint!inner(nodes)` + * + * TODO: casting operators `::text`, more support for JSON operators `->`, `->>`. + */ +type ParseNode = Input extends '' + ? ParserError<'Empty string'> + : // `*` + Input extends `*${infer Remainder}` + ? [{ star: true }, EatWhitespace] + : ParseIdentifier extends [infer Name, `${infer Remainder}`] + ? EatWhitespace extends `!inner${infer Remainder}` + ? ParseEmbeddedResource> extends [infer Fields, `${infer Remainder}`] + ? // `field!inner(nodes)` + [{ name: Name; original: Name; children: Fields }, EatWhitespace] + : ParseEmbeddedResource> extends ParserError + ? ParseEmbeddedResource> + : ParserError<'Expected embedded resource after `!inner`'> + : EatWhitespace extends `!${infer Remainder}` + ? ParseIdentifier> extends [infer Hint, `${infer Remainder}`] + ? EatWhitespace extends `!inner${infer Remainder}` + ? ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` + ] + ? // `field!hint!inner(nodes)` + [{ name: Name; original: Name; hint: Hint; children: Fields }, EatWhitespace] + : ParseEmbeddedResource> extends ParserError + ? ParseEmbeddedResource> + : ParserError<'Expected embedded resource after `!inner`'> + : ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` + ] + ? // `field!hint(nodes)` + [{ name: Name; original: Name; hint: Hint; children: Fields }, EatWhitespace] + : ParseEmbeddedResource> extends ParserError + ? ParseEmbeddedResource> + : ParserError<'Expected embedded resource after `!hint`'> + : ParserError<'Expected identifier after `!`'> + : EatWhitespace extends `:${infer Remainder}` + ? ParseIdentifier> extends [infer OriginalName, `${infer Remainder}`] + ? EatWhitespace extends `!inner${infer Remainder}` + ? ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` + ] + ? // `renamed_field:field!inner(nodes)` + [{ name: Name; original: OriginalName; children: Fields }, EatWhitespace] + : ParseEmbeddedResource> extends ParserError + ? ParseEmbeddedResource> + : ParserError<'Expected embedded resource after `!inner`'> + : EatWhitespace extends `!${infer Remainder}` + ? ParseIdentifier> extends [infer Hint, `${infer Remainder}`] + ? EatWhitespace extends `!inner${infer Remainder}` + ? ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` + ] + ? // `renamed_field:field!hint!inner(nodes)` + [ + { name: Name; original: OriginalName; hint: Hint; children: Fields }, + EatWhitespace + ] + : ParseEmbeddedResource> extends ParserError + ? ParseEmbeddedResource> + : ParserError<'Expected embedded resource after `!inner`'> + : ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` + ] + ? // `renamed_field:field!hint(nodes)` + [ + { + name: Name + original: OriginalName + hint: Hint + children: Fields + }, + EatWhitespace + ] + : ParseEmbeddedResource> extends ParserError + ? ParseEmbeddedResource> + : ParserError<'Expected embedded resource after `!hint`'> + : ParserError<'Expected identifier after `!`'> + : ParseEmbeddedResource> extends [ + infer Fields, + `${infer Remainder}` + ] + ? // `renamed_field:field(nodes)` + [{ name: Name; original: OriginalName; children: Fields }, EatWhitespace] + : ParseJsonAccessor> extends [ + infer _PropertyName, + infer PropertyType, + `${infer Remainder}` + ] + ? // `renamed_field:field->json...` + [{ name: Name; type: PropertyType }, EatWhitespace] + : ParseEmbeddedResource> extends ParserError + ? ParseEmbeddedResource> + : // `renamed_field:field` + [{ name: Name; original: OriginalName }, EatWhitespace] + : ParseIdentifier> + : ParseEmbeddedResource> extends [infer Fields, `${infer Remainder}`] + ? // `field(nodes)` + [{ name: Name; original: Name; children: Fields }, EatWhitespace] + : ParseJsonAccessor> extends [ + infer PropertyName, + infer PropertyType, + `${infer Remainder}` + ] + ? // `field->json...` + [{ name: PropertyName; type: PropertyType }, EatWhitespace] + : ParseEmbeddedResource> extends ParserError + ? ParseEmbeddedResource> + : // `field` + [{ name: Name; original: Name }, EatWhitespace] + : ParserError<`Expected identifier at \`${Input}\``> + +/** + * Parses a JSON property accessor of the shape `->a->b->c`. The last accessor in + * the series may convert to text by using the ->> operator instead of ->. + * + * Returns a tuple of ["Last property name", "Last property type", "Remainder of text"] + * or the original string input indicating that no opening `->` was found. + */ +type ParseJsonAccessor = Input extends `->${infer Remainder}` + ? Remainder extends `>${infer Remainder}` + ? ParseIdentifier extends [infer Name, `${infer Remainder}`] + ? [Name, string, EatWhitespace] + : ParserError<'Expected property name after `->>`'> + : ParseIdentifier extends [infer Name, `${infer Remainder}`] + ? ParseJsonAccessor extends [ + infer PropertyName, + infer PropertyType, + `${infer Remainder}` + ] + ? [PropertyName, PropertyType, EatWhitespace] + : [Name, Json, EatWhitespace] + : ParserError<'Expected property name after `->`'> + : Input + +/** + * Parses an embedded resource, which is an opening `(`, followed by a sequence of + * nodes, separated by `,`, then a closing `)`. + * + * Returns a tuple of ["Parsed fields", "Remainder of text"], an error, + * or the original string input indicating that no opening `(` was found. + */ +type ParseEmbeddedResource = Input extends `(${infer Remainder}` + ? ParseNodes> extends [infer Fields, `${infer Remainder}`] + ? EatWhitespace extends `)${infer Remainder}` + ? Fields extends [] + ? ParserError<'Expected fields after `(`'> + : [Fields, EatWhitespace] + : ParserError<`Expected ")"`> + : ParseNodes> + : Input + +/** + * Parses a sequence of nodes, separated by `,`. + * + * Returns a tuple of ["Parsed fields", "Remainder of text"] or an error. + */ +type ParseNodes = string extends Input + ? GenericStringError + : ParseNodesHelper + +type ParseNodesHelper = ParseNode extends [ + infer Field, + `${infer Remainder}` +] + ? EatWhitespace extends `,${infer Remainder}` + ? ParseNodesHelper, [Field, ...Fields]> + : [[Field, ...Fields], EatWhitespace] + : ParseNode + +/** + * Parses a query. + * A query is a sequence of nodes, separated by `,`, ensuring that there is + * no remaining input after all nodes have been parsed. + * + * Returns an array of parsed nodes, or an error. + */ +type ParseQuery = string extends Query + ? GenericStringError + : ParseNodes> extends [infer Fields, `${infer Remainder}`] + ? EatWhitespace extends '' + ? Fields + : ParserError<`Unexpected input: ${Remainder}`> + : ParseNodes> + +type GetResultHelper< + Schema extends GenericSchema, + Row extends Record, + Relationships, + Fields extends unknown[], + Acc +> = Fields extends [infer R] + ? ConstructFieldDefinition extends SelectQueryError + ? SelectQueryError + : GetResultHelper< + Schema, + Row, + Relationships, + [], + ConstructFieldDefinition & Acc + > + : Fields extends [infer R, ...infer Rest] + ? ConstructFieldDefinition extends SelectQueryError + ? SelectQueryError + : GetResultHelper< + Schema, + Row, + Relationships, + Rest, + ConstructFieldDefinition & Acc + > + : Prettify + +/** + * Constructs a type definition for an object based on a given PostgREST query. + * + * @param Row Record. + * @param Query Select query string literal to parse. + */ +export type GetResult< + Schema extends GenericSchema, + Row extends Record, + Relationships, + Query extends string +> = ParseQuery extends unknown[] + ? GetResultHelper, unknown> + : ParseQuery diff --git a/node_modules/@supabase/postgrest-js/src/types.ts b/node_modules/@supabase/postgrest-js/src/types.ts new file mode 100644 index 0000000..5379b27 --- /dev/null +++ b/node_modules/@supabase/postgrest-js/src/types.ts @@ -0,0 +1,72 @@ +export type Fetch = typeof fetch + +/** + * Error format + * + * {@link https://postgrest.org/en/stable/api.html?highlight=options#errors-and-http-status-codes} + */ +export type PostgrestError = { + message: string + details: string + hint: string + code: string +} + +/** + * Response format + * + * {@link https://github.com/supabase/supabase-js/issues/32} + */ +interface PostgrestResponseBase { + status: number + statusText: string +} +export interface PostgrestResponseSuccess extends PostgrestResponseBase { + error: null + data: T + count: number | null +} +export interface PostgrestResponseFailure extends PostgrestResponseBase { + error: PostgrestError + data: null + count: null +} + +// TODO: in v3: +// - remove PostgrestResponse and PostgrestMaybeSingleResponse +// - rename PostgrestSingleResponse to PostgrestResponse +export type PostgrestSingleResponse = PostgrestResponseSuccess | PostgrestResponseFailure +export type PostgrestMaybeSingleResponse = PostgrestSingleResponse +export type PostgrestResponse = PostgrestSingleResponse + +export type GenericTable = { + Row: Record + Insert: Record + Update: Record +} + +export type GenericUpdatableView = { + Row: Record + Insert: Record + Update: Record +} + +export type GenericNonUpdatableView = { + Row: Record +} + +export type GenericView = GenericUpdatableView | GenericNonUpdatableView + +export type GenericFunction = { + Args: Record + Returns: unknown +} + +export type GenericSchema = { + Tables: Record + Views: Record + Functions: Record +} + +// https://twitter.com/mattpocockuk/status/1622730173446557697 +export type Prettify = { [K in keyof T]: T[K] } & {} diff --git a/node_modules/@supabase/postgrest-js/src/version.ts b/node_modules/@supabase/postgrest-js/src/version.ts new file mode 100644 index 0000000..52b25ad --- /dev/null +++ b/node_modules/@supabase/postgrest-js/src/version.ts @@ -0,0 +1 @@ +export const version = '1.7.2' diff --git a/node_modules/@supabase/realtime-js/LICENSE.md b/node_modules/@supabase/realtime-js/LICENSE.md new file mode 100644 index 0000000..163f9b7 --- /dev/null +++ b/node_modules/@supabase/realtime-js/LICENSE.md @@ -0,0 +1,22 @@ +# MIT License + +Copyright (c) 2020 Supabase + +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/@supabase/realtime-js/README.md b/node_modules/@supabase/realtime-js/README.md new file mode 100644 index 0000000..c4b2867 --- /dev/null +++ b/node_modules/@supabase/realtime-js/README.md @@ -0,0 +1,222 @@ +
+

+ + + + + Supabase Logo + + + +

Supabase Realtime Client

+ +

Send ephemeral messages with Broadcast, track and synchronize state with Presence, and listen to database changes with Postgres Change Data Capture (CDC).

+ +

+ Guides + · + Reference Docs + · + Multiplayer Demo +

+

+ +# Overview + +This client enables you to use the following Supabase Realtime's features: + +- **Broadcast**: send ephemeral messages from client to clients with minimal latency. Use cases include sharing cursor positions between users. +- **Presence**: track and synchronize shared state across clients with the help of CRDTs. Use cases include tracking which users are currently viewing a specific webpage. +- **Postgres Change Data Capture (CDC)**: listen for changes in your PostgreSQL database and send them to clients. + +# Usage + +## Installing the Package + +```bash +npm install @supabase/realtime-js +``` + +## Creating a Channel + +```js +import { RealtimeClient } from '@supabase/realtime-js' + +const client = new RealtimeClient(REALTIME_URL, { + params: { + apikey: API_KEY, + eventsPerSecond: 10, + }, +}) + +const channel = client.channel('test-channel', {}) + +channel.subscribe((status, err) => { + if (status === 'SUBSCRIBED') { + console.log('Connected!') + } + + if (status === 'CHANNEL_ERROR') { + console.log(`There was an error subscribing to channel: ${err.message}`) + } + + if (status === 'TIMED_OUT') { + console.log('Realtime server did not respond in time.') + } + + if (status === 'CLOSED') { + console.log('Realtime channel was unexpectedly closed.') + } +}) +``` + +### Notes: + +- `REALTIME_URL` is `'ws://localhost:4000/socket'` when developing locally and `'wss://.supabase.co/realtime/v1'` when connecting to your Supabase project. +- `API_KEY` is a JWT whose claims must contain `exp` and `role` (existing database role). +- Channel name can be any `string`. +- `eventsPerSecond`, or client-side rate limiting, enforces the number of events sent to the Realtime server uniformly spread across a second. The default is 10, which means that the client can send one event, whether that's **Broadcast**/**Presence**/**Postgres CDC**, every 100 milliseconds. You may change this as you see fit, and choose to disable by passing in a negative number, but note that the server's rate limiting will need to be updated accordingly. You can learn more about Realtime's rate limits here: https://supabase.com/docs/guides/realtime/rate-limits. + +## Broadcast + +Your client can send and receive messages based on the `event`. + +```js +// Setup... + +const channel = client.channel('broadcast-test', { broadcast: { ack: false, self: false } }) + +channel.on('broadcast', { event: 'some-event' }, (payload) => + console.log(payload) +) + +channel.subscribe(async (status) => { + if (status === 'SUBSCRIBED') { + // Send message to other clients listening to 'broadcast-test' channel + await channel.send({ + type: 'broadcast', + event: 'some-event', + payload: { hello: 'world' }, + }) + } +}) +``` + +### Notes: + +- Setting `ack` to `true` means that the `channel.send` promise will resolve once server replies with acknowledgement that it received the broadcast message request. +- Setting `self` to `true` means that the client will receive the broadcast message it sent out. + +## Presence + +Your client can track and sync state that's stored in the channel. + +```js +// Setup... + +const channel = client.channel( + 'presence-test', + { + config: { + presence: { + key: '' + } + } + } +) + +channel.on('presence', { event: 'sync' }, () => { + console.log('Online users: ', channel.presenceState()) +}) + +channel.on('presence', { event: 'join' }, ({ newPresences }) => { + console.log('New users have joined: ', newPresences) +}) + +channel.on('presence', { event: 'leave' }, ({ leftPresences }) => { + console.log('Users have left: ', leftPresences) +}) + +channel.subscribe(async (status) => { + if (status === 'SUBSCRIBED') { + const status = await channel.track({ 'user_id': 1 }) + console.log(status) + } +}) +``` + +## Postgres CDC + +Receive database changes on the client. + +```js +// Setup... + +const channel = client.channel('db-changes') + +channel.on('postgres_changes', { event: '*', schema: 'public' }, (payload) => { + console.log('All changes in public schema: ', payload) +}) + +channel.on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'messages' }, (payload) => { + console.log('All inserts in messages table: ', payload) +}) + +channel.on('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'users', filter: 'username=eq.Realtime' }, (payload) => { + console.log('All updates on users table when username is Realtime: ', payload) +}) + +channel.subscribe(async (status) => { + if (status === 'SUBSCRIBED') { + console.log('Ready to receive database changes!') + } +}) +``` + +## Get All Channels + +You can see all the channels that your client has instantiatied. + +```js +// Setup... + +client.getChannels() +``` + +## Cleanup + +It is highly recommended that you clean up your channels after you're done with them. + +- Remove a single channel + +```js +// Setup... + +const channel = client.channel('some-channel-to-remove') + +channel.subscribe() + +client.removeChannel(channel) +``` + +- Remove all channels + +```js +// Setup... + +const channel1 = client.channel('a-channel-to-remove') +const channel2 = client.channel('another-channel-to-remove') + +channel1.subscribe() +channel2.subscribe() + +client.removeAllChannels() +``` + +## Credits + +This repo draws heavily from [phoenix-js](https://github.com/phoenixframework/phoenix/tree/master/assets/js/phoenix). + +## License + +MIT. diff --git a/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.d.ts b/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.d.ts new file mode 100644 index 0000000..a3489f6 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.d.ts @@ -0,0 +1,199 @@ +import { CHANNEL_STATES } from './lib/constants'; +import Push from './lib/push'; +import type RealtimeClient from './RealtimeClient'; +import Timer from './lib/timer'; +import RealtimePresence, { REALTIME_PRESENCE_LISTEN_EVENTS } from './RealtimePresence'; +import type { RealtimePresenceJoinPayload, RealtimePresenceLeavePayload, RealtimePresenceState } from './RealtimePresence'; +export declare type RealtimeChannelOptions = { + config: { + /** + * self option enables client to receive message it broadcast + * ack option instructs server to acknowledge that broadcast message was received + */ + broadcast?: { + self?: boolean; + ack?: boolean; + }; + /** + * key option is used to track presence payload across clients + */ + presence?: { + key?: string; + }; + }; +}; +declare type RealtimePostgresChangesPayloadBase = { + schema: string; + table: string; + commit_timestamp: string; + errors: string[]; +}; +export declare type RealtimePostgresInsertPayload = RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`; + new: T; + old: {}; +}; +export declare type RealtimePostgresUpdatePayload = RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`; + new: T; + old: Partial; +}; +export declare type RealtimePostgresDeletePayload = RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`; + new: {}; + old: Partial; +}; +export declare type RealtimePostgresChangesPayload = RealtimePostgresInsertPayload | RealtimePostgresUpdatePayload | RealtimePostgresDeletePayload; +export declare type RealtimePostgresChangesFilter = { + /** + * The type of database change to listen to. + */ + event: T; + /** + * The database schema to listen to. + */ + schema: string; + /** + * The database table to listen to. + */ + table?: string; + /** + * Receive database changes when filter is matched. + */ + filter?: string; +}; +export declare type RealtimeChannelSendResponse = 'ok' | 'timed out' | 'rate limited'; +export declare enum REALTIME_POSTGRES_CHANGES_LISTEN_EVENT { + ALL = "*", + INSERT = "INSERT", + UPDATE = "UPDATE", + DELETE = "DELETE" +} +export declare enum REALTIME_LISTEN_TYPES { + BROADCAST = "broadcast", + PRESENCE = "presence", + /** + * listen to Postgres changes. + */ + POSTGRES_CHANGES = "postgres_changes" +} +export declare enum REALTIME_SUBSCRIBE_STATES { + SUBSCRIBED = "SUBSCRIBED", + TIMED_OUT = "TIMED_OUT", + CLOSED = "CLOSED", + CHANNEL_ERROR = "CHANNEL_ERROR" +} +/** A channel is the basic building block of Realtime + * and narrows the scope of data flow to subscribed clients. + * You can think of a channel as a chatroom where participants are able to see who's online + * and send and receive messages. + **/ +export default class RealtimeChannel { + /** Topic name can be any string. */ + topic: string; + params: RealtimeChannelOptions; + socket: RealtimeClient; + bindings: { + [key: string]: { + type: string; + filter: { + [key: string]: any; + }; + callback: Function; + id?: string; + }[]; + }; + timeout: number; + state: CHANNEL_STATES; + joinedOnce: boolean; + joinPush: Push; + rejoinTimer: Timer; + pushBuffer: Push[]; + presence: RealtimePresence; + constructor( + /** Topic name can be any string. */ + topic: string, params: RealtimeChannelOptions, socket: RealtimeClient); + /** Subscribe registers your client with the server */ + subscribe(callback?: (status: `${REALTIME_SUBSCRIBE_STATES}`, err?: Error) => void, timeout?: number): RealtimeChannel; + presenceState(): RealtimePresenceState; + track(payload: { + [key: string]: any; + }, opts?: { + [key: string]: any; + }): Promise; + untrack(opts?: { + [key: string]: any; + }): Promise; + /** + * Creates an event handler that listens to changes. + */ + on(type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, filter: { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.SYNC}`; + }, callback: () => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, filter: { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.JOIN}`; + }, callback: (payload: RealtimePresenceJoinPayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, filter: { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.LEAVE}`; + }, callback: (payload: RealtimePresenceLeavePayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL}`>, callback: (payload: RealtimePostgresChangesPayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`>, callback: (payload: RealtimePostgresInsertPayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`>, callback: (payload: RealtimePostgresUpdatePayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`>, callback: (payload: RealtimePostgresDeletePayload) => void): RealtimeChannel; + /** + * The following is placed here to display on supabase.com/docs/reference/javascript/subscribe. + * @param type One of "broadcast", "presence", or "postgres_changes". + * @param filter Custom object specific to the Realtime feature detailing which payloads to receive. + * @param callback Function to be invoked when event handler is triggered. + */ + on(type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, filter: { + event: string; + }, callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`; + event: string; + [key: string]: any; + }) => void): RealtimeChannel; + send(payload: { + type: string; + [key: string]: any; + }, opts?: { + [key: string]: any; + }): Promise; + updateJoinPayload(payload: { + [key: string]: any; + }): void; + /** + * Leaves the channel. + * + * Unsubscribes from server events, and instructs channel to terminate on server. + * Triggers onClose() hooks. + * + * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: + * channel.unsubscribe().receive("ok", () => alert("left!") ) + */ + unsubscribe(timeout?: number): Promise<'ok' | 'timed out' | 'error'>; +} +export {}; +//# sourceMappingURL=RealtimeChannel.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.d.ts.map b/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.d.ts.map new file mode 100644 index 0000000..24156c0 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.d.ts.map @@ -0,0 +1 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GAAG,CAAA;KAAE,EAC7C,IAAI,GAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAO,GAChC,OAAO,CAAC,2BAA2B,CAAC;IAwBvC,iBAAiB,CAAC,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,GAAG,IAAI;IAIxD;;;;;;;;OAQG;IACH,WAAW,CAAC,OAAO,SAAe,GAAG,OAAO,CAAC,IAAI,GAAG,WAAW,GAAG,OAAO,CAAC;CAqS3E"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js b/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js new file mode 100644 index 0000000..0a33d19 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js @@ -0,0 +1,481 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +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.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_LISTEN_TYPES = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = void 0; +const constants_1 = require("./lib/constants"); +const push_1 = __importDefault(require("./lib/push")); +const timer_1 = __importDefault(require("./lib/timer")); +const RealtimePresence_1 = __importDefault(require("./RealtimePresence")); +const Transformers = __importStar(require("./lib/transformers")); +var REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; +(function (REALTIME_POSTGRES_CHANGES_LISTEN_EVENT) { + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["ALL"] = "*"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["INSERT"] = "INSERT"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["UPDATE"] = "UPDATE"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["DELETE"] = "DELETE"; +})(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT || (exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = {})); +var REALTIME_LISTEN_TYPES; +(function (REALTIME_LISTEN_TYPES) { + REALTIME_LISTEN_TYPES["BROADCAST"] = "broadcast"; + REALTIME_LISTEN_TYPES["PRESENCE"] = "presence"; + /** + * listen to Postgres changes. + */ + REALTIME_LISTEN_TYPES["POSTGRES_CHANGES"] = "postgres_changes"; +})(REALTIME_LISTEN_TYPES = exports.REALTIME_LISTEN_TYPES || (exports.REALTIME_LISTEN_TYPES = {})); +var REALTIME_SUBSCRIBE_STATES; +(function (REALTIME_SUBSCRIBE_STATES) { + REALTIME_SUBSCRIBE_STATES["SUBSCRIBED"] = "SUBSCRIBED"; + REALTIME_SUBSCRIBE_STATES["TIMED_OUT"] = "TIMED_OUT"; + REALTIME_SUBSCRIBE_STATES["CLOSED"] = "CLOSED"; + REALTIME_SUBSCRIBE_STATES["CHANNEL_ERROR"] = "CHANNEL_ERROR"; +})(REALTIME_SUBSCRIBE_STATES = exports.REALTIME_SUBSCRIBE_STATES || (exports.REALTIME_SUBSCRIBE_STATES = {})); +/** A channel is the basic building block of Realtime + * and narrows the scope of data flow to subscribed clients. + * You can think of a channel as a chatroom where participants are able to see who's online + * and send and receive messages. + **/ +class RealtimeChannel { + constructor( + /** Topic name can be any string. */ + topic, params = { config: {} }, socket) { + this.topic = topic; + this.params = params; + this.socket = socket; + this.bindings = {}; + this.state = constants_1.CHANNEL_STATES.closed; + this.joinedOnce = false; + this.pushBuffer = []; + this.params.config = Object.assign({ + broadcast: { ack: false, self: false }, + presence: { key: '' }, + }, params.config); + this.timeout = this.socket.timeout; + this.joinPush = new push_1.default(this, constants_1.CHANNEL_EVENTS.join, this.params, this.timeout); + this.rejoinTimer = new timer_1.default(() => this._rejoinUntilConnected(), this.socket.reconnectAfterMs); + this.joinPush.receive('ok', () => { + this.state = constants_1.CHANNEL_STATES.joined; + this.rejoinTimer.reset(); + this.pushBuffer.forEach((pushEvent) => pushEvent.send()); + this.pushBuffer = []; + }); + this._onClose(() => { + this.rejoinTimer.reset(); + this.socket.log('channel', `close ${this.topic} ${this._joinRef()}`); + this.state = constants_1.CHANNEL_STATES.closed; + this.socket._remove(this); + }); + this._onError((reason) => { + if (this._isLeaving() || this._isClosed()) { + return; + } + this.socket.log('channel', `error ${this.topic}`, reason); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this.joinPush.receive('timeout', () => { + if (!this._isJoining()) { + return; + } + this.socket.log('channel', `timeout ${this.topic}`, this.joinPush.timeout); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this._on(constants_1.CHANNEL_EVENTS.reply, {}, (payload, ref) => { + this._trigger(this._replyEventName(ref), payload); + }); + this.presence = new RealtimePresence_1.default(this); + } + /** Subscribe registers your client with the server */ + subscribe(callback, timeout = this.timeout) { + var _a, _b; + if (this.joinedOnce) { + throw `tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance`; + } + else { + const { config: { broadcast, presence }, } = this.params; + this._onError((e) => callback && callback('CHANNEL_ERROR', e)); + this._onClose(() => callback && callback('CLOSED')); + const accessTokenPayload = {}; + const config = { + broadcast, + presence, + postgres_changes: (_b = (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.map((r) => r.filter)) !== null && _b !== void 0 ? _b : [], + }; + if (this.socket.accessToken) { + accessTokenPayload.access_token = this.socket.accessToken; + } + this.updateJoinPayload(Object.assign({ config }, accessTokenPayload)); + this.joinedOnce = true; + this._rejoin(timeout); + this.joinPush + .receive('ok', ({ postgres_changes: serverPostgresFilters, }) => { + var _a; + this.socket.accessToken && + this.socket.setAuth(this.socket.accessToken); + if (serverPostgresFilters === undefined) { + callback && callback('SUBSCRIBED'); + return; + } + else { + const clientPostgresBindings = this.bindings.postgres_changes; + const bindingsLen = (_a = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a !== void 0 ? _a : 0; + const newPostgresBindings = []; + for (let i = 0; i < bindingsLen; i++) { + const clientPostgresBinding = clientPostgresBindings[i]; + const { filter: { event, schema, table, filter }, } = clientPostgresBinding; + const serverPostgresFilter = serverPostgresFilters && serverPostgresFilters[i]; + if (serverPostgresFilter && + serverPostgresFilter.event === event && + serverPostgresFilter.schema === schema && + serverPostgresFilter.table === table && + serverPostgresFilter.filter === filter) { + newPostgresBindings.push(Object.assign(Object.assign({}, clientPostgresBinding), { id: serverPostgresFilter.id })); + } + else { + this.unsubscribe(); + callback && + callback('CHANNEL_ERROR', new Error('mismatch between server and client bindings for postgres changes')); + return; + } + } + this.bindings.postgres_changes = newPostgresBindings; + callback && callback('SUBSCRIBED'); + return; + } + }) + .receive('error', (error) => { + callback && + callback('CHANNEL_ERROR', new Error(JSON.stringify(Object.values(error).join(', ') || 'error'))); + return; + }) + .receive('timeout', () => { + callback && callback('TIMED_OUT'); + return; + }); + } + return this; + } + presenceState() { + return this.presence.state; + } + track(payload, opts = {}) { + return __awaiter(this, void 0, void 0, function* () { + return yield this.send({ + type: 'presence', + event: 'track', + payload, + }, opts.timeout || this.timeout); + }); + } + untrack(opts = {}) { + return __awaiter(this, void 0, void 0, function* () { + return yield this.send({ + type: 'presence', + event: 'untrack', + }, opts); + }); + } + on(type, filter, callback) { + return this._on(type, filter, callback); + } + send(payload, opts = {}) { + return new Promise((resolve) => { + var _a, _b, _c; + const push = this._push(payload.type, payload, opts.timeout || this.timeout); + if (push.rateLimited) { + resolve('rate limited'); + } + if (payload.type === 'broadcast' && + !((_c = (_b = (_a = this.params) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.broadcast) === null || _c === void 0 ? void 0 : _c.ack)) { + resolve('ok'); + } + push.receive('ok', () => resolve('ok')); + push.receive('timeout', () => resolve('timed out')); + }); + } + updateJoinPayload(payload) { + this.joinPush.updatePayload(payload); + } + /** + * Leaves the channel. + * + * Unsubscribes from server events, and instructs channel to terminate on server. + * Triggers onClose() hooks. + * + * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: + * channel.unsubscribe().receive("ok", () => alert("left!") ) + */ + unsubscribe(timeout = this.timeout) { + this.state = constants_1.CHANNEL_STATES.leaving; + const onClose = () => { + this.socket.log('channel', `leave ${this.topic}`); + this._trigger(constants_1.CHANNEL_EVENTS.close, 'leave', this._joinRef()); + }; + this.rejoinTimer.reset(); + // Destroy joinPush to avoid connection timeouts during unscription phase + this.joinPush.destroy(); + return new Promise((resolve) => { + const leavePush = new push_1.default(this, constants_1.CHANNEL_EVENTS.leave, {}, timeout); + leavePush + .receive('ok', () => { + onClose(); + resolve('ok'); + }) + .receive('timeout', () => { + onClose(); + resolve('timed out'); + }) + .receive('error', () => { + resolve('error'); + }); + leavePush.send(); + if (!this._canPush()) { + leavePush.trigger('ok', {}); + } + }); + } + /** @internal */ + _push(event, payload, timeout = this.timeout) { + if (!this.joinedOnce) { + throw `tried to push '${event}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`; + } + let pushEvent = new push_1.default(this, event, payload, timeout); + if (this._canPush()) { + pushEvent.send(); + } + else { + pushEvent.startTimeout(); + this.pushBuffer.push(pushEvent); + } + return pushEvent; + } + /** + * Overridable message hook + * + * Receives all events for specialized message handling before dispatching to the channel callbacks. + * Must return the payload, modified or unmodified. + * + * @internal + */ + _onMessage(_event, payload, _ref) { + return payload; + } + /** @internal */ + _isMember(topic) { + return this.topic === topic; + } + /** @internal */ + _joinRef() { + return this.joinPush.ref; + } + /** @internal */ + _trigger(type, payload, ref) { + var _a, _b; + const typeLower = type.toLocaleLowerCase(); + const { close, error, leave, join } = constants_1.CHANNEL_EVENTS; + const events = [close, error, leave, join]; + if (ref && events.indexOf(typeLower) >= 0 && ref !== this._joinRef()) { + return; + } + let handledPayload = this._onMessage(typeLower, payload, ref); + if (payload && !handledPayload) { + throw 'channel onMessage callbacks must return the payload, modified or unmodified'; + } + if (['insert', 'update', 'delete'].includes(typeLower)) { + (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.filter((bind) => { + var _a, _b, _c; + return (((_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event) === '*' || + ((_c = (_b = bind.filter) === null || _b === void 0 ? void 0 : _b.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower); + }).map((bind) => bind.callback(handledPayload, ref)); + } + else { + (_b = this.bindings[typeLower]) === null || _b === void 0 ? void 0 : _b.filter((bind) => { + var _a, _b, _c, _d, _e, _f; + if (['broadcast', 'presence', 'postgres_changes'].includes(typeLower)) { + if ('id' in bind) { + const bindId = bind.id; + const bindEvent = (_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event; + return (bindId && + ((_b = payload.ids) === null || _b === void 0 ? void 0 : _b.includes(bindId)) && + (bindEvent === '*' || + (bindEvent === null || bindEvent === void 0 ? void 0 : bindEvent.toLocaleLowerCase()) === + ((_c = payload.data) === null || _c === void 0 ? void 0 : _c.type.toLocaleLowerCase()))); + } + else { + const bindEvent = (_e = (_d = bind === null || bind === void 0 ? void 0 : bind.filter) === null || _d === void 0 ? void 0 : _d.event) === null || _e === void 0 ? void 0 : _e.toLocaleLowerCase(); + return (bindEvent === '*' || + bindEvent === ((_f = payload === null || payload === void 0 ? void 0 : payload.event) === null || _f === void 0 ? void 0 : _f.toLocaleLowerCase())); + } + } + else { + return bind.type.toLocaleLowerCase() === typeLower; + } + }).map((bind) => { + if (typeof handledPayload === 'object' && 'ids' in handledPayload) { + const postgresChanges = handledPayload.data; + const { schema, table, commit_timestamp, type, errors } = postgresChanges; + const enrichedPayload = { + schema: schema, + table: table, + commit_timestamp: commit_timestamp, + eventType: type, + new: {}, + old: {}, + errors: errors, + }; + handledPayload = Object.assign(Object.assign({}, enrichedPayload), this._getPayloadRecords(postgresChanges)); + } + bind.callback(handledPayload, ref); + }); + } + } + /** @internal */ + _isClosed() { + return this.state === constants_1.CHANNEL_STATES.closed; + } + /** @internal */ + _isJoined() { + return this.state === constants_1.CHANNEL_STATES.joined; + } + /** @internal */ + _isJoining() { + return this.state === constants_1.CHANNEL_STATES.joining; + } + /** @internal */ + _isLeaving() { + return this.state === constants_1.CHANNEL_STATES.leaving; + } + /** @internal */ + _replyEventName(ref) { + return `chan_reply_${ref}`; + } + /** @internal */ + _on(type, filter, callback) { + const typeLower = type.toLocaleLowerCase(); + const binding = { + type: typeLower, + filter: filter, + callback: callback, + }; + if (this.bindings[typeLower]) { + this.bindings[typeLower].push(binding); + } + else { + this.bindings[typeLower] = [binding]; + } + return this; + } + /** @internal */ + _off(type, filter) { + const typeLower = type.toLocaleLowerCase(); + this.bindings[typeLower] = this.bindings[typeLower].filter((bind) => { + var _a; + return !(((_a = bind.type) === null || _a === void 0 ? void 0 : _a.toLocaleLowerCase()) === typeLower && + RealtimeChannel.isEqual(bind.filter, filter)); + }); + return this; + } + /** @internal */ + static isEqual(obj1, obj2) { + if (Object.keys(obj1).length !== Object.keys(obj2).length) { + return false; + } + for (const k in obj1) { + if (obj1[k] !== obj2[k]) { + return false; + } + } + return true; + } + /** @internal */ + _rejoinUntilConnected() { + this.rejoinTimer.scheduleTimeout(); + if (this.socket.isConnected()) { + this._rejoin(); + } + } + /** + * Registers a callback that will be executed when the channel closes. + * + * @internal + */ + _onClose(callback) { + this._on(constants_1.CHANNEL_EVENTS.close, {}, callback); + } + /** + * Registers a callback that will be executed when the channel encounteres an error. + * + * @internal + */ + _onError(callback) { + this._on(constants_1.CHANNEL_EVENTS.error, {}, (reason) => callback(reason)); + } + /** + * Returns `true` if the socket is connected and the channel has been joined. + * + * @internal + */ + _canPush() { + return this.socket.isConnected() && this._isJoined(); + } + /** @internal */ + _rejoin(timeout = this.timeout) { + if (this._isLeaving()) { + return; + } + this.socket._leaveOpenTopic(this.topic); + this.state = constants_1.CHANNEL_STATES.joining; + this.joinPush.resend(timeout); + } + /** @internal */ + _getPayloadRecords(payload) { + const records = { + new: {}, + old: {}, + }; + if (payload.type === 'INSERT' || payload.type === 'UPDATE') { + records.new = Transformers.convertChangeData(payload.columns, payload.record); + } + if (payload.type === 'UPDATE' || payload.type === 'DELETE') { + records.old = Transformers.convertChangeData(payload.columns, payload.old_record); + } + return records; + } +} +exports.default = RealtimeChannel; +//# sourceMappingURL=RealtimeChannel.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js.map b/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js.map new file mode 100644 index 0000000..70c4803 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimeChannel.js","sourceRoot":"","sources":["../../src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AAK,EAAE,EAAE,EAAE,CAAC,MAAc,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAA;IAC1E,CAAC;IAED;;;;OAIG;IACK,QAAQ;QACd,OAAO,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,CAAC,SAAS,EAAE,CAAA;IACtD,CAAC;IAED,gBAAgB;IACR,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO;QACpC,IAAI,IAAI,CAAC,UAAU,EAAE,EAAE;YACrB,OAAM;SACP;QACD,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QACvC,IAAI,CAAC,KAAK,GAAG,0BAAc,CAAC,OAAO,CAAA;QACnC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;IAC/B,CAAC;IAED,gBAAgB;IACR,kBAAkB,CAAC,OAAY;QACrC,MAAM,OAAO,GAAG;YACd,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,EAAE;SACR,CAAA;QAED,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE;YAC1D,OAAO,CAAC,GAAG,GAAG,YAAY,CAAC,iBAAiB,CAC1C,OAAO,CAAC,OAAO,EACf,OAAO,CAAC,MAAM,CACf,CAAA;SACF;QAED,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE;YAC1D,OAAO,CAAC,GAAG,GAAG,YAAY,CAAC,iBAAiB,CAC1C,OAAO,CAAC,OAAO,EACf,OAAO,CAAC,UAAU,CACnB,CAAA;SACF;QAED,OAAO,OAAO,CAAA;IAChB,CAAC;CACF;AAxmBD,kCAwmBC"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.d.ts b/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.d.ts new file mode 100644 index 0000000..8d3d3df --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.d.ts @@ -0,0 +1,129 @@ +import { CONNECTION_STATE } from './lib/constants'; +import Timer from './lib/timer'; +import Serializer from './lib/serializer'; +import RealtimeChannel from './RealtimeChannel'; +import type { RealtimeChannelOptions } from './RealtimeChannel'; +export declare type RealtimeClientOptions = { + transport?: WebSocket; + timeout?: number; + heartbeatIntervalMs?: number; + logger?: Function; + encode?: Function; + decode?: Function; + reconnectAfterMs?: Function; + headers?: { + [key: string]: string; + }; + params?: { + [key: string]: any; + }; + log_level?: 'info' | 'debug' | 'warn' | 'error'; +}; +export declare type RealtimeMessage = { + topic: string; + event: string; + payload: any; + ref: string; + join_ref?: string; +}; +export declare type RealtimeRemoveChannelResponse = 'ok' | 'timed out' | 'error'; +export default class RealtimeClient { + accessToken: string | null; + channels: RealtimeChannel[]; + endPoint: string; + headers?: { + [key: string]: string; + }; + params?: { + [key: string]: string; + }; + timeout: number; + transport: any; + heartbeatIntervalMs: number; + heartbeatTimer: ReturnType | undefined; + pendingHeartbeatRef: string | null; + ref: number; + reconnectTimer: Timer; + logger: Function; + encode: Function; + decode: Function; + reconnectAfterMs: Function; + conn: WebSocket | null; + sendBuffer: Function[]; + serializer: Serializer; + stateChangeCallbacks: { + open: Function[]; + close: Function[]; + error: Function[]; + message: Function[]; + }; + eventsPerSecondLimitMs: number; + inThrottle: boolean; + /** + * Initializes the Socket. + * + * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) + * @param options.transport The Websocket Transport, for example WebSocket. + * @param options.timeout The default timeout in milliseconds to trigger push timeouts. + * @param options.params The optional params to pass when connecting. + * @param options.headers The optional headers to pass when connecting. + * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. + * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } + * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) + * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. + * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. + */ + constructor(endPoint: string, options?: RealtimeClientOptions); + /** + * Connects the socket, unless already connected. + */ + connect(): void; + /** + * Disconnects the socket. + * + * @param code A numeric status code to send on disconnect. + * @param reason A custom reason for the disconnect. + */ + disconnect(code?: number, reason?: string): void; + /** + * Returns all created channels + */ + getChannels(): RealtimeChannel[]; + /** + * Unsubscribes and removes a single channel + * @param channel A RealtimeChannel instance + */ + removeChannel(channel: RealtimeChannel): Promise; + /** + * Unsubscribes and removes all channels + */ + removeAllChannels(): Promise; + /** + * Logs the message. + * + * For customized logging, `this.logger` can be overridden. + */ + log(kind: string, msg: string, data?: any): void; + /** + * Returns the current state of the socket. + */ + connectionState(): CONNECTION_STATE; + /** + * Returns `true` is the connection is open. + */ + isConnected(): boolean; + channel(topic: string, params?: RealtimeChannelOptions): RealtimeChannel; + /** + * Push out a message if the socket is connected. + * + * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. + */ + push(data: RealtimeMessage): 'rate limited' | void; + /** + * Sets the JWT access token used for channel subscription authorization and Realtime RLS. + * + * @param token A JWT string. + */ + setAuth(token: string | null): void; +} +//# sourceMappingURL=RealtimeClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.d.ts.map b/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.d.ts.map new file mode 100644 index 0000000..b5a0bd5 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimeClient.d.ts","sourceRoot":"","sources":["../../src/RealtimeClient.ts"],"names":[],"mappings":"AACA,OAAO,EAQL,gBAAgB,EACjB,MAAM,iBAAiB,CAAA;AACxB,OAAO,KAAK,MAAM,aAAa,CAAA;AAC/B,OAAO,UAAU,MAAM,kB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AE,MAAM,EAAE,IAAI,CAAC,EAAE,GAAG;IAIzC;;OAEG;IACH,eAAe,IAAI,gBAAgB;IAanC;;OAEG;IACH,WAAW,IAAI,OAAO;IAItB,OAAO,CACL,KAAK,EAAE,MAAM,EACb,MAAM,GAAE,sBAAuC,GAC9C,eAAe;IAUlB;;;;OAIG;IACH,IAAI,CAAC,IAAI,EAAE,eAAe,GAAG,cAAc,GAAG,IAAI;IAsBlD;;;;OAIG;IACH,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI;CAsMpC"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.js b/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.js new file mode 100644 index 0000000..5ceee78 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.js @@ -0,0 +1,382 @@ +"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 websocket_1 = require("websocket"); +const constants_1 = require("./lib/constants"); +const timer_1 = __importDefault(require("./lib/timer")); +const serializer_1 = __importDefault(require("./lib/serializer")); +const RealtimeChannel_1 = __importDefault(require("./RealtimeChannel")); +const noop = () => { }; +class RealtimeClient { + /** + * Initializes the Socket. + * + * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) + * @param options.transport The Websocket Transport, for example WebSocket. + * @param options.timeout The default timeout in milliseconds to trigger push timeouts. + * @param options.params The optional params to pass when connecting. + * @param options.headers The optional headers to pass when connecting. + * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. + * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } + * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) + * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. + * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. + */ + constructor(endPoint, options) { + var _a; + this.accessToken = null; + this.channels = []; + this.endPoint = ''; + this.headers = constants_1.DEFAULT_HEADERS; + this.params = {}; + this.timeout = constants_1.DEFAULT_TIMEOUT; + this.transport = websocket_1.w3cwebsocket; + this.heartbeatIntervalMs = 30000; + this.heartbeatTimer = undefined; + this.pendingHeartbeatRef = null; + this.ref = 0; + this.logger = noop; + this.conn = null; + this.sendBuffer = []; + this.serializer = new serializer_1.default(); + this.stateChangeCallbacks = { + open: [], + close: [], + error: [], + message: [], + }; + this.eventsPerSecondLimitMs = 100; + this.inThrottle = false; + this.endPoint = `${endPoint}/${constants_1.TRANSPORTS.websocket}`; + if (options === null || options === void 0 ? void 0 : options.params) + this.params = options.params; + if (options === null || options === void 0 ? void 0 : options.headers) + this.headers = Object.assign(Object.assign({}, this.headers), options.headers); + if (options === null || options === void 0 ? void 0 : options.timeout) + this.timeout = options.timeout; + if (options === null || options === void 0 ? void 0 : options.logger) + this.logger = options.logger; + if (options === null || options === void 0 ? void 0 : options.transport) + this.transport = options.transport; + if (options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) + this.heartbeatIntervalMs = options.heartbeatIntervalMs; + const eventsPerSecond = (_a = options === null || options === void 0 ? void 0 : options.params) === null || _a === void 0 ? void 0 : _a.eventsPerSecond; + if (eventsPerSecond) + this.eventsPerSecondLimitMs = Math.floor(1000 / eventsPerSecond); + this.reconnectAfterMs = (options === null || options === void 0 ? void 0 : options.reconnectAfterMs) + ? options.reconnectAfterMs + : (tries) => { + return [1000, 2000, 5000, 10000][tries - 1] || 10000; + }; + this.encode = (options === null || options === void 0 ? void 0 : options.encode) + ? options.encode + : (payload, callback) => { + return callback(JSON.stringify(payload)); + }; + this.decode = (options === null || options === void 0 ? void 0 : options.decode) + ? options.decode + : this.serializer.decode.bind(this.serializer); + this.reconnectTimer = new timer_1.default(() => __awaiter(this, void 0, void 0, function* () { + this.disconnect(); + this.connect(); + }), this.reconnectAfterMs); + } + /** + * Connects the socket, unless already connected. + */ + connect() { + if (this.conn) { + return; + } + this.conn = new this.transport(this._endPointURL(), [], null, this.headers); + if (this.conn) { + this.conn.binaryType = 'arraybuffer'; + this.conn.onopen = () => this._onConnOpen(); + this.conn.onerror = (error) => this._onConnError(error); + this.conn.onmessage = (event) => this._onConnMessage(event); + this.conn.onclose = (event) => this._onConnClose(event); + } + } + /** + * Disconnects the socket. + * + * @param code A numeric status code to send on disconnect. + * @param reason A custom reason for the disconnect. + */ + disconnect(code, reason) { + if (this.conn) { + this.conn.onclose = function () { }; // noop + if (code) { + this.conn.close(code, reason !== null && reason !== void 0 ? reason : ''); + } + else { + this.conn.close(); + } + this.conn = null; + // remove open handles + this.heartbeatTimer && clearInterval(this.heartbeatTimer); + this.reconnectTimer.reset(); + } + } + /** + * Returns all created channels + */ + getChannels() { + return this.channels; + } + /** + * Unsubscribes and removes a single channel + * @param channel A RealtimeChannel instance + */ + removeChannel(channel) { + return __awaiter(this, void 0, void 0, function* () { + const status = yield channel.unsubscribe(); + if (this.channels.length === 0) { + this.disconnect(); + } + return status; + }); + } + /** + * Unsubscribes and removes all channels + */ + removeAllChannels() { + return __awaiter(this, void 0, void 0, function* () { + const values_1 = yield Promise.all(this.channels.map((channel) => channel.unsubscribe())); + this.disconnect(); + return values_1; + }); + } + /** + * Logs the message. + * + * For customized logging, `this.logger` can be overridden. + */ + log(kind, msg, data) { + this.logger(kind, msg, data); + } + /** + * Returns the current state of the socket. + */ + connectionState() { + switch (this.conn && this.conn.readyState) { + case constants_1.SOCKET_STATES.connecting: + return constants_1.CONNECTION_STATE.Connecting; + case constants_1.SOCKET_STATES.open: + return constants_1.CONNECTION_STATE.Open; + case constants_1.SOCKET_STATES.closing: + return constants_1.CONNECTION_STATE.Closing; + default: + return constants_1.CONNECTION_STATE.Closed; + } + } + /** + * Returns `true` is the connection is open. + */ + isConnected() { + return this.connectionState() === constants_1.CONNECTION_STATE.Open; + } + channel(topic, params = { config: {} }) { + if (!this.isConnected()) { + this.connect(); + } + const chan = new RealtimeChannel_1.default(`realtime:${topic}`, params, this); + this.channels.push(chan); + return chan; + } + /** + * Push out a message if the socket is connected. + * + * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. + */ + push(data) { + const { topic, event, payload, ref } = data; + let callback = () => { + this.encode(data, (result) => { + var _a; + (_a = this.conn) === null || _a === void 0 ? void 0 : _a.send(result); + }); + }; + this.log('push', `${topic} ${event} (${ref})`, payload); + if (this.isConnected()) { + if (['broadcast', 'presence', 'postgres_changes'].includes(event)) { + const isThrottled = this._throttle(callback)(); + if (isThrottled) { + return 'rate limited'; + } + } + else { + callback(); + } + } + else { + this.sendBuffer.push(callback); + } + } + /** + * Sets the JWT access token used for channel subscription authorization and Realtime RLS. + * + * @param token A JWT string. + */ + setAuth(token) { + this.accessToken = token; + this.channels.forEach((channel) => { + token && channel.updateJoinPayload({ access_token: token }); + if (channel.joinedOnce && channel._isJoined()) { + channel._push(constants_1.CHANNEL_EVENTS.access_token, { access_token: token }); + } + }); + } + /** + * Return the next message ref, accounting for overflows + * + * @internal + */ + _makeRef() { + let newRef = this.ref + 1; + if (newRef === this.ref) { + this.ref = 0; + } + else { + this.ref = newRef; + } + return this.ref.toString(); + } + /** + * Unsubscribe from channels with the specified topic. + * + * @internal + */ + _leaveOpenTopic(topic) { + let dupChannel = this.channels.find((c) => c.topic === topic && (c._isJoined() || c._isJoining())); + if (dupChannel) { + this.log('transport', `leaving duplicate topic "${topic}"`); + dupChannel.unsubscribe(); + } + } + /** + * Removes a subscription from the socket. + * + * @param channel An open subscription. + * + * @internal + */ + _remove(channel) { + this.channels = this.channels.filter((c) => c._joinRef() !== channel._joinRef()); + } + /** + * Returns the URL of the websocket. + * + * @internal + */ + _endPointURL() { + return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: constants_1.VSN })); + } + /** @internal */ + _onConnMessage(rawMessage) { + this.decode(rawMessage.data, (msg) => { + let { topic, event, payload, ref } = msg; + if ((ref && ref === this.pendingHeartbeatRef) || + event === (payload === null || payload === void 0 ? void 0 : payload.type)) { + this.pendingHeartbeatRef = null; + } + this.log('receive', `${payload.status || ''} ${topic} ${event} ${(ref && '(' + ref + ')') || ''}`, payload); + this.channels + .filter((channel) => channel._isMember(topic)) + .forEach((channel) => channel._trigger(event, payload, ref)); + this.stateChangeCallbacks.message.forEach((callback) => callback(msg)); + }); + } + /** @internal */ + _onConnOpen() { + this.log('transport', `connected to ${this._endPointURL()}`); + this._flushSendBuffer(); + this.reconnectTimer.reset(); + this.heartbeatTimer && clearInterval(this.heartbeatTimer); + this.heartbeatTimer = setInterval(() => this._sendHeartbeat(), this.heartbeatIntervalMs); + this.stateChangeCallbacks.open.forEach((callback) => callback()); + } + /** @internal */ + _onConnClose(event) { + this.log('transport', 'close', event); + this._triggerChanError(); + this.heartbeatTimer && clearInterval(this.heartbeatTimer); + this.reconnectTimer.scheduleTimeout(); + this.stateChangeCallbacks.close.forEach((callback) => callback(event)); + } + /** @internal */ + _onConnError(error) { + this.log('transport', error.message); + this._triggerChanError(); + this.stateChangeCallbacks.error.forEach((callback) => callback(error)); + } + /** @internal */ + _triggerChanError() { + this.channels.forEach((channel) => channel._trigger(constants_1.CHANNEL_EVENTS.error)); + } + /** @internal */ + _appendParams(url, params) { + if (Object.keys(params).length === 0) { + return url; + } + const prefix = url.match(/\?/) ? '&' : '?'; + const query = new URLSearchParams(params); + return `${url}${prefix}${query}`; + } + /** @internal */ + _flushSendBuffer() { + if (this.isConnected() && this.sendBuffer.length > 0) { + this.sendBuffer.forEach((callback) => callback()); + this.sendBuffer = []; + } + } + /** @internal */ + _sendHeartbeat() { + var _a; + if (!this.isConnected()) { + return; + } + if (this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null; + this.log('transport', 'heartbeat timeout. Attempting to re-establish connection'); + (_a = this.conn) === null || _a === void 0 ? void 0 : _a.close(constants_1.WS_CLOSE_NORMAL, 'hearbeat timeout'); + return; + } + this.pendingHeartbeatRef = this._makeRef(); + this.push({ + topic: 'phoenix', + event: 'heartbeat', + payload: {}, + ref: this.pendingHeartbeatRef, + }); + this.setAuth(this.accessToken); + } + /** @internal */ + _throttle(callback, eventsPerSecondLimitMs = this.eventsPerSecondLimitMs) { + return () => { + if (this.inThrottle) + return true; + callback(); + if (eventsPerSecondLimitMs > 0) { + this.inThrottle = true; + setTimeout(() => { + this.inThrottle = false; + }, eventsPerSecondLimitMs); + } + return false; + }; + } +} +exports.default = RealtimeClient; +//# sourceMappingURL=RealtimeClient.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.js.map b/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.js.map new file mode 100644 index 0000000..b41135f --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/RealtimeClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimeClient.js","sourceRoot":"","sources":["../../src/RealtimeClient.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,yCAAwC;AACxC,+CASwB;AACxB,wDAA+B;AAC/B,kEAAyC;AACzC,wEAA+C;AA0B/C,MAAM,IAAI,GAAG,GAAG,EAAE,GAAE,CAAC,CAAA;AAErB,MAAqB,cAAc;IAkCjC;;;;;;;;;;;;;OAaG;IACH,YAAY,QAAgB,EAAE,OAA+B;;QA/C7D,gBAAW,GAAkB,IAAI,CAAA;QACjC,aAAQ,GAAsB,EAAE,CAAA;QAChC,aAAQ,GAAW,EAAE,C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AAG,CACN,WAAW,EACX,0DAA0D,CAC3D,CAAA;YACD,MAAA,IAAI,CAAC,IAAI,0CAAE,KAAK,CAAC,2BAAe,EAAE,kBAAkB,CAAC,CAAA;YACrD,OAAM;SACP;QACD,IAAI,CAAC,mBAAmB,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAA;QAC1C,IAAI,CAAC,IAAI,CAAC;YACR,KAAK,EAAE,SAAS;YAChB,KAAK,EAAE,WAAW;YAClB,OAAO,EAAE,EAAE;YACX,GAAG,EAAE,IAAI,CAAC,mBAAmB;SAC9B,CAAC,CAAA;QACF,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAA;IAChC,CAAC;IAED,gBAAgB;IACR,SAAS,CACf,QAAkB,EAClB,yBAAiC,IAAI,CAAC,sBAAsB;QAE5D,OAAO,GAAG,EAAE;YACV,IAAI,IAAI,CAAC,UAAU;gBAAE,OAAO,IAAI,CAAA;YAEhC,QAAQ,EAAE,CAAA;YAEV,IAAI,sBAAsB,GAAG,CAAC,EAAE;gBAC9B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;gBAEtB,UAAU,CAAC,GAAG,EAAE;oBACd,IAAI,CAAC,UAAU,GAAG,KAAK,CAAA;gBACzB,CAAC,EAAE,sBAAsB,CAAC,CAAA;aAC3B;YAED,OAAO,KAAK,CAAA;QACd,CAAC,CAAA;IACH,CAAC;CACF;AA7aD,iCA6aC"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.d.ts b/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.d.ts new file mode 100644 index 0000000..2972a4c --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.d.ts @@ -0,0 +1,67 @@ +import type { PresenceOpts, PresenceOnJoinCallback, PresenceOnLeaveCallback } from 'phoenix'; +import type RealtimeChannel from './RealtimeChannel'; +declare type Presence = { + presence_ref: string; +} & T; +export declare type RealtimePresenceState = { + [key: string]: Presence[]; +}; +export declare type RealtimePresenceJoinPayload = { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.JOIN}`; + key: string; + currentPresences: Presence[]; + newPresences: Presence[]; +}; +export declare type RealtimePresenceLeavePayload = { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.LEAVE}`; + key: string; + currentPresences: Presence[]; + leftPresences: Presence[]; +}; +export declare enum REALTIME_PRESENCE_LISTEN_EVENTS { + SYNC = "sync", + JOIN = "join", + LEAVE = "leave" +} +declare type RawPresenceState = { + [key: string]: { + metas: { + phx_ref?: string; + phx_ref_prev?: string; + [key: string]: any; + }[]; + }; +}; +declare type RawPresenceDiff = { + joins: RawPresenceState; + leaves: RawPresenceState; +}; +export default class RealtimePresence { + channel: RealtimeChannel; + state: RealtimePresenceState; + pendingDiffs: RawPresenceDiff[]; + joinRef: string | null; + caller: { + onJoin: PresenceOnJoinCallback; + onLeave: PresenceOnLeaveCallback; + onSync: () => void; + }; + /** + * Initializes the Presence. + * + * @param channel - The RealtimeChannel + * @param opts - The options, + * for example `{events: {state: 'state', diff: 'diff'}}` + */ + constructor(channel: RealtimeChannel, opts?: PresenceOpts); +} +export {}; +//# sourceMappingURL=RealtimePresence.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.d.ts.map b/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.d.ts.map new file mode 100644 index 0000000..0d33ce0 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimePresence.d.ts","sourceRoot":"","sources":["../../src/RealtimePresence.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EACV,YAAY,EACZ,sBAAsB,EACtB,uBAAuB,EACxB,MAAM,SAAS,CAAA;AAChB,OAAO,KAAK,eAAe,MAAM,mBAAmB,CAAA;AAEpD,aAAK,QAAQ,CAAC,CAAC,SAAS;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,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AAK,eAAe,GAAG;IACrB,KAAK,EAAE,gBAAgB,CAAA;IACvB,MAAM,EAAE,gBAAgB,CAAA;CACzB,CAAA;AAID,MAAM,CAAC,OAAO,OAAO,gBAAgB;IAqBhB,OAAO,EAAE,eAAe;IApB3C,KAAK,EAAE,qBAAqB,CAAK;IACjC,YAAY,EAAE,eAAe,EAAE,CAAK;IACpC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAO;IAC7B,MAAM,EAAE;QACN,MAAM,EAAE,sBAAsB,CAAA;QAC9B,OAAO,EAAE,uBAAuB,CAAA;QAChC,MAAM,EAAE,MAAM,IAAI,CAAA;KACnB,CAIA;IAED;;;;;;OAMG;gBACgB,OAAO,EAAE,eAAe,EAAE,IAAI,CAAC,EAAE,YAAY;CAwRjE"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.js b/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.js new file mode 100644 index 0000000..f9b1f8b --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.js @@ -0,0 +1,228 @@ +"use strict"; +/* + This file draws heavily from https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/assets/js/phoenix/presence.js + License: https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/LICENSE.md +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.REALTIME_PRESENCE_LISTEN_EVENTS = void 0; +var REALTIME_PRESENCE_LISTEN_EVENTS; +(function (REALTIME_PRESENCE_LISTEN_EVENTS) { + REALTIME_PRESENCE_LISTEN_EVENTS["SYNC"] = "sync"; + REALTIME_PRESENCE_LISTEN_EVENTS["JOIN"] = "join"; + REALTIME_PRESENCE_LISTEN_EVENTS["LEAVE"] = "leave"; +})(REALTIME_PRESENCE_LISTEN_EVENTS = exports.REALTIME_PRESENCE_LISTEN_EVENTS || (exports.REALTIME_PRESENCE_LISTEN_EVENTS = {})); +class RealtimePresence { + /** + * Initializes the Presence. + * + * @param channel - The RealtimeChannel + * @param opts - The options, + * for example `{events: {state: 'state', diff: 'diff'}}` + */ + constructor(channel, opts) { + this.channel = channel; + this.state = {}; + this.pendingDiffs = []; + this.joinRef = null; + this.caller = { + onJoin: () => { }, + onLeave: () => { }, + onSync: () => { }, + }; + const events = (opts === null || opts === void 0 ? void 0 : opts.events) || { + state: 'presence_state', + diff: 'presence_diff', + }; + this.channel._on(events.state, {}, (newState) => { + const { onJoin, onLeave, onSync } = this.caller; + this.joinRef = this.channel._joinRef(); + this.state = RealtimePresence.syncState(this.state, newState, onJoin, onLeave); + this.pendingDiffs.forEach((diff) => { + this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + }); + this.pendingDiffs = []; + onSync(); + }); + this.channel._on(events.diff, {}, (diff) => { + const { onJoin, onLeave, onSync } = this.caller; + if (this.inPendingSyncState()) { + this.pendingDiffs.push(diff); + } + else { + this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + onSync(); + } + }); + this.onJoin((key, currentPresences, newPresences) => { + this.channel._trigger('presence', { + event: 'join', + key, + currentPresences, + newPresences, + }); + }); + this.onLeave((key, currentPresences, leftPresences) => { + this.channel._trigger('presence', { + event: 'leave', + key, + currentPresences, + leftPresences, + }); + }); + this.onSync(() => { + this.channel._trigger('presence', { event: 'sync' }); + }); + } + /** + * Used to sync the list of presences on the server with the + * client's state. + * + * An optional `onJoin` and `onLeave` callback can be provided to + * react to changes in the client's local presences across + * disconnects and reconnects with the server. + * + * @internal + */ + static syncState(currentState, newState, onJoin, onLeave) { + const state = this.cloneDeep(currentState); + const transformedState = this.transformState(newState); + const joins = {}; + const leaves = {}; + this.map(state, (key, presences) => { + if (!transformedState[key]) { + leaves[key] = presences; + } + }); + this.map(transformedState, (key, newPresences) => { + const currentPresences = state[key]; + if (currentPresences) { + const newPresenceRefs = newPresences.map((m) => m.presence_ref); + const curPresenceRefs = currentPresences.map((m) => m.presence_ref); + const joinedPresences = newPresences.filter((m) => curPresenceRefs.indexOf(m.presence_ref) < 0); + const leftPresences = currentPresences.filter((m) => newPresenceRefs.indexOf(m.presence_ref) < 0); + if (joinedPresences.length > 0) { + joins[key] = joinedPresences; + } + if (leftPresences.length > 0) { + leaves[key] = leftPresences; + } + } + else { + joins[key] = newPresences; + } + }); + return this.syncDiff(state, { joins, leaves }, onJoin, onLeave); + } + /** + * Used to sync a diff of presence join and leave events from the + * server, as they happen. + * + * Like `syncState`, `syncDiff` accepts optional `onJoin` and + * `onLeave` callbacks to react to a user joining or leaving from a + * device. + * + * @internal + */ + static syncDiff(state, diff, onJoin, onLeave) { + const { joins, leaves } = { + joins: this.transformState(diff.joins), + leaves: this.transformState(diff.leaves), + }; + if (!onJoin) { + onJoin = () => { }; + } + if (!onLeave) { + onLeave = () => { }; + } + this.map(joins, (key, newPresences) => { + var _a; + const currentPresences = (_a = state[key]) !== null && _a !== void 0 ? _a : []; + state[key] = this.cloneDeep(newPresences); + if (currentPresences.length > 0) { + const joinedPresenceRefs = state[key].map((m) => m.presence_ref); + const curPresences = currentPresences.filter((m) => joinedPresenceRefs.indexOf(m.presence_ref) < 0); + state[key].unshift(...curPresences); + } + onJoin(key, currentPresences, newPresences); + }); + this.map(leaves, (key, leftPresences) => { + let currentPresences = state[key]; + if (!currentPresences) + return; + const presenceRefsToRemove = leftPresences.map((m) => m.presence_ref); + currentPresences = currentPresences.filter((m) => presenceRefsToRemove.indexOf(m.presence_ref) < 0); + state[key] = currentPresences; + onLeave(key, currentPresences, leftPresences); + if (currentPresences.length === 0) + delete state[key]; + }); + return state; + } + /** @internal */ + static map(obj, func) { + return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key])); + } + /** + * Remove 'metas' key + * Change 'phx_ref' to 'presence_ref' + * Remove 'phx_ref' and 'phx_ref_prev' + * + * @example + * // returns { + * abc123: [ + * { presence_ref: '2', user_id: 1 }, + * { presence_ref: '3', user_id: 2 } + * ] + * } + * RealtimePresence.transformState({ + * abc123: { + * metas: [ + * { phx_ref: '2', phx_ref_prev: '1' user_id: 1 }, + * { phx_ref: '3', user_id: 2 } + * ] + * } + * }) + * + * @internal + */ + static transformState(state) { + state = this.cloneDeep(state); + return Object.getOwnPropertyNames(state).reduce((newState, key) => { + const presences = state[key]; + if ('metas' in presences) { + newState[key] = presences.metas.map((presence) => { + presence['presence_ref'] = presence['phx_ref']; + delete presence['phx_ref']; + delete presence['phx_ref_prev']; + return presence; + }); + } + else { + newState[key] = presences; + } + return newState; + }, {}); + } + /** @internal */ + static cloneDeep(obj) { + return JSON.parse(JSON.stringify(obj)); + } + /** @internal */ + onJoin(callback) { + this.caller.onJoin = callback; + } + /** @internal */ + onLeave(callback) { + this.caller.onLeave = callback; + } + /** @internal */ + onSync(callback) { + this.caller.onSync = callback; + } + /** @internal */ + inPendingSyncState() { + return !this.joinRef || this.joinRef !== this.channel._joinRef(); + } +} +exports.default = RealtimePresence; +//# sourceMappingURL=RealtimePresence.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.js.map b/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.js.map new file mode 100644 index 0000000..bcf6fe6 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/RealtimePresence.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimePresence.js","sourceRoot":"","sources":["../../src/RealtimePresence.ts"],"names":[],"mappings":";AAAA;;;EAGE;;;AA+BF,IAAY,+BAIX;AAJD,WAAY,+BAA+B;IACzC,gDAAa,CAAA;IACb,gDAAa,CAAA;IACb,kDAAe,CAAA;AACjB,CAAC,EAJW,+BAA+B,GAA/B,uCAA+B,KAA/B,uCAA+B,QAI1C;AAwBD,MAAqB,gBAAgB;IAcnC;;;;;;OAMG;IACH,YAAmB,OAAwB,EAAE,IAAmB;QAA7C,YAAO,GAAP,OAAO,CAAiB;QApB3C,UAAK,GAA0B,EAAE,CAAA;QACjC,iBAAY,GAAsB,EAAE,CAAA;QACpC,YAAO,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/main/index.d.ts b/node_modules/@supabase/realtime-js/dist/main/index.d.ts new file mode 100644 index 0000000..0aaf49d --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/index.d.ts @@ -0,0 +1,5 @@ +import RealtimeClient, { RealtimeClientOptions, RealtimeMessage, RealtimeRemoveChannelResponse } from './RealtimeClient'; +import RealtimeChannel, { RealtimeChannelOptions, RealtimeChannelSendResponse, RealtimePostgresChangesFilter, RealtimePostgresChangesPayload, RealtimePostgresInsertPayload, RealtimePostgresUpdatePayload, RealtimePostgresDeletePayload, REALTIME_LISTEN_TYPES, REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, REALTIME_SUBSCRIBE_STATES } from './RealtimeChannel'; +import RealtimePresence, { RealtimePresenceState, RealtimePresenceJoinPayload, RealtimePresenceLeavePayload, REALTIME_PRESENCE_LISTEN_EVENTS } from './RealtimePresence'; +export { RealtimePresence, RealtimeChannel, RealtimeChannelOptions, RealtimeChannelSendResponse, RealtimeClient, RealtimeClientOptions, RealtimeMessage, RealtimePostgresChangesFilter, RealtimePostgresChangesPayload, RealtimePostgresInsertPayload, RealtimePostgresUpdatePayload, RealtimePostgresDeletePayload, RealtimePresenceJoinPayload, RealtimePresenceLeavePayload, RealtimePresenceState, RealtimeRemoveChannelResponse, REALTIME_LISTEN_TYPES, REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, REALTIME_PRESENCE_LISTEN_EVENTS, REALTIME_SUBSCRIBE_STATES, }; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/index.d.ts.map b/node_modules/@supabase/realtime-js/dist/main/index.d.ts.map new file mode 100644 index 0000000..7b78323 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,EAAE,EACrB,qBAAqB,EACrB,eAAe,EACf,6BAA6B,EAC9B,MAAM,kBAAkB,CAAA;AACzB,OAAO,eAAe,EAAE,EACtB,sBAAsB,EACtB,2BAA2B,EAC3B,6BAA6B,EAC7B,8BAA8B,EAC9B,6BAA6B,EAC7B,6BAA6B,EAC7B,6BAA6B,EAC7B,qBAAqB,EACrB,sCAAsC,EACtC,yBAAyB,EAC1B,MAAM,mBAAmB,CAAA;AAC1B,OAAO,gBAAgB,EAAE,EACvB,qBAAqB,EACrB,2BAA2B,EAC3B,4BAA4B,EAC5B,+BAA+B,EAChC,MAAM,oBAAoB,CAAA;AAE3B,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,sBAAsB,EACtB,2BAA2B,EAC3B,cAAc,EACd,qBAAqB,EACrB,eAAe,EACf,6BAA6B,EAC7B,8BAA8B,EAC9B,6BAA6B,EAC7B,6BAA6B,EAC7B,6BAA6B,EAC7B,2BAA2B,EAC3B,4BAA4B,EAC5B,qBAAqB,EACrB,6BAA6B,EAC7B,qBAAqB,EACrB,sCAAsC,EACtC,+BAA+B,EAC/B,yBAAyB,GAC1B,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/index.js b/node_modules/@supabase/realtime-js/dist/main/index.js new file mode 100644 index 0000000..bdfb7c2 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/index.js @@ -0,0 +1,40 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_PRESENCE_LISTEN_EVENTS = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = exports.REALTIME_LISTEN_TYPES = exports.RealtimeClient = exports.RealtimeChannel = exports.RealtimePresence = void 0; +const RealtimeClient_1 = __importDefault(require("./RealtimeClient")); +exports.RealtimeClient = RealtimeClient_1.default; +const RealtimeChannel_1 = __importStar(require("./RealtimeChannel")); +exports.RealtimeChannel = RealtimeChannel_1.default; +Object.defineProperty(exports, "REALTIME_LISTEN_TYPES", { enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_LISTEN_TYPES; } }); +Object.defineProperty(exports, "REALTIME_POSTGRES_CHANGES_LISTEN_EVENT", { enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; } }); +Object.defineProperty(exports, "REALTIME_SUBSCRIBE_STATES", { enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_SUBSCRIBE_STATES; } }); +const RealtimePresence_1 = __importStar(require("./RealtimePresence")); +exports.RealtimePresence = RealtimePresence_1.default; +Object.defineProperty(exports, "REALTIME_PRESENCE_LISTEN_EVENTS", { enumerable: true, get: function () { return RealtimePresence_1.REALTIME_PRESENCE_LISTEN_EVENTS; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/index.js.map b/node_modules/@supabase/realtime-js/dist/main/index.js.map new file mode 100644 index 0000000..34134a5 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sEAIyB;AAyBvB,yBA7BK,wBAAc,CA6BL;AAxBhB,qEAW0B;AAUxB,0BArBK,yBAAe,CAqBL;AAef,sGA5BA,uCAAqB,OA4BA;AACrB,uHA5BA,wDAAsC,OA4BA;AAEtC,0GA7BA,2CAAyB,OA6BA;AA3B3B,uEAK2B;AAGzB,2BARK,0BAAgB,CAQL;AAkBhB,gHAtBA,kDAA+B,OAsBA"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/constants.d.ts b/node_modules/@supabase/realtime-js/dist/main/lib/constants.d.ts new file mode 100644 index 0000000..8a17e42 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/constants.d.ts @@ -0,0 +1,37 @@ +export declare const DEFAULT_HEADERS: { + 'X-Client-Info': string; +}; +export declare const VSN: string; +export declare const DEFAULT_TIMEOUT = 10000; +export declare const WS_CLOSE_NORMAL = 1000; +export declare enum SOCKET_STATES { + connecting = 0, + open = 1, + closing = 2, + closed = 3 +} +export declare enum CHANNEL_STATES { + closed = "closed", + errored = "errored", + joined = "joined", + joining = "joining", + leaving = "leaving" +} +export declare enum CHANNEL_EVENTS { + close = "phx_close", + error = "phx_error", + join = "phx_join", + reply = "phx_reply", + leave = "phx_leave", + access_token = "access_token" +} +export declare enum TRANSPORTS { + websocket = "websocket" +} +export declare enum CONNECTION_STATE { + Connecting = "connecting", + Open = "open", + Closing = "closing", + Closed = "closed" +} +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/constants.d.ts.map b/node_modules/@supabase/realtime-js/dist/main/lib/constants.d.ts.map new file mode 100644 index 0000000..8f7b275 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe;;CAAgD,CAAA;AAE5E,eAAO,MAAM,GAAG,EAAE,MAAgB,CAAA;AAElC,eAAO,MAAM,eAAe,QAAQ,CAAA;AAEpC,eAAO,MAAM,eAAe,OAAO,CAAA;AAEnC,oBAAY,aAAa;IACvB,UAAU,IAAI;IACd,IAAI,IAAI;IACR,OAAO,IAAI;IACX,MAAM,IAAI;CACX;AAED,oBAAY,cAAc;IACxB,MAAM,WAAW;IACjB,OAAO,YAAY;IACnB,MAAM,WAAW;IACjB,OAAO,YAAY;IACnB,OAAO,YAAY;CACpB;AAED,oBAAY,cAAc;IACxB,KAAK,cAAc;IACnB,KAAK,cAAc;IACnB,IAAI,aAAa;IACjB,KAAK,cAAc;IACnB,KAAK,cAAc;IACnB,YAAY,iBAAiB;CAC9B;AAED,oBAAY,UAAU;IACpB,SAAS,cAAc;CACxB;AAED,oBAAY,gBAAgB;IAC1B,UAAU,eAAe;IACzB,IAAI,SAAS;IACb,OAAO,YAAY;IACnB,MAAM,WAAW;CAClB"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/constants.js b/node_modules/@supabase/realtime-js/dist/main/lib/constants.js new file mode 100644 index 0000000..715affe --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/constants.js @@ -0,0 +1,44 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CONNECTION_STATE = exports.TRANSPORTS = exports.CHANNEL_EVENTS = exports.CHANNEL_STATES = exports.SOCKET_STATES = exports.WS_CLOSE_NORMAL = exports.DEFAULT_TIMEOUT = exports.VSN = exports.DEFAULT_HEADERS = void 0; +const version_1 = require("./version"); +exports.DEFAULT_HEADERS = { 'X-Client-Info': `realtime-js/${version_1.version}` }; +exports.VSN = '1.0.0'; +exports.DEFAULT_TIMEOUT = 10000; +exports.WS_CLOSE_NORMAL = 1000; +var SOCKET_STATES; +(function (SOCKET_STATES) { + SOCKET_STATES[SOCKET_STATES["connecting"] = 0] = "connecting"; + SOCKET_STATES[SOCKET_STATES["open"] = 1] = "open"; + SOCKET_STATES[SOCKET_STATES["closing"] = 2] = "closing"; + SOCKET_STATES[SOCKET_STATES["closed"] = 3] = "closed"; +})(SOCKET_STATES = exports.SOCKET_STATES || (exports.SOCKET_STATES = {})); +var CHANNEL_STATES; +(function (CHANNEL_STATES) { + CHANNEL_STATES["closed"] = "closed"; + CHANNEL_STATES["errored"] = "errored"; + CHANNEL_STATES["joined"] = "joined"; + CHANNEL_STATES["joining"] = "joining"; + CHANNEL_STATES["leaving"] = "leaving"; +})(CHANNEL_STATES = exports.CHANNEL_STATES || (exports.CHANNEL_STATES = {})); +var CHANNEL_EVENTS; +(function (CHANNEL_EVENTS) { + CHANNEL_EVENTS["close"] = "phx_close"; + CHANNEL_EVENTS["error"] = "phx_error"; + CHANNEL_EVENTS["join"] = "phx_join"; + CHANNEL_EVENTS["reply"] = "phx_reply"; + CHANNEL_EVENTS["leave"] = "phx_leave"; + CHANNEL_EVENTS["access_token"] = "access_token"; +})(CHANNEL_EVENTS = exports.CHANNEL_EVENTS || (exports.CHANNEL_EVENTS = {})); +var TRANSPORTS; +(function (TRANSPORTS) { + TRANSPORTS["websocket"] = "websocket"; +})(TRANSPORTS = exports.TRANSPORTS || (exports.TRANSPORTS = {})); +var CONNECTION_STATE; +(function (CONNECTION_STATE) { + CONNECTION_STATE["Connecting"] = "connecting"; + CONNECTION_STATE["Open"] = "open"; + CONNECTION_STATE["Closing"] = "closing"; + CONNECTION_STATE["Closed"] = "closed"; +})(CONNECTION_STATE = exports.CONNECTION_STATE || (exports.CONNECTION_STATE = {})); +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/constants.js.map b/node_modules/@supabase/realtime-js/dist/main/lib/constants.js.map new file mode 100644 index 0000000..14c7c89 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":";;;AAAA,uCAAmC;AAEtB,QAAA,eAAe,GAAG,EAAE,eAAe,EAAE,eAAe,iBAAO,EAAE,EAAE,CAAA;AAE/D,QAAA,GAAG,GAAW,OAAO,CAAA;AAErB,QAAA,eAAe,GAAG,KAAK,CAAA;AAEvB,QAAA,eAAe,GAAG,IAAI,CAAA;AAEnC,IAAY,aAKX;AALD,WAAY,aAAa;IACvB,6DAAc,CAAA;IACd,iDAAQ,CAAA;IACR,uDAAW,CAAA;IACX,qDAAU,CAAA;AACZ,CAAC,EALW,aAAa,GAAb,qBAAa,KAAb,qBAAa,QAKxB;AAED,IAAY,cAMX;AAND,WAAY,cAAc;IACxB,mCAAiB,CAAA;IACjB,qCAAmB,CAAA;IACnB,mCAAiB,CAAA;IACjB,qCAAmB,CAAA;IACnB,qCAAmB,CAAA;AACrB,CAAC,EANW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAMzB;AAED,IAAY,cAOX;AAPD,WAAY,cAAc;IACxB,qCAAmB,CAAA;IACnB,qCAAmB,CAAA;IACnB,mCAAiB,CAAA;IACjB,qCAAmB,CAAA;IACnB,qCAAmB,CAAA;IACnB,+CAA6B,CAAA;AAC/B,CAAC,EAPW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAOzB;AAED,IAAY,UAEX;AAFD,WAAY,UAAU;IACpB,qCAAuB,CAAA;AACzB,CAAC,EAFW,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAErB;AAED,IAAY,gBAKX;AALD,WAAY,gBAAgB;IAC1B,6CAAyB,CAAA;IACzB,iCAAa,CAAA;IACb,uCAAmB,CAAA;IACnB,qCAAiB,CAAA;AACnB,CAAC,EALW,gBAAgB,GAAhB,wBAAgB,KAAhB,wBAAgB,QAK3B"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/push.d.ts b/node_modules/@supabase/realtime-js/dist/main/lib/push.d.ts new file mode 100644 index 0000000..16d954c --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/push.d.ts @@ -0,0 +1,49 @@ +import type RealtimeChannel from '../RealtimeChannel'; +export default class Push { + channel: RealtimeChannel; + event: string; + payload: { + [key: string]: any; + }; + timeout: number; + sent: boolean; + timeoutTimer: number | undefined; + ref: string; + receivedResp: { + status: string; + response: { + [key: string]: any; + }; + } | null; + recHooks: { + status: string; + callback: Function; + }[]; + refEvent: string | null; + rateLimited: boolean; + /** + * Initializes the Push + * + * @param channel The Channel + * @param event The event, for example `"phx_join"` + * @param payload The payload, for example `{user_id: 123}` + * @param timeout The push timeout in milliseconds + */ + constructor(channel: RealtimeChannel, event: string, payload?: { + [key: string]: any; + }, timeout?: number); + resend(timeout: number): void; + send(): void; + updatePayload(payload: { + [key: string]: any; + }): void; + receive(status: string, callback: Function): this; + startTimeout(): void; + trigger(status: string, response: any): void; + destroy(): void; + private _cancelRefEvent; + private _cancelTimeout; + private _matchReceive; + private _hasReceived; +} +//# sourceMappingURL=push.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/push.d.ts.map b/node_modules/@supabase/realtime-js/dist/main/lib/push.d.ts.map new file mode 100644 index 0000000..c4174d5 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/push.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"push.d.ts","sourceRoot":"","sources":["../../../src/lib/push.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,eAAe,MAAM,oBAAoB,CAAA;AAErD,MAAM,CAAC,OAAO,OAAO,IAAI;IAwBd,OAAO,EAAE,eAAe;IACxB,KAAK,EAAE,MAAM;IACb,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE;IAC/B,OAAO,EAAE,MAAM;IA1BxB,IAAI,EAAE,OAAO,CAAQ;IACrB,YAAY,EAAE,MAAM,GAAG,SAAS,CAAY;IAC5C,GAAG,EAAE,MAAM,CAAK;IAChB,YAAY,EAAE;QACZ,MAAM,EAAE,MAAM,CAAA;QACd,QAAQ,EAAE;YAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;SAAE,CAAA;KACjC,GAAG,IAAI,CAAO;IACf,QAAQ,EAAE;QACR,MAAM,EAAE,MAAM,CAAA;QACd,QAAQ,EAAE,QAAQ,CAAA;KACnB,EAAE,CAAK;IACR,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAO;IAC9B,WAAW,EAAE,OAAO,CAAQ;IAE5B;;;;;;;OAOG;gBAEM,OAAO,EAAE,eAAe,EACxB,KAAK,EAAE,MAAM,EACb,OAAO,GAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAO,EACpC,OAAO,GAAE,MAAwB;IAG1C,MAAM,CAAC,OAAO,EAAE,MAAM;IAUtB,IAAI;IAkBJ,aAAa,CAAC,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,GAAG,IAAI;IAIpD,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ;IAS1C,YAAY;IAqBZ,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG;IAKrC,OAAO;IAKP,OAAO,CAAC,eAAe;IAQvB,OAAO,CAAC,cAAc;IAKtB,OAAO,CAAC,aAAa;IAYrB,OAAO,CAAC,YAAY;CAGrB"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/push.js b/node_modules/@supabase/realtime-js/dist/main/lib/push.js new file mode 100644 index 0000000..d781268 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/push.js @@ -0,0 +1,108 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const constants_1 = require("../lib/constants"); +class Push { + /** + * Initializes the Push + * + * @param channel The Channel + * @param event The event, for example `"phx_join"` + * @param payload The payload, for example `{user_id: 123}` + * @param timeout The push timeout in milliseconds + */ + constructor(channel, event, payload = {}, timeout = constants_1.DEFAULT_TIMEOUT) { + this.channel = channel; + this.event = event; + this.payload = payload; + this.timeout = timeout; + this.sent = false; + this.timeoutTimer = undefined; + this.ref = ''; + this.receivedResp = null; + this.recHooks = []; + this.refEvent = null; + this.rateLimited = false; + } + resend(timeout) { + this.timeout = timeout; + this._cancelRefEvent(); + this.ref = ''; + this.refEvent = null; + this.receivedResp = null; + this.sent = false; + this.send(); + } + send() { + if (this._hasReceived('timeout')) { + return; + } + this.startTimeout(); + this.sent = true; + const status = this.channel.socket.push({ + topic: this.channel.topic, + event: this.event, + payload: this.payload, + ref: this.ref, + join_ref: this.channel._joinRef(), + }); + if (status === 'rate limited') { + this.rateLimited = true; + } + } + updatePayload(payload) { + this.payload = Object.assign(Object.assign({}, this.payload), payload); + } + receive(status, callback) { + var _a; + if (this._hasReceived(status)) { + callback((_a = this.receivedResp) === null || _a === void 0 ? void 0 : _a.response); + } + this.recHooks.push({ status, callback }); + return this; + } + startTimeout() { + if (this.timeoutTimer) { + return; + } + this.ref = this.channel.socket._makeRef(); + this.refEvent = this.channel._replyEventName(this.ref); + const callback = (payload) => { + this._cancelRefEvent(); + this._cancelTimeout(); + this.receivedResp = payload; + this._matchReceive(payload); + }; + this.channel._on(this.refEvent, {}, callback); + this.timeoutTimer = setTimeout(() => { + this.trigger('timeout', {}); + }, this.timeout); + } + trigger(status, response) { + if (this.refEvent) + this.channel._trigger(this.refEvent, { status, response }); + } + destroy() { + this._cancelRefEvent(); + this._cancelTimeout(); + } + _cancelRefEvent() { + if (!this.refEvent) { + return; + } + this.channel._off(this.refEvent, {}); + } + _cancelTimeout() { + clearTimeout(this.timeoutTimer); + this.timeoutTimer = undefined; + } + _matchReceive({ status, response, }) { + this.recHooks + .filter((h) => h.status === status) + .forEach((h) => h.callback(response)); + } + _hasReceived(status) { + return this.receivedResp && this.receivedResp.status === status; + } +} +exports.default = Push; +//# sourceMappingURL=push.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/push.js.map b/node_modules/@supabase/realtime-js/dist/main/lib/push.js.map new file mode 100644 index 0000000..5dc2a51 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/push.js.map @@ -0,0 +1 @@ +{"version":3,"file":"push.js","sourceRoot":"","sources":["../../../src/lib/push.ts"],"names":[],"mappings":";;AAAA,gDAAkD;AAGlD,MAAqB,IAAI;IAevB;;;;;;;OAOG;IACH,YACS,OAAwB,EACxB,KAAa,EACb,UAAkC,EAAE,EACpC,UAAkB,2BAAe;QAHjC,YAAO,GAAP,OAAO,CAAiB;QACxB,UAAK,GAAL,KAAK,CAAQ;QACb,YAAO,GAAP,OAAO,CAA6B;QACpC,YAAO,GAAP,OAAO,CAA0B;QA1B1C,SAAI,GAAY,KAAK,CAAA;QACrB,iBAAY,GAAuB,SAAS,CAAA;QAC5C,QAAG,GAAW,EAAE,CAAA;QAChB,iBAAY,GAGD,IAAI,CAAA;QACf,aAAQ,GAGF,EAAE,CAAA;QACR,aAAQ,GAAkB,IAAI,CAAA;QAC9B,gBAAW,GAAY,KAAK,CAAA;IAezB,CAAC;IAEJ,MAAM,CAAC,OAAe;QACpB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,eAAe,EAAE,CAAA;QACtB,IAAI,CAAC,GAAG,GAAG,EAAE,CAAA;QACb,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAA;QACpB,IAAI,CAAC,YAAY,GAAG,IAAI,CAAA;QACxB,IAAI,CAAC,IAAI,GAAG,KAAK,CAAA;QACjB,IAAI,CAAC,IAAI,EAAE,CAAA;IACb,CAAC;IAED,IAAI;QACF,IAAI,IAAI,CAAC,YAAY,CAAC,SAAS,CAAC,EAAE;YAChC,OAAM;SACP;QACD,IAAI,CAAC,YAAY,EAAE,CAAA;QACnB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,MAAM,MAAM,GAAG,IAAI,CAAC,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CAAC;CACF;AAlID,uBAkIC"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/serializer.d.ts b/node_modules/@supabase/realtime-js/dist/main/lib/serializer.d.ts new file mode 100644 index 0000000..2e86807 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/serializer.d.ts @@ -0,0 +1,7 @@ +export default class Serializer { + HEADER_LENGTH: number; + decode(rawPayload: ArrayBuffer | string, callback: Function): any; + private _binaryDecode; + private _decodeBroadcast; +} +//# sourceMappingURL=serializer.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/serializer.d.ts.map b/node_modules/@supabase/realtime-js/dist/main/lib/serializer.d.ts.map new file mode 100644 index 0000000..3a7f65f --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/serializer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"serializer.d.ts","sourceRoot":"","sources":["../../../src/lib/serializer.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,OAAO,OAAO,UAAU;IAC7B,aAAa,SAAI;IAEjB,MAAM,CAAC,UAAU,EAAE,WAAW,GAAG,MAAM,EAAE,QAAQ,EAAE,QAAQ;IAY3D,OAAO,CAAC,aAAa;IAOrB,OAAO,CAAC,gBAAgB;CAuBzB"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/serializer.js b/node_modules/@supabase/realtime-js/dist/main/lib/serializer.js new file mode 100644 index 0000000..fc1f495 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/serializer.js @@ -0,0 +1,36 @@ +"use strict"; +// This file draws heavily from https://github.com/phoenixframework/phoenix/commit/cf098e9cf7a44ee6479d31d911a97d3c7430c6fe +// License: https://github.com/phoenixframework/phoenix/blob/master/LICENSE.md +Object.defineProperty(exports, "__esModule", { value: true }); +class Serializer { + constructor() { + this.HEADER_LENGTH = 1; + } + decode(rawPayload, callback) { + if (rawPayload.constructor === ArrayBuffer) { + return callback(this._binaryDecode(rawPayload)); + } + if (typeof rawPayload === 'string') { + return callback(JSON.parse(rawPayload)); + } + return callback({}); + } + _binaryDecode(buffer) { + const view = new DataView(buffer); + const decoder = new TextDecoder(); + return this._decodeBroadcast(buffer, view, decoder); + } + _decodeBroadcast(buffer, view, decoder) { + const topicSize = view.getUint8(1); + const eventSize = view.getUint8(2); + let offset = this.HEADER_LENGTH + 2; + const topic = decoder.decode(buffer.slice(offset, offset + topicSize)); + offset = offset + topicSize; + const event = decoder.decode(buffer.slice(offset, offset + eventSize)); + offset = offset + eventSize; + const data = JSON.parse(decoder.decode(buffer.slice(offset, buffer.byteLength))); + return { ref: null, topic: topic, event: event, payload: data }; + } +} +exports.default = Serializer; +//# sourceMappingURL=serializer.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/serializer.js.map b/node_modules/@supabase/realtime-js/dist/main/lib/serializer.js.map new file mode 100644 index 0000000..4c909b7 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/serializer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"serializer.js","sourceRoot":"","sources":["../../../src/lib/serializer.ts"],"names":[],"mappings":";AAAA,2HAA2H;AAC3H,8EAA8E;;AAE9E,MAAqB,UAAU;IAA/B;QACE,kBAAa,GAAG,CAAC,CAAA;IA4CnB,CAAC;IA1CC,MAAM,CAAC,UAAgC,EAAE,QAAkB;QACzD,IAAI,UAAU,CAAC,WAAW,KAAK,WAAW,EAAE;YAC1C,OAAO,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC,CAAA;SAChD;QAED,IAAI,OAAO,UAAU,KAAK,QAAQ,EAAE;YAClC,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAA;SACxC;QAED,OAAO,QAAQ,CAAC,EAAE,CAAC,CAAA;IACrB,CAAC;IAEO,aAAa,CAAC,MAAmB;QACvC,MAAM,IAAI,GAAG,IAAI,QAAQ,CAAC,MAAM,CAAC,CAAA;QACjC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAA;QAEjC,OAAO,IAAI,CAAC,gBAAgB,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,CAAA;IACrD,CAAC;IAEO,gBAAgB,CACtB,MAAmB,EACnB,IAAc,EACd,OAAoB;QAOpB,MAAM,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAA;QAClC,MAAM,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAA;QAClC,IAAI,MAAM,GAAG,IAAI,CAAC,aAAa,GAAG,CAAC,CAAA;QACnC,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAA;QACtE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAA;QAC3B,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAA;QACtE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAA;QAC3B,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CACrB,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC,CACxD,CAAA;QAED,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,CAAA;IACjE,CAAC;CACF;AA7CD,6BA6CC"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/timer.d.ts b/node_modules/@supabase/realtime-js/dist/main/lib/timer.d.ts new file mode 100644 index 0000000..d5df4a6 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/timer.d.ts @@ -0,0 +1,22 @@ +/** + * Creates a timer that accepts a `timerCalc` function to perform calculated timeout retries, such as exponential backoff. + * + * @example + * let reconnectTimer = new Timer(() => this.connect(), function(tries){ + * return [1000, 5000, 10000][tries - 1] || 10000 + * }) + * reconnectTimer.scheduleTimeout() // fires after 1000 + * reconnectTimer.scheduleTimeout() // fires after 5000 + * reconnectTimer.reset() + * reconnectTimer.scheduleTimeout() // fires after 1000 + */ +export default class Timer { + callback: Function; + timerCalc: Function; + timer: number | undefined; + tries: number; + constructor(callback: Function, timerCalc: Function); + reset(): void; + scheduleTimeout(): void; +} +//# sourceMappingURL=timer.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/timer.d.ts.map b/node_modules/@supabase/realtime-js/dist/main/lib/timer.d.ts.map new file mode 100644 index 0000000..35ca72e --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/timer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"timer.d.ts","sourceRoot":"","sources":["../../../src/lib/timer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,OAAO,OAAO,KAAK;IAIL,QAAQ,EAAE,QAAQ;IAAS,SAAS,EAAE,QAAQ;IAHjE,KAAK,EAAE,MAAM,GAAG,SAAS,CAAY;IACrC,KAAK,EAAE,MAAM,CAAI;gBAEE,QAAQ,EAAE,QAAQ,EAAS,SAAS,EAAE,QAAQ;IAKjE,KAAK;IAML,eAAe;CAQhB"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/timer.js b/node_modules/@supabase/realtime-js/dist/main/lib/timer.js new file mode 100644 index 0000000..9f7b174 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/timer.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Creates a timer that accepts a `timerCalc` function to perform calculated timeout retries, such as exponential backoff. + * + * @example + * let reconnectTimer = new Timer(() => this.connect(), function(tries){ + * return [1000, 5000, 10000][tries - 1] || 10000 + * }) + * reconnectTimer.scheduleTimeout() // fires after 1000 + * reconnectTimer.scheduleTimeout() // fires after 5000 + * reconnectTimer.reset() + * reconnectTimer.scheduleTimeout() // fires after 1000 + */ +class Timer { + constructor(callback, timerCalc) { + this.callback = callback; + this.timerCalc = timerCalc; + this.timer = undefined; + this.tries = 0; + this.callback = callback; + this.timerCalc = timerCalc; + } + reset() { + this.tries = 0; + clearTimeout(this.timer); + } + // Cancels any previous scheduleTimeout and schedules callback + scheduleTimeout() { + clearTimeout(this.timer); + this.timer = setTimeout(() => { + this.tries = this.tries + 1; + this.callback(); + }, this.timerCalc(this.tries + 1)); + } +} +exports.default = Timer; +//# sourceMappingURL=timer.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/timer.js.map b/node_modules/@supabase/realtime-js/dist/main/lib/timer.js.map new file mode 100644 index 0000000..e01ffb1 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/timer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"timer.js","sourceRoot":"","sources":["../../../src/lib/timer.ts"],"names":[],"mappings":";;AAAA;;;;;;;;;;;GAWG;AACH,MAAqB,KAAK;IAIxB,YAAmB,QAAkB,EAAS,SAAmB;QAA9C,aAAQ,GAAR,QAAQ,CAAU;QAAS,cAAS,GAAT,SAAS,CAAU;QAHjE,UAAK,GAAuB,SAAS,CAAA;QACrC,UAAK,GAAW,CAAC,CAAA;QAGf,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAA;IAC5B,CAAC;IAED,KAAK;QACH,IAAI,CAAC,KAAK,GAAG,CAAC,CAAA;QACd,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;IAC1B,CAAC;IAED,8DAA8D;IAC9D,eAAe;QACb,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QAExB,IAAI,CAAC,KAAK,GAAQ,UAAU,CAAC,GAAG,EAAE;YAChC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,GAAG,CAAC,CAAA;YAC3B,IAAI,CAAC,QAAQ,EAAE,CAAA;QACjB,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,CAAA;IACpC,CAAC;CACF;AAvBD,wBAuBC"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/transformers.d.ts b/node_modules/@supabase/realtime-js/dist/main/lib/transformers.d.ts new file mode 100644 index 0000000..992cdfa --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/transformers.d.ts @@ -0,0 +1,108 @@ +/** + * Helpers to convert the change Payload into native JS types. + */ +export declare enum PostgresTypes { + abstime = "abstime", + bool = "bool", + date = "date", + daterange = "daterange", + float4 = "float4", + float8 = "float8", + int2 = "int2", + int4 = "int4", + int4range = "int4range", + int8 = "int8", + int8range = "int8range", + json = "json", + jsonb = "jsonb", + money = "money", + numeric = "numeric", + oid = "oid", + reltime = "reltime", + text = "text", + time = "time", + timestamp = "timestamp", + timestamptz = "timestamptz", + timetz = "timetz", + tsrange = "tsrange", + tstzrange = "tstzrange" +} +declare type Columns = { + name: string; + type: string; + flags?: string[]; + type_modifier?: number; +}[]; +declare type BaseValue = null | string | number | boolean; +declare type RecordValue = BaseValue | BaseValue[]; +declare type Record = { + [key: string]: RecordValue; +}; +/** + * Takes an array of columns and an object of string values then converts each string value + * to its mapped type. + * + * @param {{name: String, type: String}[]} columns + * @param {Object} record + * @param {Object} options The map of various options that can be applied to the mapper + * @param {Array} options.skipTypes The array of types that should not be converted + * + * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {}) + * //=>{ first_name: 'Paul', age: 33 } + */ +export declare const convertChangeData: (columns: Columns, record: Record, options?: { + skipTypes?: string[]; +}) => Record; +/** + * Converts the value of an individual column. + * + * @param {String} columnName The column that you want to convert + * @param {{name: String, type: String}[]} columns All of the columns + * @param {Object} record The map of string values + * @param {Array} skipTypes An array of types that should not be converted + * @return {object} Useless information + * + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, []) + * //=> 33 + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4']) + * //=> "33" + */ +export declare const convertColumn: (columnName: string, columns: Columns, record: Record, skipTypes: string[]) => RecordValue; +/** + * If the value of the cell is `null`, returns null. + * Otherwise converts the string value to the correct type. + * @param {String} type A postgres column type + * @param {String} value The cell value + * + * @example convertCell('bool', 't') + * //=> true + * @example convertCell('int8', '10') + * //=> 10 + * @example convertCell('_int4', '{1,2,3,4}') + * //=> [1,2,3,4] + */ +export declare const convertCell: (type: string, value: RecordValue) => RecordValue; +export declare const toBoolean: (value: RecordValue) => RecordValue; +export declare const toNumber: (value: RecordValue) => RecordValue; +export declare const toJson: (value: RecordValue) => RecordValue; +/** + * Converts a Postgres Array into a native JS array + * + * @example toArray('{}', 'int4') + * //=> [] + * @example toArray('{"[2021-01-01,2021-12-31)","(2021-01-01,2021-12-32]"}', 'daterange') + * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]'] + * @example toArray([1,2,3,4], 'int4') + * //=> [1,2,3,4] + */ +export declare const toArray: (value: RecordValue, type: string) => RecordValue; +/** + * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T' + * See https://github.com/supabase/supabase/issues/18 + * + * @example toTimestampString('2019-09-10 00:00:00') + * //=> '2019-09-10T00:00:00' + */ +export declare const toTimestampString: (value: RecordValue) => RecordValue; +export {}; +//# sourceMappingURL=transformers.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/transformers.d.ts.map b/node_modules/@supabase/realtime-js/dist/main/lib/transformers.d.ts.map new file mode 100644 index 0000000..6af783a --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/transformers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transformers.d.ts","sourceRoot":"","sources":["../../../src/lib/transformers.ts"],"names":[],"mappings":"AAAA;;GAEG;AAKH,oBAAY,aAAa;IACvB,OAAO,YAAY;IACnB,IAAI,SAAS;IACb,IAAI,SAAS;IACb,SAAS,cAAc;IACvB,MAAM,WAAW;IACjB,MAAM,WAAW;IACjB,IAAI,SAAS;IACb,IAAI,SAAS;IACb,SAAS,cAAc;IACvB,IAAI,SAAS;IACb,SAAS,cAAc;IACvB,IAAI,SAAS;IACb,KAAK,UAAU;IACf,KAAK,UAAU;IACf,OAAO,YAAY;IACnB,GAAG,QAAQ;IACX,OAAO,YAAY;IACnB,IAAI,SAAS;IACb,IAAI,SAAS;IACb,SAAS,cAAc;IACvB,WAAW,gBAAgB;IAC3B,MAAM,WAAW;IACjB,OAAO,YAAY;IACnB,SAAS,cAAc;CACxB;AAED,aAAK,OAAO,GAAG;IACb,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,CAAC,EAAE,MAAM,EAAE,CAAA;IAChB,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB,EAAE,CAAA;AAEH,aAAK,SAAS,GAAG,IAAI,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAA;AACjD,aAAK,WAAW,GAAG,SAAS,GAAG,SAAS,EAAE,CAAA;AAE1C,aAAK,MAAM,GAAG;IACZ,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW,CAAA;CAC3B,CAAA;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,iBAAiB,6BAEpB,MAAM,YACL;IAAE,SAAS,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,KAChC,MAOF,CAAA;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,aAAa,eACZ,MAAM,4BAEV,MAAM,aACH,MAAM,EAAE,KAClB,WAUF,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,WAAW,SAAU,MAAM,SAAS,WAAW,KAAG,WA0C9D,CAAA;AAKD,eAAO,MAAM,SAAS,UAAW,WAAW,KAAG,WAS9C,CAAA;AACD,eAAO,MAAM,QAAQ,UAAW,WAAW,KAAG,WAQ7C,CAAA;AACD,eAAO,MAAM,MAAM,UAAW,WAAW,KAAG,WAU3C,CAAA;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,OAAO,UAAW,WAAW,QAAQ,MAAM,KAAG,WA0B1D,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,iBAAiB,UAAW,WAAW,KAAG,WAMtD,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/transformers.js b/node_modules/@supabase/realtime-js/dist/main/lib/transformers.js new file mode 100644 index 0000000..10ed0b4 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/transformers.js @@ -0,0 +1,222 @@ +"use strict"; +/** + * Helpers to convert the change Payload into native JS types. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toTimestampString = exports.toArray = exports.toJson = exports.toNumber = exports.toBoolean = exports.convertCell = exports.convertColumn = exports.convertChangeData = exports.PostgresTypes = void 0; +// Adapted from epgsql (src/epgsql_binary.erl), this module licensed under +// 3-clause BSD found here: https://raw.githubusercontent.com/epgsql/epgsql/devel/LICENSE +var PostgresTypes; +(function (PostgresTypes) { + PostgresTypes["abstime"] = "abstime"; + PostgresTypes["bool"] = "bool"; + PostgresTypes["date"] = "date"; + PostgresTypes["daterange"] = "daterange"; + PostgresTypes["float4"] = "float4"; + PostgresTypes["float8"] = "float8"; + PostgresTypes["int2"] = "int2"; + PostgresTypes["int4"] = "int4"; + PostgresTypes["int4range"] = "int4range"; + PostgresTypes["int8"] = "int8"; + PostgresTypes["int8range"] = "int8range"; + PostgresTypes["json"] = "json"; + PostgresTypes["jsonb"] = "jsonb"; + PostgresTypes["money"] = "money"; + PostgresTypes["numeric"] = "numeric"; + PostgresTypes["oid"] = "oid"; + PostgresTypes["reltime"] = "reltime"; + PostgresTypes["text"] = "text"; + PostgresTypes["time"] = "time"; + PostgresTypes["timestamp"] = "timestamp"; + PostgresTypes["timestamptz"] = "timestamptz"; + PostgresTypes["timetz"] = "timetz"; + PostgresTypes["tsrange"] = "tsrange"; + PostgresTypes["tstzrange"] = "tstzrange"; +})(PostgresTypes = exports.PostgresTypes || (exports.PostgresTypes = {})); +/** + * Takes an array of columns and an object of string values then converts each string value + * to its mapped type. + * + * @param {{name: String, type: String}[]} columns + * @param {Object} record + * @param {Object} options The map of various options that can be applied to the mapper + * @param {Array} options.skipTypes The array of types that should not be converted + * + * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {}) + * //=>{ first_name: 'Paul', age: 33 } + */ +const convertChangeData = (columns, record, options = {}) => { + var _a; + const skipTypes = (_a = options.skipTypes) !== null && _a !== void 0 ? _a : []; + return Object.keys(record).reduce((acc, rec_key) => { + acc[rec_key] = (0, exports.convertColumn)(rec_key, columns, record, skipTypes); + return acc; + }, {}); +}; +exports.convertChangeData = convertChangeData; +/** + * Converts the value of an individual column. + * + * @param {String} columnName The column that you want to convert + * @param {{name: String, type: String}[]} columns All of the columns + * @param {Object} record The map of string values + * @param {Array} skipTypes An array of types that should not be converted + * @return {object} Useless information + * + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, []) + * //=> 33 + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4']) + * //=> "33" + */ +const convertColumn = (columnName, columns, record, skipTypes) => { + const column = columns.find((x) => x.name === columnName); + const colType = column === null || column === void 0 ? void 0 : column.type; + const value = record[columnName]; + if (colType && !skipTypes.includes(colType)) { + return (0, exports.convertCell)(colType, value); + } + return noop(value); +}; +exports.convertColumn = convertColumn; +/** + * If the value of the cell is `null`, returns null. + * Otherwise converts the string value to the correct type. + * @param {String} type A postgres column type + * @param {String} value The cell value + * + * @example convertCell('bool', 't') + * //=> true + * @example convertCell('int8', '10') + * //=> 10 + * @example convertCell('_int4', '{1,2,3,4}') + * //=> [1,2,3,4] + */ +const convertCell = (type, value) => { + // if data type is an array + if (type.charAt(0) === '_') { + const dataType = type.slice(1, type.length); + return (0, exports.toArray)(value, dataType); + } + // If not null, convert to correct type. + switch (type) { + case PostgresTypes.bool: + return (0, exports.toBoolean)(value); + case PostgresTypes.float4: + case PostgresTypes.float8: + case PostgresTypes.int2: + case PostgresTypes.int4: + case PostgresTypes.int8: + case PostgresTypes.numeric: + case PostgresTypes.oid: + return (0, exports.toNumber)(value); + case PostgresTypes.json: + case PostgresTypes.jsonb: + return (0, exports.toJson)(value); + case PostgresTypes.timestamp: + return (0, exports.toTimestampString)(value); // Format to be consistent with PostgREST + case PostgresTypes.abstime: // To allow users to cast it based on Timezone + case PostgresTypes.date: // To allow users to cast it based on Timezone + case PostgresTypes.daterange: + case PostgresTypes.int4range: + case PostgresTypes.int8range: + case PostgresTypes.money: + case PostgresTypes.reltime: // To allow users to cast it based on Timezone + case PostgresTypes.text: + case PostgresTypes.time: // To allow users to cast it based on Timezone + case PostgresTypes.timestamptz: // To allow users to cast it based on Timezone + case PostgresTypes.timetz: // To allow users to cast it based on Timezone + case PostgresTypes.tsrange: + case PostgresTypes.tstzrange: + return noop(value); + default: + // Return the value for remaining types + return noop(value); + } +}; +exports.convertCell = convertCell; +const noop = (value) => { + return value; +}; +const toBoolean = (value) => { + switch (value) { + case 't': + return true; + case 'f': + return false; + default: + return value; + } +}; +exports.toBoolean = toBoolean; +const toNumber = (value) => { + if (typeof value === 'string') { + const parsedValue = parseFloat(value); + if (!Number.isNaN(parsedValue)) { + return parsedValue; + } + } + return value; +}; +exports.toNumber = toNumber; +const toJson = (value) => { + if (typeof value === 'string') { + try { + return JSON.parse(value); + } + catch (error) { + console.log(`JSON parse error: ${error}`); + return value; + } + } + return value; +}; +exports.toJson = toJson; +/** + * Converts a Postgres Array into a native JS array + * + * @example toArray('{}', 'int4') + * //=> [] + * @example toArray('{"[2021-01-01,2021-12-31)","(2021-01-01,2021-12-32]"}', 'daterange') + * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]'] + * @example toArray([1,2,3,4], 'int4') + * //=> [1,2,3,4] + */ +const toArray = (value, type) => { + if (typeof value !== 'string') { + return value; + } + const lastIdx = value.length - 1; + const closeBrace = value[lastIdx]; + const openBrace = value[0]; + // Confirm value is a Postgres array by checking curly brackets + if (openBrace === '{' && closeBrace === '}') { + let arr; + const valTrim = value.slice(1, lastIdx); + // TODO: find a better solution to separate Postgres array data + try { + arr = JSON.parse('[' + valTrim + ']'); + } + catch (_) { + // WARNING: splitting on comma does not cover all edge cases + arr = valTrim ? valTrim.split(',') : []; + } + return arr.map((val) => (0, exports.convertCell)(type, val)); + } + return value; +}; +exports.toArray = toArray; +/** + * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T' + * See https://github.com/supabase/supabase/issues/18 + * + * @example toTimestampString('2019-09-10 00:00:00') + * //=> '2019-09-10T00:00:00' + */ +const toTimestampString = (value) => { + if (typeof value === 'string') { + return value.replace(' ', 'T'); + } + return value; +}; +exports.toTimestampString = toTimestampString; +//# sourceMappingURL=transformers.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/transformers.js.map b/node_modules/@supabase/realtime-js/dist/main/lib/transformers.js.map new file mode 100644 index 0000000..6b70358 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/transformers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transformers.js","sourceRoot":"","sources":["../../../src/lib/transformers.ts"],"names":[],"mappings":";AAAA;;GAEG;;;AAEH,0EAA0E;AAC1E,yFAAyF;AAEzF,IAAY,aAyBX;AAzBD,WAAY,aAAa;IACvB,oCAAmB,CAAA;IACnB,8BAAa,CAAA;IACb,8BAAa,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G,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;SACxC;QAED,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,GAAc,EAAE,EAAE,CAAC,IAAA,mBAAW,EAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;KAC3D;IAED,OAAO,KAAK,CAAA;AACd,CAAC,CAAA;AA1BY,QAAA,OAAO,WA0BnB;AAED;;;;;;GAMG;AACI,MAAM,iBAAiB,GAAG,CAAC,KAAkB,EAAe,EAAE;IACnE,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC7B,OAAO,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;KAC/B;IAED,OAAO,KAAK,CAAA;AACd,CAAC,CAAA;AANY,QAAA,iBAAiB,qBAM7B"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/version.d.ts b/node_modules/@supabase/realtime-js/dist/main/lib/version.d.ts new file mode 100644 index 0000000..b67fe60 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.7.3"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/version.d.ts.map b/node_modules/@supabase/realtime-js/dist/main/lib/version.d.ts.map new file mode 100644 index 0000000..7c1c990 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,oBAAoB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/version.js b/node_modules/@supabase/realtime-js/dist/main/lib/version.js new file mode 100644 index 0000000..600fffa --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/version.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.version = void 0; +exports.version = '2.7.3'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/main/lib/version.js.map b/node_modules/@supabase/realtime-js/dist/main/lib/version.js.map new file mode 100644 index 0000000..a69abef --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/main/lib/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":";;;AAAa,QAAA,OAAO,GAAG,iBAAiB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.d.ts b/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.d.ts new file mode 100644 index 0000000..a3489f6 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.d.ts @@ -0,0 +1,199 @@ +import { CHANNEL_STATES } from './lib/constants'; +import Push from './lib/push'; +import type RealtimeClient from './RealtimeClient'; +import Timer from './lib/timer'; +import RealtimePresence, { REALTIME_PRESENCE_LISTEN_EVENTS } from './RealtimePresence'; +import type { RealtimePresenceJoinPayload, RealtimePresenceLeavePayload, RealtimePresenceState } from './RealtimePresence'; +export declare type RealtimeChannelOptions = { + config: { + /** + * self option enables client to receive message it broadcast + * ack option instructs server to acknowledge that broadcast message was received + */ + broadcast?: { + self?: boolean; + ack?: boolean; + }; + /** + * key option is used to track presence payload across clients + */ + presence?: { + key?: string; + }; + }; +}; +declare type RealtimePostgresChangesPayloadBase = { + schema: string; + table: string; + commit_timestamp: string; + errors: string[]; +}; +export declare type RealtimePostgresInsertPayload = RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`; + new: T; + old: {}; +}; +export declare type RealtimePostgresUpdatePayload = RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`; + new: T; + old: Partial; +}; +export declare type RealtimePostgresDeletePayload = RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`; + new: {}; + old: Partial; +}; +export declare type RealtimePostgresChangesPayload = RealtimePostgresInsertPayload | RealtimePostgresUpdatePayload | RealtimePostgresDeletePayload; +export declare type RealtimePostgresChangesFilter = { + /** + * The type of database change to listen to. + */ + event: T; + /** + * The database schema to listen to. + */ + schema: string; + /** + * The database table to listen to. + */ + table?: string; + /** + * Receive database changes when filter is matched. + */ + filter?: string; +}; +export declare type RealtimeChannelSendResponse = 'ok' | 'timed out' | 'rate limited'; +export declare enum REALTIME_POSTGRES_CHANGES_LISTEN_EVENT { + ALL = "*", + INSERT = "INSERT", + UPDATE = "UPDATE", + DELETE = "DELETE" +} +export declare enum REALTIME_LISTEN_TYPES { + BROADCAST = "broadcast", + PRESENCE = "presence", + /** + * listen to Postgres changes. + */ + POSTGRES_CHANGES = "postgres_changes" +} +export declare enum REALTIME_SUBSCRIBE_STATES { + SUBSCRIBED = "SUBSCRIBED", + TIMED_OUT = "TIMED_OUT", + CLOSED = "CLOSED", + CHANNEL_ERROR = "CHANNEL_ERROR" +} +/** A channel is the basic building block of Realtime + * and narrows the scope of data flow to subscribed clients. + * You can think of a channel as a chatroom where participants are able to see who's online + * and send and receive messages. + **/ +export default class RealtimeChannel { + /** Topic name can be any string. */ + topic: string; + params: RealtimeChannelOptions; + socket: RealtimeClient; + bindings: { + [key: string]: { + type: string; + filter: { + [key: string]: any; + }; + callback: Function; + id?: string; + }[]; + }; + timeout: number; + state: CHANNEL_STATES; + joinedOnce: boolean; + joinPush: Push; + rejoinTimer: Timer; + pushBuffer: Push[]; + presence: RealtimePresence; + constructor( + /** Topic name can be any string. */ + topic: string, params: RealtimeChannelOptions, socket: RealtimeClient); + /** Subscribe registers your client with the server */ + subscribe(callback?: (status: `${REALTIME_SUBSCRIBE_STATES}`, err?: Error) => void, timeout?: number): RealtimeChannel; + presenceState(): RealtimePresenceState; + track(payload: { + [key: string]: any; + }, opts?: { + [key: string]: any; + }): Promise; + untrack(opts?: { + [key: string]: any; + }): Promise; + /** + * Creates an event handler that listens to changes. + */ + on(type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, filter: { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.SYNC}`; + }, callback: () => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, filter: { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.JOIN}`; + }, callback: (payload: RealtimePresenceJoinPayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, filter: { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.LEAVE}`; + }, callback: (payload: RealtimePresenceLeavePayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL}`>, callback: (payload: RealtimePostgresChangesPayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`>, callback: (payload: RealtimePostgresInsertPayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`>, callback: (payload: RealtimePostgresUpdatePayload) => void): RealtimeChannel; + on(type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`>, callback: (payload: RealtimePostgresDeletePayload) => void): RealtimeChannel; + /** + * The following is placed here to display on supabase.com/docs/reference/javascript/subscribe. + * @param type One of "broadcast", "presence", or "postgres_changes". + * @param filter Custom object specific to the Realtime feature detailing which payloads to receive. + * @param callback Function to be invoked when event handler is triggered. + */ + on(type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, filter: { + event: string; + }, callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`; + event: string; + [key: string]: any; + }) => void): RealtimeChannel; + send(payload: { + type: string; + [key: string]: any; + }, opts?: { + [key: string]: any; + }): Promise; + updateJoinPayload(payload: { + [key: string]: any; + }): void; + /** + * Leaves the channel. + * + * Unsubscribes from server events, and instructs channel to terminate on server. + * Triggers onClose() hooks. + * + * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: + * channel.unsubscribe().receive("ok", () => alert("left!") ) + */ + unsubscribe(timeout?: number): Promise<'ok' | 'timed out' | 'error'>; +} +export {}; +//# sourceMappingURL=RealtimeChannel.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.d.ts.map b/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.d.ts.map new file mode 100644 index 0000000..24156c0 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimeChannel.d.ts","sourceRoot":"","sources":["../../src/RealtimeChannel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAChE,OAAO,IAAI,MAAM,YAAY,CAAA;AAC7B,OAAO,KAAK,cAAc,MAAM,kBAAkB,CAAA;AAClD,OAAO,KAAK,MAAM,aAAa,CAAA;AAC/B,OAAO,gBAAgB,EAAE,EACvB,+BAA+B,EAChC,MAAM,oBAAoB,CAAA;AAC3B,OAAO,KAAK,EACV,2BAA2B,EAC3B,4BAA4B,EAC5B,qBAAqB,EACtB,MAAM,oBAAoB,CAAA;AAG3B,oBAAY,sBAAsB,GAAG;IACnC,MAAM,EAAE;QACN;;;WAGG;QACH,SAAS,CAAC,EAAE;YAAE,IAAI,CAAC,EAAE,OAAO,CAAC;YAAC,GAAG,CAAC,EAAE,OAAO,C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AAM,GAAG,GAAG,CAAA;KAAE,EACjC,IAAI,EAAE,GAAG,qBAAqB,CAAC,gBAAgB,EAAE,EACjD,MAAM,EAAE,6BAA6B,CAAC,GAAG,sCAAsC,CAAC,MAAM,EAAE,CAAC,EACzF,QAAQ,EAAE,CAAC,OAAO,EAAE,6BAA6B,CAAC,CAAC,CAAC,KAAK,IAAI,GAC5D,eAAe;IAClB;;;;;OAKG;IACH,EAAE,CACA,IAAI,EAAE,GAAG,qBAAqB,CAAC,SAAS,EAAE,EAC1C,MAAM,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,EACzB,QAAQ,EAAE,CAAC,OAAO,EAAE;QAClB,IAAI,EAAE,GAAG,qBAAqB,CAAC,SAAS,EAAE,CAAA;QAC1C,KAAK,EAAE,MAAM,CAAA;QACb,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KACnB,KAAK,IAAI,GACT,eAAe;IASlB,IAAI,CACF,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,EAC7C,IAAI,GAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAO,GAChC,OAAO,CAAC,2BAA2B,CAAC;IAwBvC,iBAAiB,CAAC,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,GAAG,IAAI;IAIxD;;;;;;;;OAQG;IACH,WAAW,CAAC,OAAO,SAAe,GAAG,OAAO,CAAC,IAAI,GAAG,WAAW,GAAG,OAAO,CAAC;CAqS3E"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.js b/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.js new file mode 100644 index 0000000..9abc837 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.js @@ -0,0 +1,451 @@ +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 { CHANNEL_EVENTS, CHANNEL_STATES } from './lib/constants'; +import Push from './lib/push'; +import Timer from './lib/timer'; +import RealtimePresence from './RealtimePresence'; +import * as Transformers from './lib/transformers'; +export var REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; +(function (REALTIME_POSTGRES_CHANGES_LISTEN_EVENT) { + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["ALL"] = "*"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["INSERT"] = "INSERT"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["UPDATE"] = "UPDATE"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["DELETE"] = "DELETE"; +})(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT || (REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = {})); +export var REALTIME_LISTEN_TYPES; +(function (REALTIME_LISTEN_TYPES) { + REALTIME_LISTEN_TYPES["BROADCAST"] = "broadcast"; + REALTIME_LISTEN_TYPES["PRESENCE"] = "presence"; + /** + * listen to Postgres changes. + */ + REALTIME_LISTEN_TYPES["POSTGRES_CHANGES"] = "postgres_changes"; +})(REALTIME_LISTEN_TYPES || (REALTIME_LISTEN_TYPES = {})); +export var REALTIME_SUBSCRIBE_STATES; +(function (REALTIME_SUBSCRIBE_STATES) { + REALTIME_SUBSCRIBE_STATES["SUBSCRIBED"] = "SUBSCRIBED"; + REALTIME_SUBSCRIBE_STATES["TIMED_OUT"] = "TIMED_OUT"; + REALTIME_SUBSCRIBE_STATES["CLOSED"] = "CLOSED"; + REALTIME_SUBSCRIBE_STATES["CHANNEL_ERROR"] = "CHANNEL_ERROR"; +})(REALTIME_SUBSCRIBE_STATES || (REALTIME_SUBSCRIBE_STATES = {})); +/** A channel is the basic building block of Realtime + * and narrows the scope of data flow to subscribed clients. + * You can think of a channel as a chatroom where participants are able to see who's online + * and send and receive messages. + **/ +export default class RealtimeChannel { + constructor( + /** Topic name can be any string. */ + topic, params = { config: {} }, socket) { + this.topic = topic; + this.params = params; + this.socket = socket; + this.bindings = {}; + this.state = CHANNEL_STATES.closed; + this.joinedOnce = false; + this.pushBuffer = []; + this.params.config = Object.assign({ + broadcast: { ack: false, self: false }, + presence: { key: '' }, + }, params.config); + this.timeout = this.socket.timeout; + this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout); + this.rejoinTimer = new Timer(() => this._rejoinUntilConnected(), this.socket.reconnectAfterMs); + this.joinPush.receive('ok', () => { + this.state = CHANNEL_STATES.joined; + this.rejoinTimer.reset(); + this.pushBuffer.forEach((pushEvent) => pushEvent.send()); + this.pushBuffer = []; + }); + this._onClose(() => { + this.rejoinTimer.reset(); + this.socket.log('channel', `close ${this.topic} ${this._joinRef()}`); + this.state = CHANNEL_STATES.closed; + this.socket._remove(this); + }); + this._onError((reason) => { + if (this._isLeaving() || this._isClosed()) { + return; + } + this.socket.log('channel', `error ${this.topic}`, reason); + this.state = CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this.joinPush.receive('timeout', () => { + if (!this._isJoining()) { + return; + } + this.socket.log('channel', `timeout ${this.topic}`, this.joinPush.timeout); + this.state = CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this._on(CHANNEL_EVENTS.reply, {}, (payload, ref) => { + this._trigger(this._replyEventName(ref), payload); + }); + this.presence = new RealtimePresence(this); + } + /** Subscribe registers your client with the server */ + subscribe(callback, timeout = this.timeout) { + var _a, _b; + if (this.joinedOnce) { + throw `tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance`; + } + else { + const { config: { broadcast, presence }, } = this.params; + this._onError((e) => callback && callback('CHANNEL_ERROR', e)); + this._onClose(() => callback && callback('CLOSED')); + const accessTokenPayload = {}; + const config = { + broadcast, + presence, + postgres_changes: (_b = (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.map((r) => r.filter)) !== null && _b !== void 0 ? _b : [], + }; + if (this.socket.accessToken) { + accessTokenPayload.access_token = this.socket.accessToken; + } + this.updateJoinPayload(Object.assign({ config }, accessTokenPayload)); + this.joinedOnce = true; + this._rejoin(timeout); + this.joinPush + .receive('ok', ({ postgres_changes: serverPostgresFilters, }) => { + var _a; + this.socket.accessToken && + this.socket.setAuth(this.socket.accessToken); + if (serverPostgresFilters === undefined) { + callback && callback('SUBSCRIBED'); + return; + } + else { + const clientPostgresBindings = this.bindings.postgres_changes; + const bindingsLen = (_a = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a !== void 0 ? _a : 0; + const newPostgresBindings = []; + for (let i = 0; i < bindingsLen; i++) { + const clientPostgresBinding = clientPostgresBindings[i]; + const { filter: { event, schema, table, filter }, } = clientPostgresBinding; + const serverPostgresFilter = serverPostgresFilters && serverPostgresFilters[i]; + if (serverPostgresFilter && + serverPostgresFilter.event === event && + serverPostgresFilter.schema === schema && + serverPostgresFilter.table === table && + serverPostgresFilter.filter === filter) { + newPostgresBindings.push(Object.assign(Object.assign({}, clientPostgresBinding), { id: serverPostgresFilter.id })); + } + else { + this.unsubscribe(); + callback && + callback('CHANNEL_ERROR', new Error('mismatch between server and client bindings for postgres changes')); + return; + } + } + this.bindings.postgres_changes = newPostgresBindings; + callback && callback('SUBSCRIBED'); + return; + } + }) + .receive('error', (error) => { + callback && + callback('CHANNEL_ERROR', new Error(JSON.stringify(Object.values(error).join(', ') || 'error'))); + return; + }) + .receive('timeout', () => { + callback && callback('TIMED_OUT'); + return; + }); + } + return this; + } + presenceState() { + return this.presence.state; + } + track(payload, opts = {}) { + return __awaiter(this, void 0, void 0, function* () { + return yield this.send({ + type: 'presence', + event: 'track', + payload, + }, opts.timeout || this.timeout); + }); + } + untrack(opts = {}) { + return __awaiter(this, void 0, void 0, function* () { + return yield this.send({ + type: 'presence', + event: 'untrack', + }, opts); + }); + } + on(type, filter, callback) { + return this._on(type, filter, callback); + } + send(payload, opts = {}) { + return new Promise((resolve) => { + var _a, _b, _c; + const push = this._push(payload.type, payload, opts.timeout || this.timeout); + if (push.rateLimited) { + resolve('rate limited'); + } + if (payload.type === 'broadcast' && + !((_c = (_b = (_a = this.params) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.broadcast) === null || _c === void 0 ? void 0 : _c.ack)) { + resolve('ok'); + } + push.receive('ok', () => resolve('ok')); + push.receive('timeout', () => resolve('timed out')); + }); + } + updateJoinPayload(payload) { + this.joinPush.updatePayload(payload); + } + /** + * Leaves the channel. + * + * Unsubscribes from server events, and instructs channel to terminate on server. + * Triggers onClose() hooks. + * + * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: + * channel.unsubscribe().receive("ok", () => alert("left!") ) + */ + unsubscribe(timeout = this.timeout) { + this.state = CHANNEL_STATES.leaving; + const onClose = () => { + this.socket.log('channel', `leave ${this.topic}`); + this._trigger(CHANNEL_EVENTS.close, 'leave', this._joinRef()); + }; + this.rejoinTimer.reset(); + // Destroy joinPush to avoid connection timeouts during unscription phase + this.joinPush.destroy(); + return new Promise((resolve) => { + const leavePush = new Push(this, CHANNEL_EVENTS.leave, {}, timeout); + leavePush + .receive('ok', () => { + onClose(); + resolve('ok'); + }) + .receive('timeout', () => { + onClose(); + resolve('timed out'); + }) + .receive('error', () => { + resolve('error'); + }); + leavePush.send(); + if (!this._canPush()) { + leavePush.trigger('ok', {}); + } + }); + } + /** @internal */ + _push(event, payload, timeout = this.timeout) { + if (!this.joinedOnce) { + throw `tried to push '${event}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`; + } + let pushEvent = new Push(this, event, payload, timeout); + if (this._canPush()) { + pushEvent.send(); + } + else { + pushEvent.startTimeout(); + this.pushBuffer.push(pushEvent); + } + return pushEvent; + } + /** + * Overridable message hook + * + * Receives all events for specialized message handling before dispatching to the channel callbacks. + * Must return the payload, modified or unmodified. + * + * @internal + */ + _onMessage(_event, payload, _ref) { + return payload; + } + /** @internal */ + _isMember(topic) { + return this.topic === topic; + } + /** @internal */ + _joinRef() { + return this.joinPush.ref; + } + /** @internal */ + _trigger(type, payload, ref) { + var _a, _b; + const typeLower = type.toLocaleLowerCase(); + const { close, error, leave, join } = CHANNEL_EVENTS; + const events = [close, error, leave, join]; + if (ref && events.indexOf(typeLower) >= 0 && ref !== this._joinRef()) { + return; + } + let handledPayload = this._onMessage(typeLower, payload, ref); + if (payload && !handledPayload) { + throw 'channel onMessage callbacks must return the payload, modified or unmodified'; + } + if (['insert', 'update', 'delete'].includes(typeLower)) { + (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.filter((bind) => { + var _a, _b, _c; + return (((_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event) === '*' || + ((_c = (_b = bind.filter) === null || _b === void 0 ? void 0 : _b.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower); + }).map((bind) => bind.callback(handledPayload, ref)); + } + else { + (_b = this.bindings[typeLower]) === null || _b === void 0 ? void 0 : _b.filter((bind) => { + var _a, _b, _c, _d, _e, _f; + if (['broadcast', 'presence', 'postgres_changes'].includes(typeLower)) { + if ('id' in bind) { + const bindId = bind.id; + const bindEvent = (_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event; + return (bindId && + ((_b = payload.ids) === null || _b === void 0 ? void 0 : _b.includes(bindId)) && + (bindEvent === '*' || + (bindEvent === null || bindEvent === void 0 ? void 0 : bindEvent.toLocaleLowerCase()) === + ((_c = payload.data) === null || _c === void 0 ? void 0 : _c.type.toLocaleLowerCase()))); + } + else { + const bindEvent = (_e = (_d = bind === null || bind === void 0 ? void 0 : bind.filter) === null || _d === void 0 ? void 0 : _d.event) === null || _e === void 0 ? void 0 : _e.toLocaleLowerCase(); + return (bindEvent === '*' || + bindEvent === ((_f = payload === null || payload === void 0 ? void 0 : payload.event) === null || _f === void 0 ? void 0 : _f.toLocaleLowerCase())); + } + } + else { + return bind.type.toLocaleLowerCase() === typeLower; + } + }).map((bind) => { + if (typeof handledPayload === 'object' && 'ids' in handledPayload) { + const postgresChanges = handledPayload.data; + const { schema, table, commit_timestamp, type, errors } = postgresChanges; + const enrichedPayload = { + schema: schema, + table: table, + commit_timestamp: commit_timestamp, + eventType: type, + new: {}, + old: {}, + errors: errors, + }; + handledPayload = Object.assign(Object.assign({}, enrichedPayload), this._getPayloadRecords(postgresChanges)); + } + bind.callback(handledPayload, ref); + }); + } + } + /** @internal */ + _isClosed() { + return this.state === CHANNEL_STATES.closed; + } + /** @internal */ + _isJoined() { + return this.state === CHANNEL_STATES.joined; + } + /** @internal */ + _isJoining() { + return this.state === CHANNEL_STATES.joining; + } + /** @internal */ + _isLeaving() { + return this.state === CHANNEL_STATES.leaving; + } + /** @internal */ + _replyEventName(ref) { + return `chan_reply_${ref}`; + } + /** @internal */ + _on(type, filter, callback) { + const typeLower = type.toLocaleLowerCase(); + const binding = { + type: typeLower, + filter: filter, + callback: callback, + }; + if (this.bindings[typeLower]) { + this.bindings[typeLower].push(binding); + } + else { + this.bindings[typeLower] = [binding]; + } + return this; + } + /** @internal */ + _off(type, filter) { + const typeLower = type.toLocaleLowerCase(); + this.bindings[typeLower] = this.bindings[typeLower].filter((bind) => { + var _a; + return !(((_a = bind.type) === null || _a === void 0 ? void 0 : _a.toLocaleLowerCase()) === typeLower && + RealtimeChannel.isEqual(bind.filter, filter)); + }); + return this; + } + /** @internal */ + static isEqual(obj1, obj2) { + if (Object.keys(obj1).length !== Object.keys(obj2).length) { + return false; + } + for (const k in obj1) { + if (obj1[k] !== obj2[k]) { + return false; + } + } + return true; + } + /** @internal */ + _rejoinUntilConnected() { + this.rejoinTimer.scheduleTimeout(); + if (this.socket.isConnected()) { + this._rejoin(); + } + } + /** + * Registers a callback that will be executed when the channel closes. + * + * @internal + */ + _onClose(callback) { + this._on(CHANNEL_EVENTS.close, {}, callback); + } + /** + * Registers a callback that will be executed when the channel encounteres an error. + * + * @internal + */ + _onError(callback) { + this._on(CHANNEL_EVENTS.error, {}, (reason) => callback(reason)); + } + /** + * Returns `true` if the socket is connected and the channel has been joined. + * + * @internal + */ + _canPush() { + return this.socket.isConnected() && this._isJoined(); + } + /** @internal */ + _rejoin(timeout = this.timeout) { + if (this._isLeaving()) { + return; + } + this.socket._leaveOpenTopic(this.topic); + this.state = CHANNEL_STATES.joining; + this.joinPush.resend(timeout); + } + /** @internal */ + _getPayloadRecords(payload) { + const records = { + new: {}, + old: {}, + }; + if (payload.type === 'INSERT' || payload.type === 'UPDATE') { + records.new = Transformers.convertChangeData(payload.columns, payload.record); + } + if (payload.type === 'UPDATE' || payload.type === 'DELETE') { + records.old = Transformers.convertChangeData(payload.columns, payload.old_record); + } + return records; + } +} +//# sourceMappingURL=RealtimeChannel.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.js.map b/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.js.map new file mode 100644 index 0000000..973913d --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/RealtimeChannel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimeChannel.js","sourceRoot":"","sources":["../../src/RealtimeChannel.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAChE,OAAO,IAAI,MAAM,YAAY,CAAA;AAE7B,OAAO,KAAK,MAAM,aAAa,CAAA;AAC/B,OAAO,gBAEN,MAAM,oBAAoB,CAAA;AAM3B,OAAO,KAAK,YAAY,MAAM,oBAAoB,CAAA;AAwElD,MAAM,CAAN,IAAY,sCAKX;AALD,WAAY,sCAAsC;IAChD,mDAAS,CAAA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AgB;IACR,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO;QACpC,IAAI,IAAI,CAAC,UAAU,EAAE,EAAE;YACrB,OAAM;SACP;QACD,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QACvC,IAAI,CAAC,KAAK,GAAG,cAAc,CAAC,OAAO,CAAA;QACnC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;IAC/B,CAAC;IAED,gBAAgB;IACR,kBAAkB,CAAC,OAAY;QACrC,MAAM,OAAO,GAAG;YACd,GAAG,EAAE,EAAE;YACP,GAAG,EAAE,EAAE;SACR,CAAA;QAED,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE;YAC1D,OAAO,CAAC,GAAG,GAAG,YAAY,CAAC,iBAAiB,CAC1C,OAAO,CAAC,OAAO,EACf,OAAO,CAAC,MAAM,CACf,CAAA;SACF;QAED,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE;YAC1D,OAAO,CAAC,GAAG,GAAG,YAAY,CAAC,iBAAiB,CAC1C,OAAO,CAAC,OAAO,EACf,OAAO,CAAC,UAAU,CACnB,CAAA;SACF;QAED,OAAO,OAAO,CAAA;IAChB,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.d.ts b/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.d.ts new file mode 100644 index 0000000..8d3d3df --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.d.ts @@ -0,0 +1,129 @@ +import { CONNECTION_STATE } from './lib/constants'; +import Timer from './lib/timer'; +import Serializer from './lib/serializer'; +import RealtimeChannel from './RealtimeChannel'; +import type { RealtimeChannelOptions } from './RealtimeChannel'; +export declare type RealtimeClientOptions = { + transport?: WebSocket; + timeout?: number; + heartbeatIntervalMs?: number; + logger?: Function; + encode?: Function; + decode?: Function; + reconnectAfterMs?: Function; + headers?: { + [key: string]: string; + }; + params?: { + [key: string]: any; + }; + log_level?: 'info' | 'debug' | 'warn' | 'error'; +}; +export declare type RealtimeMessage = { + topic: string; + event: string; + payload: any; + ref: string; + join_ref?: string; +}; +export declare type RealtimeRemoveChannelResponse = 'ok' | 'timed out' | 'error'; +export default class RealtimeClient { + accessToken: string | null; + channels: RealtimeChannel[]; + endPoint: string; + headers?: { + [key: string]: string; + }; + params?: { + [key: string]: string; + }; + timeout: number; + transport: any; + heartbeatIntervalMs: number; + heartbeatTimer: ReturnType | undefined; + pendingHeartbeatRef: string | null; + ref: number; + reconnectTimer: Timer; + logger: Function; + encode: Function; + decode: Function; + reconnectAfterMs: Function; + conn: WebSocket | null; + sendBuffer: Function[]; + serializer: Serializer; + stateChangeCallbacks: { + open: Function[]; + close: Function[]; + error: Function[]; + message: Function[]; + }; + eventsPerSecondLimitMs: number; + inThrottle: boolean; + /** + * Initializes the Socket. + * + * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) + * @param options.transport The Websocket Transport, for example WebSocket. + * @param options.timeout The default timeout in milliseconds to trigger push timeouts. + * @param options.params The optional params to pass when connecting. + * @param options.headers The optional headers to pass when connecting. + * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. + * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } + * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) + * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. + * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. + */ + constructor(endPoint: string, options?: RealtimeClientOptions); + /** + * Connects the socket, unless already connected. + */ + connect(): void; + /** + * Disconnects the socket. + * + * @param code A numeric status code to send on disconnect. + * @param reason A custom reason for the disconnect. + */ + disconnect(code?: number, reason?: string): void; + /** + * Returns all created channels + */ + getChannels(): RealtimeChannel[]; + /** + * Unsubscribes and removes a single channel + * @param channel A RealtimeChannel instance + */ + removeChannel(channel: RealtimeChannel): Promise; + /** + * Unsubscribes and removes all channels + */ + removeAllChannels(): Promise; + /** + * Logs the message. + * + * For customized logging, `this.logger` can be overridden. + */ + log(kind: string, msg: string, data?: any): void; + /** + * Returns the current state of the socket. + */ + connectionState(): CONNECTION_STATE; + /** + * Returns `true` is the connection is open. + */ + isConnected(): boolean; + channel(topic: string, params?: RealtimeChannelOptions): RealtimeChannel; + /** + * Push out a message if the socket is connected. + * + * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. + */ + push(data: RealtimeMessage): 'rate limited' | void; + /** + * Sets the JWT access token used for channel subscription authorization and Realtime RLS. + * + * @param token A JWT string. + */ + setAuth(token: string | null): void; +} +//# sourceMappingURL=RealtimeClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.d.ts.map b/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.d.ts.map new file mode 100644 index 0000000..b5a0bd5 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimeClient.d.ts","sourceRoot":"","sources":["../../src/RealtimeClient.ts"],"names":[],"mappings":"AACA,OAAO,EAQL,gBAAgB,EACjB,MAAM,iBAAiB,CAAA;AACxB,OAAO,KAAK,MAAM,aAAa,CAAA;AAC/B,OAAO,UAAU,MAAM,kBAAkB,CAAA;AACzC,OAAO,eAAe,MAAM,mBAAmB,CAAA;AAC/C,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAA;AAE/D,oBAAY,qBAAqB,GAAG;IAClC,SAAS,CAAC,EAAE,SAAS,CAAA;IACrB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,mBAAmB,CAAC,EAAE,MAAM,CAAA;IA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GAAG,IAAI;IAsBlD;;;;OAIG;IACH,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI;CAsMpC"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.js b/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.js new file mode 100644 index 0000000..2d933c1 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.js @@ -0,0 +1,376 @@ +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 { w3cwebsocket } from 'websocket'; +import { VSN, CHANNEL_EVENTS, TRANSPORTS, SOCKET_STATES, DEFAULT_TIMEOUT, WS_CLOSE_NORMAL, DEFAULT_HEADERS, CONNECTION_STATE, } from './lib/constants'; +import Timer from './lib/timer'; +import Serializer from './lib/serializer'; +import RealtimeChannel from './RealtimeChannel'; +const noop = () => { }; +export default class RealtimeClient { + /** + * Initializes the Socket. + * + * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) + * @param options.transport The Websocket Transport, for example WebSocket. + * @param options.timeout The default timeout in milliseconds to trigger push timeouts. + * @param options.params The optional params to pass when connecting. + * @param options.headers The optional headers to pass when connecting. + * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. + * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } + * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) + * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. + * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. + */ + constructor(endPoint, options) { + var _a; + this.accessToken = null; + this.channels = []; + this.endPoint = ''; + this.headers = DEFAULT_HEADERS; + this.params = {}; + this.timeout = DEFAULT_TIMEOUT; + this.transport = w3cwebsocket; + this.heartbeatIntervalMs = 30000; + this.heartbeatTimer = undefined; + this.pendingHeartbeatRef = null; + this.ref = 0; + this.logger = noop; + this.conn = null; + this.sendBuffer = []; + this.serializer = new Serializer(); + this.stateChangeCallbacks = { + open: [], + close: [], + error: [], + message: [], + }; + this.eventsPerSecondLimitMs = 100; + this.inThrottle = false; + this.endPoint = `${endPoint}/${TRANSPORTS.websocket}`; + if (options === null || options === void 0 ? void 0 : options.params) + this.params = options.params; + if (options === null || options === void 0 ? void 0 : options.headers) + this.headers = Object.assign(Object.assign({}, this.headers), options.headers); + if (options === null || options === void 0 ? void 0 : options.timeout) + this.timeout = options.timeout; + if (options === null || options === void 0 ? void 0 : options.logger) + this.logger = options.logger; + if (options === null || options === void 0 ? void 0 : options.transport) + this.transport = options.transport; + if (options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) + this.heartbeatIntervalMs = options.heartbeatIntervalMs; + const eventsPerSecond = (_a = options === null || options === void 0 ? void 0 : options.params) === null || _a === void 0 ? void 0 : _a.eventsPerSecond; + if (eventsPerSecond) + this.eventsPerSecondLimitMs = Math.floor(1000 / eventsPerSecond); + this.reconnectAfterMs = (options === null || options === void 0 ? void 0 : options.reconnectAfterMs) + ? options.reconnectAfterMs + : (tries) => { + return [1000, 2000, 5000, 10000][tries - 1] || 10000; + }; + this.encode = (options === null || options === void 0 ? void 0 : options.encode) + ? options.encode + : (payload, callback) => { + return callback(JSON.stringify(payload)); + }; + this.decode = (options === null || options === void 0 ? void 0 : options.decode) + ? options.decode + : this.serializer.decode.bind(this.serializer); + this.reconnectTimer = new Timer(() => __awaiter(this, void 0, void 0, function* () { + this.disconnect(); + this.connect(); + }), this.reconnectAfterMs); + } + /** + * Connects the socket, unless already connected. + */ + connect() { + if (this.conn) { + return; + } + this.conn = new this.transport(this._endPointURL(), [], null, this.headers); + if (this.conn) { + this.conn.binaryType = 'arraybuffer'; + this.conn.onopen = () => this._onConnOpen(); + this.conn.onerror = (error) => this._onConnError(error); + this.conn.onmessage = (event) => this._onConnMessage(event); + this.conn.onclose = (event) => this._onConnClose(event); + } + } + /** + * Disconnects the socket. + * + * @param code A numeric status code to send on disconnect. + * @param reason A custom reason for the disconnect. + */ + disconnect(code, reason) { + if (this.conn) { + this.conn.onclose = function () { }; // noop + if (code) { + this.conn.close(code, reason !== null && reason !== void 0 ? reason : ''); + } + else { + this.conn.close(); + } + this.conn = null; + // remove open handles + this.heartbeatTimer && clearInterval(this.heartbeatTimer); + this.reconnectTimer.reset(); + } + } + /** + * Returns all created channels + */ + getChannels() { + return this.channels; + } + /** + * Unsubscribes and removes a single channel + * @param channel A RealtimeChannel instance + */ + removeChannel(channel) { + return __awaiter(this, void 0, void 0, function* () { + const status = yield channel.unsubscribe(); + if (this.channels.length === 0) { + this.disconnect(); + } + return status; + }); + } + /** + * Unsubscribes and removes all channels + */ + removeAllChannels() { + return __awaiter(this, void 0, void 0, function* () { + const values_1 = yield Promise.all(this.channels.map((channel) => channel.unsubscribe())); + this.disconnect(); + return values_1; + }); + } + /** + * Logs the message. + * + * For customized logging, `this.logger` can be overridden. + */ + log(kind, msg, data) { + this.logger(kind, msg, data); + } + /** + * Returns the current state of the socket. + */ + connectionState() { + switch (this.conn && this.conn.readyState) { + case SOCKET_STATES.connecting: + return CONNECTION_STATE.Connecting; + case SOCKET_STATES.open: + return CONNECTION_STATE.Open; + case SOCKET_STATES.closing: + return CONNECTION_STATE.Closing; + default: + return CONNECTION_STATE.Closed; + } + } + /** + * Returns `true` is the connection is open. + */ + isConnected() { + return this.connectionState() === CONNECTION_STATE.Open; + } + channel(topic, params = { config: {} }) { + if (!this.isConnected()) { + this.connect(); + } + const chan = new RealtimeChannel(`realtime:${topic}`, params, this); + this.channels.push(chan); + return chan; + } + /** + * Push out a message if the socket is connected. + * + * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. + */ + push(data) { + const { topic, event, payload, ref } = data; + let callback = () => { + this.encode(data, (result) => { + var _a; + (_a = this.conn) === null || _a === void 0 ? void 0 : _a.send(result); + }); + }; + this.log('push', `${topic} ${event} (${ref})`, payload); + if (this.isConnected()) { + if (['broadcast', 'presence', 'postgres_changes'].includes(event)) { + const isThrottled = this._throttle(callback)(); + if (isThrottled) { + return 'rate limited'; + } + } + else { + callback(); + } + } + else { + this.sendBuffer.push(callback); + } + } + /** + * Sets the JWT access token used for channel subscription authorization and Realtime RLS. + * + * @param token A JWT string. + */ + setAuth(token) { + this.accessToken = token; + this.channels.forEach((channel) => { + token && channel.updateJoinPayload({ access_token: token }); + if (channel.joinedOnce && channel._isJoined()) { + channel._push(CHANNEL_EVENTS.access_token, { access_token: token }); + } + }); + } + /** + * Return the next message ref, accounting for overflows + * + * @internal + */ + _makeRef() { + let newRef = this.ref + 1; + if (newRef === this.ref) { + this.ref = 0; + } + else { + this.ref = newRef; + } + return this.ref.toString(); + } + /** + * Unsubscribe from channels with the specified topic. + * + * @internal + */ + _leaveOpenTopic(topic) { + let dupChannel = this.channels.find((c) => c.topic === topic && (c._isJoined() || c._isJoining())); + if (dupChannel) { + this.log('transport', `leaving duplicate topic "${topic}"`); + dupChannel.unsubscribe(); + } + } + /** + * Removes a subscription from the socket. + * + * @param channel An open subscription. + * + * @internal + */ + _remove(channel) { + this.channels = this.channels.filter((c) => c._joinRef() !== channel._joinRef()); + } + /** + * Returns the URL of the websocket. + * + * @internal + */ + _endPointURL() { + return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: VSN })); + } + /** @internal */ + _onConnMessage(rawMessage) { + this.decode(rawMessage.data, (msg) => { + let { topic, event, payload, ref } = msg; + if ((ref && ref === this.pendingHeartbeatRef) || + event === (payload === null || payload === void 0 ? void 0 : payload.type)) { + this.pendingHeartbeatRef = null; + } + this.log('receive', `${payload.status || ''} ${topic} ${event} ${(ref && '(' + ref + ')') || ''}`, payload); + this.channels + .filter((channel) => channel._isMember(topic)) + .forEach((channel) => channel._trigger(event, payload, ref)); + this.stateChangeCallbacks.message.forEach((callback) => callback(msg)); + }); + } + /** @internal */ + _onConnOpen() { + this.log('transport', `connected to ${this._endPointURL()}`); + this._flushSendBuffer(); + this.reconnectTimer.reset(); + this.heartbeatTimer && clearInterval(this.heartbeatTimer); + this.heartbeatTimer = setInterval(() => this._sendHeartbeat(), this.heartbeatIntervalMs); + this.stateChangeCallbacks.open.forEach((callback) => callback()); + } + /** @internal */ + _onConnClose(event) { + this.log('transport', 'close', event); + this._triggerChanError(); + this.heartbeatTimer && clearInterval(this.heartbeatTimer); + this.reconnectTimer.scheduleTimeout(); + this.stateChangeCallbacks.close.forEach((callback) => callback(event)); + } + /** @internal */ + _onConnError(error) { + this.log('transport', error.message); + this._triggerChanError(); + this.stateChangeCallbacks.error.forEach((callback) => callback(error)); + } + /** @internal */ + _triggerChanError() { + this.channels.forEach((channel) => channel._trigger(CHANNEL_EVENTS.error)); + } + /** @internal */ + _appendParams(url, params) { + if (Object.keys(params).length === 0) { + return url; + } + const prefix = url.match(/\?/) ? '&' : '?'; + const query = new URLSearchParams(params); + return `${url}${prefix}${query}`; + } + /** @internal */ + _flushSendBuffer() { + if (this.isConnected() && this.sendBuffer.length > 0) { + this.sendBuffer.forEach((callback) => callback()); + this.sendBuffer = []; + } + } + /** @internal */ + _sendHeartbeat() { + var _a; + if (!this.isConnected()) { + return; + } + if (this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null; + this.log('transport', 'heartbeat timeout. Attempting to re-establish connection'); + (_a = this.conn) === null || _a === void 0 ? void 0 : _a.close(WS_CLOSE_NORMAL, 'hearbeat timeout'); + return; + } + this.pendingHeartbeatRef = this._makeRef(); + this.push({ + topic: 'phoenix', + event: 'heartbeat', + payload: {}, + ref: this.pendingHeartbeatRef, + }); + this.setAuth(this.accessToken); + } + /** @internal */ + _throttle(callback, eventsPerSecondLimitMs = this.eventsPerSecondLimitMs) { + return () => { + if (this.inThrottle) + return true; + callback(); + if (eventsPerSecondLimitMs > 0) { + this.inThrottle = true; + setTimeout(() => { + this.inThrottle = false; + }, eventsPerSecondLimitMs); + } + return false; + }; + } +} +//# sourceMappingURL=RealtimeClient.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.js.map b/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.js.map new file mode 100644 index 0000000..33dd520 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/RealtimeClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimeClient.js","sourceRoot":"","sources":["../../src/RealtimeClient.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA;AACxC,OAAO,EACL,GAAG,EACH,cAAc,EACd,UAAU,EACV,aAAa,EACb,eAAe,EACf,eAAe,EACf,eAAe,EACf,gBAAgB,GACjB,MAAM,iBAAiB,CAAA;AACxB,OAAO,KAAK,MAAM,aAAa,CAAA;AAC/B,OAAO,UAAU,MAAM,kBAAkB,CAAA;AACzC,OAAO,eAAe,MAAM,mBAAmB,CAAA;AA0B/C,MAAM,IAAI,GAAG,GAAG,EAAE,GAAE,CAAC,CAAA;AAErB,MAAM,CAAC,OAAO,OAAO,cAAc;IAkCjC;;;;;;;;;;;;;OAaG;IACH,YAAY,QAAgB,EAAE,OAA+B;;QA/C7D,gBAAW,GAAkB,IAAI,CAAA;QACjC,aAAQ,GAAsB,EAAE,CAAA;QAChC,aAAQ,GAAW,EAAE,CAAA;QACrB,YAAO,GAA+B,eAAe,CAAA;QACrD,WAAM,GAA+B,EAAE,CAAA;QACvC,YAAO,GAAW,eAAe,CAAA;QACjC,cAAS,GAAQ,YAAY,CAAA;QAC7B,wBAAmB,GAAW,KAAK,CAAA;QACnC,mBAAc,GAA+C,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CAAA;QAC1C,IAAI,CAAC,IAAI,CAAC;YACR,KAAK,EAAE,SAAS;YAChB,KAAK,EAAE,WAAW;YAClB,OAAO,EAAE,EAAE;YACX,GAAG,EAAE,IAAI,CAAC,mBAAmB;SAC9B,CAAC,CAAA;QACF,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAA;IAChC,CAAC;IAED,gBAAgB;IACR,SAAS,CACf,QAAkB,EAClB,yBAAiC,IAAI,CAAC,sBAAsB;QAE5D,OAAO,GAAG,EAAE;YACV,IAAI,IAAI,CAAC,UAAU;gBAAE,OAAO,IAAI,CAAA;YAEhC,QAAQ,EAAE,CAAA;YAEV,IAAI,sBAAsB,GAAG,CAAC,EAAE;gBAC9B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAA;gBAEtB,UAAU,CAAC,GAAG,EAAE;oBACd,IAAI,CAAC,UAAU,GAAG,KAAK,CAAA;gBACzB,CAAC,EAAE,sBAAsB,CAAC,CAAA;aAC3B;YAED,OAAO,KAAK,CAAA;QACd,CAAC,CAAA;IACH,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.d.ts b/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.d.ts new file mode 100644 index 0000000..2972a4c --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.d.ts @@ -0,0 +1,67 @@ +import type { PresenceOpts, PresenceOnJoinCallback, PresenceOnLeaveCallback } from 'phoenix'; +import type RealtimeChannel from './RealtimeChannel'; +declare type Presence = { + presence_ref: string; +} & T; +export declare type RealtimePresenceState = { + [key: string]: Presence[]; +}; +export declare type RealtimePresenceJoinPayload = { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.JOIN}`; + key: string; + currentPresences: Presence[]; + newPresences: Presence[]; +}; +export declare type RealtimePresenceLeavePayload = { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.LEAVE}`; + key: string; + currentPresences: Presence[]; + leftPresences: Presence[]; +}; +export declare enum REALTIME_PRESENCE_LISTEN_EVENTS { + SYNC = "sync", + JOIN = "join", + LEAVE = "leave" +} +declare type RawPresenceState = { + [key: string]: { + metas: { + phx_ref?: string; + phx_ref_prev?: string; + [key: string]: any; + }[]; + }; +}; +declare type RawPresenceDiff = { + joins: RawPresenceState; + leaves: RawPresenceState; +}; +export default class RealtimePresence { + channel: RealtimeChannel; + state: RealtimePresenceState; + pendingDiffs: RawPresenceDiff[]; + joinRef: string | null; + caller: { + onJoin: PresenceOnJoinCallback; + onLeave: PresenceOnLeaveCallback; + onSync: () => void; + }; + /** + * Initializes the Presence. + * + * @param channel - The RealtimeChannel + * @param opts - The options, + * for example `{events: {state: 'state', diff: 'diff'}}` + */ + constructor(channel: RealtimeChannel, opts?: PresenceOpts); +} +export {}; +//# sourceMappingURL=RealtimePresence.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.d.ts.map b/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.d.ts.map new file mode 100644 index 0000000..0d33ce0 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimePresence.d.ts","sourceRoot":"","sources":["../../src/RealtimePresence.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EACV,YAAY,EACZ,sBAAsB,EACtB,uBAAuB,EACxB,MAAM,SAAS,CAAA;AAChB,OAAO,KAAK,eAAe,MAAM,mBAAmB,CAAA;AAEpD,aAAK,QAAQ,CAAC,CAAC,SAAS;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;CAAE,GAAG,EAAE,IAAI;IACrD,YAAY,EAAE,MAAM,CAAA;CACrB,GAAG,CAAC,CAAA;AAEL,oBAAY,qBAAqB,CAAC,CAAC,SAAS;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;CAAE,GAAG,EAAE,IAAI;IACzE,CAAC,GAAG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e,EAAE,CAAK;IACpC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAO;IAC7B,MAAM,EAAE;QACN,MAAM,EAAE,sBAAsB,CAAA;QAC9B,OAAO,EAAE,uBAAuB,CAAA;QAChC,MAAM,EAAE,MAAM,IAAI,CAAA;KACnB,CAIA;IAED;;;;;;OAMG;gBACgB,OAAO,EAAE,eAAe,EAAE,IAAI,CAAC,EAAE,YAAY;CAwRjE"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.js b/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.js new file mode 100644 index 0000000..1fd672c --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.js @@ -0,0 +1,224 @@ +/* + This file draws heavily from https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/assets/js/phoenix/presence.js + License: https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/LICENSE.md +*/ +export var REALTIME_PRESENCE_LISTEN_EVENTS; +(function (REALTIME_PRESENCE_LISTEN_EVENTS) { + REALTIME_PRESENCE_LISTEN_EVENTS["SYNC"] = "sync"; + REALTIME_PRESENCE_LISTEN_EVENTS["JOIN"] = "join"; + REALTIME_PRESENCE_LISTEN_EVENTS["LEAVE"] = "leave"; +})(REALTIME_PRESENCE_LISTEN_EVENTS || (REALTIME_PRESENCE_LISTEN_EVENTS = {})); +export default class RealtimePresence { + /** + * Initializes the Presence. + * + * @param channel - The RealtimeChannel + * @param opts - The options, + * for example `{events: {state: 'state', diff: 'diff'}}` + */ + constructor(channel, opts) { + this.channel = channel; + this.state = {}; + this.pendingDiffs = []; + this.joinRef = null; + this.caller = { + onJoin: () => { }, + onLeave: () => { }, + onSync: () => { }, + }; + const events = (opts === null || opts === void 0 ? void 0 : opts.events) || { + state: 'presence_state', + diff: 'presence_diff', + }; + this.channel._on(events.state, {}, (newState) => { + const { onJoin, onLeave, onSync } = this.caller; + this.joinRef = this.channel._joinRef(); + this.state = RealtimePresence.syncState(this.state, newState, onJoin, onLeave); + this.pendingDiffs.forEach((diff) => { + this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + }); + this.pendingDiffs = []; + onSync(); + }); + this.channel._on(events.diff, {}, (diff) => { + const { onJoin, onLeave, onSync } = this.caller; + if (this.inPendingSyncState()) { + this.pendingDiffs.push(diff); + } + else { + this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + onSync(); + } + }); + this.onJoin((key, currentPresences, newPresences) => { + this.channel._trigger('presence', { + event: 'join', + key, + currentPresences, + newPresences, + }); + }); + this.onLeave((key, currentPresences, leftPresences) => { + this.channel._trigger('presence', { + event: 'leave', + key, + currentPresences, + leftPresences, + }); + }); + this.onSync(() => { + this.channel._trigger('presence', { event: 'sync' }); + }); + } + /** + * Used to sync the list of presences on the server with the + * client's state. + * + * An optional `onJoin` and `onLeave` callback can be provided to + * react to changes in the client's local presences across + * disconnects and reconnects with the server. + * + * @internal + */ + static syncState(currentState, newState, onJoin, onLeave) { + const state = this.cloneDeep(currentState); + const transformedState = this.transformState(newState); + const joins = {}; + const leaves = {}; + this.map(state, (key, presences) => { + if (!transformedState[key]) { + leaves[key] = presences; + } + }); + this.map(transformedState, (key, newPresences) => { + const currentPresences = state[key]; + if (currentPresences) { + const newPresenceRefs = newPresences.map((m) => m.presence_ref); + const curPresenceRefs = currentPresences.map((m) => m.presence_ref); + const joinedPresences = newPresences.filter((m) => curPresenceRefs.indexOf(m.presence_ref) < 0); + const leftPresences = currentPresences.filter((m) => newPresenceRefs.indexOf(m.presence_ref) < 0); + if (joinedPresences.length > 0) { + joins[key] = joinedPresences; + } + if (leftPresences.length > 0) { + leaves[key] = leftPresences; + } + } + else { + joins[key] = newPresences; + } + }); + return this.syncDiff(state, { joins, leaves }, onJoin, onLeave); + } + /** + * Used to sync a diff of presence join and leave events from the + * server, as they happen. + * + * Like `syncState`, `syncDiff` accepts optional `onJoin` and + * `onLeave` callbacks to react to a user joining or leaving from a + * device. + * + * @internal + */ + static syncDiff(state, diff, onJoin, onLeave) { + const { joins, leaves } = { + joins: this.transformState(diff.joins), + leaves: this.transformState(diff.leaves), + }; + if (!onJoin) { + onJoin = () => { }; + } + if (!onLeave) { + onLeave = () => { }; + } + this.map(joins, (key, newPresences) => { + var _a; + const currentPresences = (_a = state[key]) !== null && _a !== void 0 ? _a : []; + state[key] = this.cloneDeep(newPresences); + if (currentPresences.length > 0) { + const joinedPresenceRefs = state[key].map((m) => m.presence_ref); + const curPresences = currentPresences.filter((m) => joinedPresenceRefs.indexOf(m.presence_ref) < 0); + state[key].unshift(...curPresences); + } + onJoin(key, currentPresences, newPresences); + }); + this.map(leaves, (key, leftPresences) => { + let currentPresences = state[key]; + if (!currentPresences) + return; + const presenceRefsToRemove = leftPresences.map((m) => m.presence_ref); + currentPresences = currentPresences.filter((m) => presenceRefsToRemove.indexOf(m.presence_ref) < 0); + state[key] = currentPresences; + onLeave(key, currentPresences, leftPresences); + if (currentPresences.length === 0) + delete state[key]; + }); + return state; + } + /** @internal */ + static map(obj, func) { + return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key])); + } + /** + * Remove 'metas' key + * Change 'phx_ref' to 'presence_ref' + * Remove 'phx_ref' and 'phx_ref_prev' + * + * @example + * // returns { + * abc123: [ + * { presence_ref: '2', user_id: 1 }, + * { presence_ref: '3', user_id: 2 } + * ] + * } + * RealtimePresence.transformState({ + * abc123: { + * metas: [ + * { phx_ref: '2', phx_ref_prev: '1' user_id: 1 }, + * { phx_ref: '3', user_id: 2 } + * ] + * } + * }) + * + * @internal + */ + static transformState(state) { + state = this.cloneDeep(state); + return Object.getOwnPropertyNames(state).reduce((newState, key) => { + const presences = state[key]; + if ('metas' in presences) { + newState[key] = presences.metas.map((presence) => { + presence['presence_ref'] = presence['phx_ref']; + delete presence['phx_ref']; + delete presence['phx_ref_prev']; + return presence; + }); + } + else { + newState[key] = presences; + } + return newState; + }, {}); + } + /** @internal */ + static cloneDeep(obj) { + return JSON.parse(JSON.stringify(obj)); + } + /** @internal */ + onJoin(callback) { + this.caller.onJoin = callback; + } + /** @internal */ + onLeave(callback) { + this.caller.onLeave = callback; + } + /** @internal */ + onSync(callback) { + this.caller.onSync = callback; + } + /** @internal */ + inPendingSyncState() { + return !this.joinRef || this.joinRef !== this.channel._joinRef(); + } +} +//# sourceMappingURL=RealtimePresence.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.js.map b/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.js.map new file mode 100644 index 0000000..54d647f --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/RealtimePresence.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RealtimePresence.js","sourceRoot":"","sources":["../../src/RealtimePresence.ts"],"names":[],"mappings":"AAAA;;;EAGE;AA+BF,MAAM,CAAN,IAAY,+BAIX;AAJD,WAAY,+BAA+B;IACzC,gDAAa,CAAA;IACb,gDAAa,CAAA;IACb,kDAAe,CAAA;AACjB,CAAC,EAJW,+BAA+B,KAA/B,+BAA+B,QAI1C;AAwBD,MAAM,CAAC,OAAO,OAAO,gBAAgB;IAcnC;;;;;;OAMG;IACH,YAAmB,OAAwB,EAAE,IAAmB;QAA7C,YAAO,GAAP,OAAO,CAAiB;QApB3C,UAAK,GAA0B,EAAE,CAAA;QACjC,iBAAY,GAAsB,EAAE,CAAA;QACpC,YAAO,GAAkB,IAAI,CAAA;QAC7B,WAAM,GAIF;YACF,MAAM,EAAE,GAAG,EAAE,GAAE,CAAC;YAChB,OAAO,EAAE,GAAG,EAAE,GAAE,CAAC;YACjB,MAAM,EAAE,GAAG,EAAE,GAAE,CAAC;SACjB,CAAA;QAUC,MAAM,MAAM,GAAG,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,KAAI;YAC7B,KAAK,EAAE,gBAAgB;YACvB,IAAI,EAAE,eAAe;SACtB,CAAA;QAED,IAAI,CAAC,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CAAC,cAAc,CAAC,CAAA;oBAE/B,OAAO,QAAQ,CAAA;gBACjB,CAAC,CAAe,CAAA;aACjB;iBAAM;gBACL,QAAQ,CAAC,GAAG,CAAC,GAAG,SAAS,CAAA;aAC1B;YAED,OAAO,QAAQ,CAAA;QACjB,CAAC,EAAE,EAA2B,CAAC,CAAA;IACjC,CAAC;IAED,gBAAgB;IACR,MAAM,CAAC,SAAS,CAAC,GAA2B;QAClD,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAA;IACxC,CAAC;IAED,gBAAgB;IACR,MAAM,CAAC,QAAgC;QAC7C,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,QAAQ,CAAA;IAC/B,CAAC;IAED,gBAAgB;IACR,OAAO,CAAC,QAAiC;QAC/C,IAAI,CAAC,MAAM,CAAC,OAAO,GAAG,QAAQ,CAAA;IAChC,CAAC;IAED,gBAAgB;IACR,MAAM,CAAC,QAAoB;QACjC,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,QAAQ,CAAA;IAC/B,CAAC;IAED,gBAAgB;IACR,kBAAkB;QACxB,OAAO,CAAC,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,KAAK,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAA;IAClE,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/index.d.ts b/node_modules/@supabase/realtime-js/dist/module/index.d.ts new file mode 100644 index 0000000..0aaf49d --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/index.d.ts @@ -0,0 +1,5 @@ +import RealtimeClient, { RealtimeClientOptions, RealtimeMessage, RealtimeRemoveChannelResponse } from './RealtimeClient'; +import RealtimeChannel, { RealtimeChannelOptions, RealtimeChannelSendResponse, RealtimePostgresChangesFilter, RealtimePostgresChangesPayload, RealtimePostgresInsertPayload, RealtimePostgresUpdatePayload, RealtimePostgresDeletePayload, REALTIME_LISTEN_TYPES, REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, REALTIME_SUBSCRIBE_STATES } from './RealtimeChannel'; +import RealtimePresence, { RealtimePresenceState, RealtimePresenceJoinPayload, RealtimePresenceLeavePayload, REALTIME_PRESENCE_LISTEN_EVENTS } from './RealtimePresence'; +export { RealtimePresence, RealtimeChannel, RealtimeChannelOptions, RealtimeChannelSendResponse, RealtimeClient, RealtimeClientOptions, RealtimeMessage, RealtimePostgresChangesFilter, RealtimePostgresChangesPayload, RealtimePostgresInsertPayload, RealtimePostgresUpdatePayload, RealtimePostgresDeletePayload, RealtimePresenceJoinPayload, RealtimePresenceLeavePayload, RealtimePresenceState, RealtimeRemoveChannelResponse, REALTIME_LISTEN_TYPES, REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, REALTIME_PRESENCE_LISTEN_EVENTS, REALTIME_SUBSCRIBE_STATES, }; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/index.d.ts.map b/node_modules/@supabase/realtime-js/dist/module/index.d.ts.map new file mode 100644 index 0000000..7b78323 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,EAAE,EACrB,qBAAqB,EACrB,eAAe,EACf,6BAA6B,EAC9B,MAAM,kBAAkB,CAAA;AACzB,OAAO,eAAe,EAAE,EACtB,sBAAsB,EACtB,2BAA2B,EAC3B,6BAA6B,EAC7B,8BAA8B,EAC9B,6BAA6B,EAC7B,6BAA6B,EAC7B,6BAA6B,EAC7B,qBAAqB,EACrB,sCAAsC,EACtC,yBAAyB,EAC1B,MAAM,mBAAmB,CAAA;AAC1B,OAAO,gBAAgB,EAAE,EACvB,qBAAqB,EACrB,2BAA2B,EAC3B,4BAA4B,EAC5B,+BAA+B,EAChC,MAAM,oBAAoB,CAAA;AAE3B,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,sBAAsB,EACtB,2BAA2B,EAC3B,cAAc,EACd,qBAAqB,EACrB,eAAe,EACf,6BAA6B,EAC7B,8BAA8B,EAC9B,6BAA6B,EAC7B,6BAA6B,EAC7B,6BAA6B,EAC7B,2BAA2B,EAC3B,4BAA4B,EAC5B,qBAAqB,EACrB,6BAA6B,EAC7B,qBAAqB,EACrB,sCAAsC,EACtC,+BAA+B,EAC/B,yBAAyB,GAC1B,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/index.js b/node_modules/@supabase/realtime-js/dist/module/index.js new file mode 100644 index 0000000..9698dd9 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/index.js @@ -0,0 +1,5 @@ +import RealtimeClient from './RealtimeClient'; +import RealtimeChannel, { REALTIME_LISTEN_TYPES, REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, REALTIME_SUBSCRIBE_STATES, } from './RealtimeChannel'; +import RealtimePresence, { REALTIME_PRESENCE_LISTEN_EVENTS, } from './RealtimePresence'; +export { RealtimePresence, RealtimeChannel, RealtimeClient, REALTIME_LISTEN_TYPES, REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, REALTIME_PRESENCE_LISTEN_EVENTS, REALTIME_SUBSCRIBE_STATES, }; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/index.js.map b/node_modules/@supabase/realtime-js/dist/module/index.js.map new file mode 100644 index 0000000..3669d86 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAIN,MAAM,kBAAkB,CAAA;AACzB,OAAO,eAAe,EAAE,EAQtB,qBAAqB,EACrB,sCAAsC,EACtC,yBAAyB,GAC1B,MAAM,mBAAmB,CAAA;AAC1B,OAAO,gBAAgB,EAAE,EAIvB,+BAA+B,GAChC,MAAM,oBAAoB,CAAA;AAE3B,OAAO,EACL,gBAAgB,EAChB,eAAe,EAGf,cAAc,EAYd,qBAAqB,EACrB,sCAAsC,EACtC,+BAA+B,EAC/B,yBAAyB,GAC1B,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/constants.d.ts b/node_modules/@supabase/realtime-js/dist/module/lib/constants.d.ts new file mode 100644 index 0000000..8a17e42 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/constants.d.ts @@ -0,0 +1,37 @@ +export declare const DEFAULT_HEADERS: { + 'X-Client-Info': string; +}; +export declare const VSN: string; +export declare const DEFAULT_TIMEOUT = 10000; +export declare const WS_CLOSE_NORMAL = 1000; +export declare enum SOCKET_STATES { + connecting = 0, + open = 1, + closing = 2, + closed = 3 +} +export declare enum CHANNEL_STATES { + closed = "closed", + errored = "errored", + joined = "joined", + joining = "joining", + leaving = "leaving" +} +export declare enum CHANNEL_EVENTS { + close = "phx_close", + error = "phx_error", + join = "phx_join", + reply = "phx_reply", + leave = "phx_leave", + access_token = "access_token" +} +export declare enum TRANSPORTS { + websocket = "websocket" +} +export declare enum CONNECTION_STATE { + Connecting = "connecting", + Open = "open", + Closing = "closing", + Closed = "closed" +} +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/constants.d.ts.map b/node_modules/@supabase/realtime-js/dist/module/lib/constants.d.ts.map new file mode 100644 index 0000000..8f7b275 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe;;CAAgD,CAAA;AAE5E,eAAO,MAAM,GAAG,EAAE,MAAgB,CAAA;AAElC,eAAO,MAAM,eAAe,QAAQ,CAAA;AAEpC,eAAO,MAAM,eAAe,OAAO,CAAA;AAEnC,oBAAY,aAAa;IACvB,UAAU,IAAI;IACd,IAAI,IAAI;IACR,OAAO,IAAI;IACX,MAAM,IAAI;CACX;AAED,oBAAY,cAAc;IACxB,MAAM,WAAW;IACjB,OAAO,YAAY;IACnB,MAAM,WAAW;IACjB,OAAO,YAAY;IACnB,OAAO,YAAY;CACpB;AAED,oBAAY,cAAc;IACxB,KAAK,cAAc;IACnB,KAAK,cAAc;IACnB,IAAI,aAAa;IACjB,KAAK,cAAc;IACnB,KAAK,cAAc;IACnB,YAAY,iBAAiB;CAC9B;AAED,oBAAY,UAAU;IACpB,SAAS,cAAc;CACxB;AAED,oBAAY,gBAAgB;IAC1B,UAAU,eAAe;IACzB,IAAI,SAAS;IACb,OAAO,YAAY;IACnB,MAAM,WAAW;CAClB"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/constants.js b/node_modules/@supabase/realtime-js/dist/module/lib/constants.js new file mode 100644 index 0000000..19a6c41 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/constants.js @@ -0,0 +1,41 @@ +import { version } from './version'; +export const DEFAULT_HEADERS = { 'X-Client-Info': `realtime-js/${version}` }; +export const VSN = '1.0.0'; +export const DEFAULT_TIMEOUT = 10000; +export const WS_CLOSE_NORMAL = 1000; +export var SOCKET_STATES; +(function (SOCKET_STATES) { + SOCKET_STATES[SOCKET_STATES["connecting"] = 0] = "connecting"; + SOCKET_STATES[SOCKET_STATES["open"] = 1] = "open"; + SOCKET_STATES[SOCKET_STATES["closing"] = 2] = "closing"; + SOCKET_STATES[SOCKET_STATES["closed"] = 3] = "closed"; +})(SOCKET_STATES || (SOCKET_STATES = {})); +export var CHANNEL_STATES; +(function (CHANNEL_STATES) { + CHANNEL_STATES["closed"] = "closed"; + CHANNEL_STATES["errored"] = "errored"; + CHANNEL_STATES["joined"] = "joined"; + CHANNEL_STATES["joining"] = "joining"; + CHANNEL_STATES["leaving"] = "leaving"; +})(CHANNEL_STATES || (CHANNEL_STATES = {})); +export var CHANNEL_EVENTS; +(function (CHANNEL_EVENTS) { + CHANNEL_EVENTS["close"] = "phx_close"; + CHANNEL_EVENTS["error"] = "phx_error"; + CHANNEL_EVENTS["join"] = "phx_join"; + CHANNEL_EVENTS["reply"] = "phx_reply"; + CHANNEL_EVENTS["leave"] = "phx_leave"; + CHANNEL_EVENTS["access_token"] = "access_token"; +})(CHANNEL_EVENTS || (CHANNEL_EVENTS = {})); +export var TRANSPORTS; +(function (TRANSPORTS) { + TRANSPORTS["websocket"] = "websocket"; +})(TRANSPORTS || (TRANSPORTS = {})); +export var CONNECTION_STATE; +(function (CONNECTION_STATE) { + CONNECTION_STATE["Connecting"] = "connecting"; + CONNECTION_STATE["Open"] = "open"; + CONNECTION_STATE["Closing"] = "closing"; + CONNECTION_STATE["Closed"] = "closed"; +})(CONNECTION_STATE || (CONNECTION_STATE = {})); +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/constants.js.map b/node_modules/@supabase/realtime-js/dist/module/lib/constants.js.map new file mode 100644 index 0000000..811e453 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAEnC,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,eAAe,EAAE,eAAe,OAAO,EAAE,EAAE,CAAA;AAE5E,MAAM,CAAC,MAAM,GAAG,GAAW,OAAO,CAAA;AAElC,MAAM,CAAC,MAAM,eAAe,GAAG,KAAK,CAAA;AAEpC,MAAM,CAAC,MAAM,eAAe,GAAG,IAAI,CAAA;AAEnC,MAAM,CAAN,IAAY,aAKX;AALD,WAAY,aAAa;IACvB,6DAAc,CAAA;IACd,iDAAQ,CAAA;IACR,uDAAW,CAAA;IACX,qDAAU,CAAA;AACZ,CAAC,EALW,aAAa,KAAb,aAAa,QAKxB;AAED,MAAM,CAAN,IAAY,cAMX;AAND,WAAY,cAAc;IACxB,mCAAiB,CAAA;IACjB,qCAAmB,CAAA;IACnB,mCAAiB,CAAA;IACjB,qCAAmB,CAAA;IACnB,qCAAmB,CAAA;AACrB,CAAC,EANW,cAAc,KAAd,cAAc,QAMzB;AAED,MAAM,CAAN,IAAY,cAOX;AAPD,WAAY,cAAc;IACxB,qCAAmB,CAAA;IACnB,qCAAmB,CAAA;IACnB,mCAAiB,CAAA;IACjB,qCAAmB,CAAA;IACnB,qCAAmB,CAAA;IACnB,+CAA6B,CAAA;AAC/B,CAAC,EAPW,cAAc,KAAd,cAAc,QAOzB;AAED,MAAM,CAAN,IAAY,UAEX;AAFD,WAAY,UAAU;IACpB,qCAAuB,CAAA;AACzB,CAAC,EAFW,UAAU,KAAV,UAAU,QAErB;AAED,MAAM,CAAN,IAAY,gBAKX;AALD,WAAY,gBAAgB;IAC1B,6CAAyB,CAAA;IACzB,iCAAa,CAAA;IACb,uCAAmB,CAAA;IACnB,qCAAiB,CAAA;AACnB,CAAC,EALW,gBAAgB,KAAhB,gBAAgB,QAK3B"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/push.d.ts b/node_modules/@supabase/realtime-js/dist/module/lib/push.d.ts new file mode 100644 index 0000000..16d954c --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/push.d.ts @@ -0,0 +1,49 @@ +import type RealtimeChannel from '../RealtimeChannel'; +export default class Push { + channel: RealtimeChannel; + event: string; + payload: { + [key: string]: any; + }; + timeout: number; + sent: boolean; + timeoutTimer: number | undefined; + ref: string; + receivedResp: { + status: string; + response: { + [key: string]: any; + }; + } | null; + recHooks: { + status: string; + callback: Function; + }[]; + refEvent: string | null; + rateLimited: boolean; + /** + * Initializes the Push + * + * @param channel The Channel + * @param event The event, for example `"phx_join"` + * @param payload The payload, for example `{user_id: 123}` + * @param timeout The push timeout in milliseconds + */ + constructor(channel: RealtimeChannel, event: string, payload?: { + [key: string]: any; + }, timeout?: number); + resend(timeout: number): void; + send(): void; + updatePayload(payload: { + [key: string]: any; + }): void; + receive(status: string, callback: Function): this; + startTimeout(): void; + trigger(status: string, response: any): void; + destroy(): void; + private _cancelRefEvent; + private _cancelTimeout; + private _matchReceive; + private _hasReceived; +} +//# sourceMappingURL=push.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/push.d.ts.map b/node_modules/@supabase/realtime-js/dist/module/lib/push.d.ts.map new file mode 100644 index 0000000..c4174d5 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/push.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"push.d.ts","sourceRoot":"","sources":["../../../src/lib/push.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,eAAe,MAAM,oBAAoB,CAAA;AAErD,MAAM,CAAC,OAAO,OAAO,IAAI;IAwBd,OAAO,EAAE,eAAe;IACxB,KAAK,EAAE,MAAM;IACb,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE;IAC/B,OAAO,EAAE,MAAM;IA1BxB,IAAI,EAAE,OAAO,CAAQ;IACrB,YAAY,EAAE,MAAM,GAAG,SAAS,CAAY;IAC5C,GAAG,EAAE,MAAM,CAAK;IAChB,YAAY,EAAE;QACZ,MAAM,EAAE,MAAM,CAAA;QACd,QAAQ,EAAE;YAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;SAAE,CAAA;KACjC,GAAG,IAAI,CAAO;IACf,QAAQ,EAAE;QACR,MAAM,EAAE,MAAM,CAAA;QACd,QAAQ,EAAE,QAAQ,CAAA;KACnB,EAAE,CAAK;IACR,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAO;IAC9B,WAAW,EAAE,OAAO,CAAQ;IAE5B;;;;;;;OAOG;gBAEM,OAAO,EAAE,eAAe,EACxB,KAAK,EAAE,MAAM,EACb,OAAO,GAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAO,EACpC,OAAO,GAAE,MAAwB;IAG1C,MAAM,CAAC,OAAO,EAAE,MAAM;IAUtB,IAAI;IAkBJ,aAAa,CAAC,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,GAAG,IAAI;IAIpD,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ;IAS1C,YAAY;IAqBZ,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG;IAKrC,OAAO;IAKP,OAAO,CAAC,eAAe;IAQvB,OAAO,CAAC,cAAc;IAKtB,OAAO,CAAC,aAAa;IAYrB,OAAO,CAAC,YAAY;CAGrB"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/push.js b/node_modules/@supabase/realtime-js/dist/module/lib/push.js new file mode 100644 index 0000000..695ad2e --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/push.js @@ -0,0 +1,105 @@ +import { DEFAULT_TIMEOUT } from '../lib/constants'; +export default class Push { + /** + * Initializes the Push + * + * @param channel The Channel + * @param event The event, for example `"phx_join"` + * @param payload The payload, for example `{user_id: 123}` + * @param timeout The push timeout in milliseconds + */ + constructor(channel, event, payload = {}, timeout = DEFAULT_TIMEOUT) { + this.channel = channel; + this.event = event; + this.payload = payload; + this.timeout = timeout; + this.sent = false; + this.timeoutTimer = undefined; + this.ref = ''; + this.receivedResp = null; + this.recHooks = []; + this.refEvent = null; + this.rateLimited = false; + } + resend(timeout) { + this.timeout = timeout; + this._cancelRefEvent(); + this.ref = ''; + this.refEvent = null; + this.receivedResp = null; + this.sent = false; + this.send(); + } + send() { + if (this._hasReceived('timeout')) { + return; + } + this.startTimeout(); + this.sent = true; + const status = this.channel.socket.push({ + topic: this.channel.topic, + event: this.event, + payload: this.payload, + ref: this.ref, + join_ref: this.channel._joinRef(), + }); + if (status === 'rate limited') { + this.rateLimited = true; + } + } + updatePayload(payload) { + this.payload = Object.assign(Object.assign({}, this.payload), payload); + } + receive(status, callback) { + var _a; + if (this._hasReceived(status)) { + callback((_a = this.receivedResp) === null || _a === void 0 ? void 0 : _a.response); + } + this.recHooks.push({ status, callback }); + return this; + } + startTimeout() { + if (this.timeoutTimer) { + return; + } + this.ref = this.channel.socket._makeRef(); + this.refEvent = this.channel._replyEventName(this.ref); + const callback = (payload) => { + this._cancelRefEvent(); + this._cancelTimeout(); + this.receivedResp = payload; + this._matchReceive(payload); + }; + this.channel._on(this.refEvent, {}, callback); + this.timeoutTimer = setTimeout(() => { + this.trigger('timeout', {}); + }, this.timeout); + } + trigger(status, response) { + if (this.refEvent) + this.channel._trigger(this.refEvent, { status, response }); + } + destroy() { + this._cancelRefEvent(); + this._cancelTimeout(); + } + _cancelRefEvent() { + if (!this.refEvent) { + return; + } + this.channel._off(this.refEvent, {}); + } + _cancelTimeout() { + clearTimeout(this.timeoutTimer); + this.timeoutTimer = undefined; + } + _matchReceive({ status, response, }) { + this.recHooks + .filter((h) => h.status === status) + .forEach((h) => h.callback(response)); + } + _hasReceived(status) { + return this.receivedResp && this.receivedResp.status === status; + } +} +//# sourceMappingURL=push.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/push.js.map b/node_modules/@supabase/realtime-js/dist/module/lib/push.js.map new file mode 100644 index 0000000..f0c38b6 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/push.js.map @@ -0,0 +1 @@ +{"version":3,"file":"push.js","sourceRoot":"","sources":["../../../src/lib/push.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAGlD,MAAM,CAAC,OAAO,OAAO,IAAI;IAevB;;;;;;;OAOG;IACH,YACS,OAAwB,EACxB,KAAa,EACb,UAAkC,EAAE,EACpC,UAAkB,eAAe;QAHjC,YAAO,GAAP,OAAO,CAAiB;QACxB,UAAK,GAAL,K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AE,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAA;IAC9D,CAAC;IAED,OAAO;QACL,IAAI,CAAC,eAAe,EAAE,CAAA;QACtB,IAAI,CAAC,cAAc,EAAE,CAAA;IACvB,CAAC;IAEO,eAAe;QACrB,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE;YAClB,OAAM;SACP;QAED,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAA;IACtC,CAAC;IAEO,cAAc;QACpB,YAAY,CAAC,IAAI,CAAC,YAAY,CAAC,CAAA;QAC/B,IAAI,CAAC,YAAY,GAAG,SAAS,CAAA;IAC/B,CAAC;IAEO,aAAa,CAAC,EACpB,MAAM,EACN,QAAQ,GAIT;QACC,IAAI,CAAC,QAAQ;aACV,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC;aAClC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAA;IACzC,CAAC;IAEO,YAAY,CAAC,MAAc;QACjC,OAAO,IAAI,CAAC,YAAY,IAAI,IAAI,CAAC,YAAY,CAAC,MAAM,KAAK,MAAM,CAAA;IACjE,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/serializer.d.ts b/node_modules/@supabase/realtime-js/dist/module/lib/serializer.d.ts new file mode 100644 index 0000000..2e86807 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/serializer.d.ts @@ -0,0 +1,7 @@ +export default class Serializer { + HEADER_LENGTH: number; + decode(rawPayload: ArrayBuffer | string, callback: Function): any; + private _binaryDecode; + private _decodeBroadcast; +} +//# sourceMappingURL=serializer.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/serializer.d.ts.map b/node_modules/@supabase/realtime-js/dist/module/lib/serializer.d.ts.map new file mode 100644 index 0000000..3a7f65f --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/serializer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"serializer.d.ts","sourceRoot":"","sources":["../../../src/lib/serializer.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,OAAO,OAAO,UAAU;IAC7B,aAAa,SAAI;IAEjB,MAAM,CAAC,UAAU,EAAE,WAAW,GAAG,MAAM,EAAE,QAAQ,EAAE,QAAQ;IAY3D,OAAO,CAAC,aAAa;IAOrB,OAAO,CAAC,gBAAgB;CAuBzB"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/serializer.js b/node_modules/@supabase/realtime-js/dist/module/lib/serializer.js new file mode 100644 index 0000000..f816d40 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/serializer.js @@ -0,0 +1,33 @@ +// This file draws heavily from https://github.com/phoenixframework/phoenix/commit/cf098e9cf7a44ee6479d31d911a97d3c7430c6fe +// License: https://github.com/phoenixframework/phoenix/blob/master/LICENSE.md +export default class Serializer { + constructor() { + this.HEADER_LENGTH = 1; + } + decode(rawPayload, callback) { + if (rawPayload.constructor === ArrayBuffer) { + return callback(this._binaryDecode(rawPayload)); + } + if (typeof rawPayload === 'string') { + return callback(JSON.parse(rawPayload)); + } + return callback({}); + } + _binaryDecode(buffer) { + const view = new DataView(buffer); + const decoder = new TextDecoder(); + return this._decodeBroadcast(buffer, view, decoder); + } + _decodeBroadcast(buffer, view, decoder) { + const topicSize = view.getUint8(1); + const eventSize = view.getUint8(2); + let offset = this.HEADER_LENGTH + 2; + const topic = decoder.decode(buffer.slice(offset, offset + topicSize)); + offset = offset + topicSize; + const event = decoder.decode(buffer.slice(offset, offset + eventSize)); + offset = offset + eventSize; + const data = JSON.parse(decoder.decode(buffer.slice(offset, buffer.byteLength))); + return { ref: null, topic: topic, event: event, payload: data }; + } +} +//# sourceMappingURL=serializer.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/serializer.js.map b/node_modules/@supabase/realtime-js/dist/module/lib/serializer.js.map new file mode 100644 index 0000000..3a47282 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/serializer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"serializer.js","sourceRoot":"","sources":["../../../src/lib/serializer.ts"],"names":[],"mappings":"AAAA,2HAA2H;AAC3H,8EAA8E;AAE9E,MAAM,CAAC,OAAO,OAAO,UAAU;IAA/B;QACE,kBAAa,GAAG,CAAC,CAAA;IA4CnB,CAAC;IA1CC,MAAM,CAAC,UAAgC,EAAE,QAAkB;QACzD,IAAI,UAAU,CAAC,WAAW,KAAK,WAAW,EAAE;YAC1C,OAAO,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC,CAAA;SAChD;QAED,IAAI,OAAO,UAAU,KAAK,QAAQ,EAAE;YAClC,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAA;SACxC;QAED,OAAO,QAAQ,CAAC,EAAE,CAAC,CAAA;IACrB,CAAC;IAEO,aAAa,CAAC,MAAmB;QACvC,MAAM,IAAI,GAAG,IAAI,QAAQ,CAAC,MAAM,CAAC,CAAA;QACjC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAA;QAEjC,OAAO,IAAI,CAAC,gBAAgB,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,CAAA;IACrD,CAAC;IAEO,gBAAgB,CACtB,MAAmB,EACnB,IAAc,EACd,OAAoB;QAOpB,MAAM,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAA;QAClC,MAAM,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAA;QAClC,IAAI,MAAM,GAAG,IAAI,CAAC,aAAa,GAAG,CAAC,CAAA;QACnC,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAA;QACtE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAA;QAC3B,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAA;QACtE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAA;QAC3B,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CACrB,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC,CACxD,CAAA;QAED,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,CAAA;IACjE,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/timer.d.ts b/node_modules/@supabase/realtime-js/dist/module/lib/timer.d.ts new file mode 100644 index 0000000..d5df4a6 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/timer.d.ts @@ -0,0 +1,22 @@ +/** + * Creates a timer that accepts a `timerCalc` function to perform calculated timeout retries, such as exponential backoff. + * + * @example + * let reconnectTimer = new Timer(() => this.connect(), function(tries){ + * return [1000, 5000, 10000][tries - 1] || 10000 + * }) + * reconnectTimer.scheduleTimeout() // fires after 1000 + * reconnectTimer.scheduleTimeout() // fires after 5000 + * reconnectTimer.reset() + * reconnectTimer.scheduleTimeout() // fires after 1000 + */ +export default class Timer { + callback: Function; + timerCalc: Function; + timer: number | undefined; + tries: number; + constructor(callback: Function, timerCalc: Function); + reset(): void; + scheduleTimeout(): void; +} +//# sourceMappingURL=timer.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/timer.d.ts.map b/node_modules/@supabase/realtime-js/dist/module/lib/timer.d.ts.map new file mode 100644 index 0000000..35ca72e --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/timer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"timer.d.ts","sourceRoot":"","sources":["../../../src/lib/timer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,OAAO,OAAO,KAAK;IAIL,QAAQ,EAAE,QAAQ;IAAS,SAAS,EAAE,QAAQ;IAHjE,KAAK,EAAE,MAAM,GAAG,SAAS,CAAY;IACrC,KAAK,EAAE,MAAM,CAAI;gBAEE,QAAQ,EAAE,QAAQ,EAAS,SAAS,EAAE,QAAQ;IAKjE,KAAK;IAML,eAAe;CAQhB"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/timer.js b/node_modules/@supabase/realtime-js/dist/module/lib/timer.js new file mode 100644 index 0000000..e0921f0 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/timer.js @@ -0,0 +1,35 @@ +/** + * Creates a timer that accepts a `timerCalc` function to perform calculated timeout retries, such as exponential backoff. + * + * @example + * let reconnectTimer = new Timer(() => this.connect(), function(tries){ + * return [1000, 5000, 10000][tries - 1] || 10000 + * }) + * reconnectTimer.scheduleTimeout() // fires after 1000 + * reconnectTimer.scheduleTimeout() // fires after 5000 + * reconnectTimer.reset() + * reconnectTimer.scheduleTimeout() // fires after 1000 + */ +export default class Timer { + constructor(callback, timerCalc) { + this.callback = callback; + this.timerCalc = timerCalc; + this.timer = undefined; + this.tries = 0; + this.callback = callback; + this.timerCalc = timerCalc; + } + reset() { + this.tries = 0; + clearTimeout(this.timer); + } + // Cancels any previous scheduleTimeout and schedules callback + scheduleTimeout() { + clearTimeout(this.timer); + this.timer = setTimeout(() => { + this.tries = this.tries + 1; + this.callback(); + }, this.timerCalc(this.tries + 1)); + } +} +//# sourceMappingURL=timer.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/timer.js.map b/node_modules/@supabase/realtime-js/dist/module/lib/timer.js.map new file mode 100644 index 0000000..bab3121 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/timer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"timer.js","sourceRoot":"","sources":["../../../src/lib/timer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,OAAO,OAAO,KAAK;IAIxB,YAAmB,QAAkB,EAAS,SAAmB;QAA9C,aAAQ,GAAR,QAAQ,CAAU;QAAS,cAAS,GAAT,SAAS,CAAU;QAHjE,UAAK,GAAuB,SAAS,CAAA;QACrC,UAAK,GAAW,CAAC,CAAA;QAGf,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAA;IAC5B,CAAC;IAED,KAAK;QACH,IAAI,CAAC,KAAK,GAAG,CAAC,CAAA;QACd,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;IAC1B,CAAC;IAED,8DAA8D;IAC9D,eAAe;QACb,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QAExB,IAAI,CAAC,KAAK,GAAQ,UAAU,CAAC,GAAG,EAAE;YAChC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,GAAG,CAAC,CAAA;YAC3B,IAAI,CAAC,QAAQ,EAAE,CAAA;QACjB,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,CAAA;IACpC,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/transformers.d.ts b/node_modules/@supabase/realtime-js/dist/module/lib/transformers.d.ts new file mode 100644 index 0000000..992cdfa --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/transformers.d.ts @@ -0,0 +1,108 @@ +/** + * Helpers to convert the change Payload into native JS types. + */ +export declare enum PostgresTypes { + abstime = "abstime", + bool = "bool", + date = "date", + daterange = "daterange", + float4 = "float4", + float8 = "float8", + int2 = "int2", + int4 = "int4", + int4range = "int4range", + int8 = "int8", + int8range = "int8range", + json = "json", + jsonb = "jsonb", + money = "money", + numeric = "numeric", + oid = "oid", + reltime = "reltime", + text = "text", + time = "time", + timestamp = "timestamp", + timestamptz = "timestamptz", + timetz = "timetz", + tsrange = "tsrange", + tstzrange = "tstzrange" +} +declare type Columns = { + name: string; + type: string; + flags?: string[]; + type_modifier?: number; +}[]; +declare type BaseValue = null | string | number | boolean; +declare type RecordValue = BaseValue | BaseValue[]; +declare type Record = { + [key: string]: RecordValue; +}; +/** + * Takes an array of columns and an object of string values then converts each string value + * to its mapped type. + * + * @param {{name: String, type: String}[]} columns + * @param {Object} record + * @param {Object} options The map of various options that can be applied to the mapper + * @param {Array} options.skipTypes The array of types that should not be converted + * + * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {}) + * //=>{ first_name: 'Paul', age: 33 } + */ +export declare const convertChangeData: (columns: Columns, record: Record, options?: { + skipTypes?: string[]; +}) => Record; +/** + * Converts the value of an individual column. + * + * @param {String} columnName The column that you want to convert + * @param {{name: String, type: String}[]} columns All of the columns + * @param {Object} record The map of string values + * @param {Array} skipTypes An array of types that should not be converted + * @return {object} Useless information + * + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, []) + * //=> 33 + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4']) + * //=> "33" + */ +export declare const convertColumn: (columnName: string, columns: Columns, record: Record, skipTypes: string[]) => RecordValue; +/** + * If the value of the cell is `null`, returns null. + * Otherwise converts the string value to the correct type. + * @param {String} type A postgres column type + * @param {String} value The cell value + * + * @example convertCell('bool', 't') + * //=> true + * @example convertCell('int8', '10') + * //=> 10 + * @example convertCell('_int4', '{1,2,3,4}') + * //=> [1,2,3,4] + */ +export declare const convertCell: (type: string, value: RecordValue) => RecordValue; +export declare const toBoolean: (value: RecordValue) => RecordValue; +export declare const toNumber: (value: RecordValue) => RecordValue; +export declare const toJson: (value: RecordValue) => RecordValue; +/** + * Converts a Postgres Array into a native JS array + * + * @example toArray('{}', 'int4') + * //=> [] + * @example toArray('{"[2021-01-01,2021-12-31)","(2021-01-01,2021-12-32]"}', 'daterange') + * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]'] + * @example toArray([1,2,3,4], 'int4') + * //=> [1,2,3,4] + */ +export declare const toArray: (value: RecordValue, type: string) => RecordValue; +/** + * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T' + * See https://github.com/supabase/supabase/issues/18 + * + * @example toTimestampString('2019-09-10 00:00:00') + * //=> '2019-09-10T00:00:00' + */ +export declare const toTimestampString: (value: RecordValue) => RecordValue; +export {}; +//# sourceMappingURL=transformers.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/transformers.d.ts.map b/node_modules/@supabase/realtime-js/dist/module/lib/transformers.d.ts.map new file mode 100644 index 0000000..6af783a --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/transformers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transformers.d.ts","sourceRoot":"","sources":["../../../src/lib/transformers.ts"],"names":[],"mappings":"AAAA;;GAEG;AAKH,oBAAY,aAAa;IACvB,OAAO,YAAY;IACnB,IAAI,SAAS;IACb,IAAI,SAAS;IACb,SAAS,cAAc;IACvB,MAAM,WAAW;IACjB,MAAM,WAAW;IACjB,IAAI,SAAS;IACb,IAAI,SAAS;IACb,SAAS,cAAc;IACvB,IAAI,SAAS;IACb,SAAS,cAAc;IACvB,IAAI,SAAS;IACb,KAAK,UAAU;IACf,KAAK,UAAU;IACf,OAAO,YAAY;IACnB,GAAG,QAAQ;IACX,OAAO,YAAY;IACnB,IAAI,SAAS;IACb,IAAI,SAAS;IACb,SAAS,cAAc;IACvB,WAAW,gBAAgB;IAC3B,MAAM,WAAW;IACjB,OAAO,YAAY;IACnB,SAAS,cAAc;CACxB;AAED,aAAK,OAAO,GAAG;IACb,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,CAAC,EAAE,MAAM,EAAE,CAAA;IAChB,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB,EAAE,CAAA;AAEH,aAAK,SAAS,GAAG,IAAI,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAA;AACjD,aAAK,WAAW,GAAG,SAAS,GAAG,SAAS,EAAE,CAAA;AAE1C,aAAK,MAAM,GAAG;IACZ,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW,CAAA;CAC3B,CAAA;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,iBAAiB,6BAEpB,MAAM,YACL;IAAE,SAAS,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,KAChC,MAOF,CAAA;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,aAAa,eACZ,MAAM,4BAEV,MAAM,aACH,MAAM,EAAE,KAClB,WAUF,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,WAAW,SAAU,MAAM,SAAS,WAAW,KAAG,WA0C9D,CAAA;AAKD,eAAO,MAAM,SAAS,UAAW,WAAW,KAAG,WAS9C,CAAA;AACD,eAAO,MAAM,QAAQ,UAAW,WAAW,KAAG,WAQ7C,CAAA;AACD,eAAO,MAAM,MAAM,UAAW,WAAW,KAAG,WAU3C,CAAA;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,OAAO,UAAW,WAAW,QAAQ,MAAM,KAAG,WA0B1D,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,iBAAiB,UAAW,WAAW,KAAG,WAMtD,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/transformers.js b/node_modules/@supabase/realtime-js/dist/module/lib/transformers.js new file mode 100644 index 0000000..d02f8e3 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/transformers.js @@ -0,0 +1,211 @@ +/** + * Helpers to convert the change Payload into native JS types. + */ +// Adapted from epgsql (src/epgsql_binary.erl), this module licensed under +// 3-clause BSD found here: https://raw.githubusercontent.com/epgsql/epgsql/devel/LICENSE +export var PostgresTypes; +(function (PostgresTypes) { + PostgresTypes["abstime"] = "abstime"; + PostgresTypes["bool"] = "bool"; + PostgresTypes["date"] = "date"; + PostgresTypes["daterange"] = "daterange"; + PostgresTypes["float4"] = "float4"; + PostgresTypes["float8"] = "float8"; + PostgresTypes["int2"] = "int2"; + PostgresTypes["int4"] = "int4"; + PostgresTypes["int4range"] = "int4range"; + PostgresTypes["int8"] = "int8"; + PostgresTypes["int8range"] = "int8range"; + PostgresTypes["json"] = "json"; + PostgresTypes["jsonb"] = "jsonb"; + PostgresTypes["money"] = "money"; + PostgresTypes["numeric"] = "numeric"; + PostgresTypes["oid"] = "oid"; + PostgresTypes["reltime"] = "reltime"; + PostgresTypes["text"] = "text"; + PostgresTypes["time"] = "time"; + PostgresTypes["timestamp"] = "timestamp"; + PostgresTypes["timestamptz"] = "timestamptz"; + PostgresTypes["timetz"] = "timetz"; + PostgresTypes["tsrange"] = "tsrange"; + PostgresTypes["tstzrange"] = "tstzrange"; +})(PostgresTypes || (PostgresTypes = {})); +/** + * Takes an array of columns and an object of string values then converts each string value + * to its mapped type. + * + * @param {{name: String, type: String}[]} columns + * @param {Object} record + * @param {Object} options The map of various options that can be applied to the mapper + * @param {Array} options.skipTypes The array of types that should not be converted + * + * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {}) + * //=>{ first_name: 'Paul', age: 33 } + */ +export const convertChangeData = (columns, record, options = {}) => { + var _a; + const skipTypes = (_a = options.skipTypes) !== null && _a !== void 0 ? _a : []; + return Object.keys(record).reduce((acc, rec_key) => { + acc[rec_key] = convertColumn(rec_key, columns, record, skipTypes); + return acc; + }, {}); +}; +/** + * Converts the value of an individual column. + * + * @param {String} columnName The column that you want to convert + * @param {{name: String, type: String}[]} columns All of the columns + * @param {Object} record The map of string values + * @param {Array} skipTypes An array of types that should not be converted + * @return {object} Useless information + * + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, []) + * //=> 33 + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4']) + * //=> "33" + */ +export const convertColumn = (columnName, columns, record, skipTypes) => { + const column = columns.find((x) => x.name === columnName); + const colType = column === null || column === void 0 ? void 0 : column.type; + const value = record[columnName]; + if (colType && !skipTypes.includes(colType)) { + return convertCell(colType, value); + } + return noop(value); +}; +/** + * If the value of the cell is `null`, returns null. + * Otherwise converts the string value to the correct type. + * @param {String} type A postgres column type + * @param {String} value The cell value + * + * @example convertCell('bool', 't') + * //=> true + * @example convertCell('int8', '10') + * //=> 10 + * @example convertCell('_int4', '{1,2,3,4}') + * //=> [1,2,3,4] + */ +export const convertCell = (type, value) => { + // if data type is an array + if (type.charAt(0) === '_') { + const dataType = type.slice(1, type.length); + return toArray(value, dataType); + } + // If not null, convert to correct type. + switch (type) { + case PostgresTypes.bool: + return toBoolean(value); + case PostgresTypes.float4: + case PostgresTypes.float8: + case PostgresTypes.int2: + case PostgresTypes.int4: + case PostgresTypes.int8: + case PostgresTypes.numeric: + case PostgresTypes.oid: + return toNumber(value); + case PostgresTypes.json: + case PostgresTypes.jsonb: + return toJson(value); + case PostgresTypes.timestamp: + return toTimestampString(value); // Format to be consistent with PostgREST + case PostgresTypes.abstime: // To allow users to cast it based on Timezone + case PostgresTypes.date: // To allow users to cast it based on Timezone + case PostgresTypes.daterange: + case PostgresTypes.int4range: + case PostgresTypes.int8range: + case PostgresTypes.money: + case PostgresTypes.reltime: // To allow users to cast it based on Timezone + case PostgresTypes.text: + case PostgresTypes.time: // To allow users to cast it based on Timezone + case PostgresTypes.timestamptz: // To allow users to cast it based on Timezone + case PostgresTypes.timetz: // To allow users to cast it based on Timezone + case PostgresTypes.tsrange: + case PostgresTypes.tstzrange: + return noop(value); + default: + // Return the value for remaining types + return noop(value); + } +}; +const noop = (value) => { + return value; +}; +export const toBoolean = (value) => { + switch (value) { + case 't': + return true; + case 'f': + return false; + default: + return value; + } +}; +export const toNumber = (value) => { + if (typeof value === 'string') { + const parsedValue = parseFloat(value); + if (!Number.isNaN(parsedValue)) { + return parsedValue; + } + } + return value; +}; +export const toJson = (value) => { + if (typeof value === 'string') { + try { + return JSON.parse(value); + } + catch (error) { + console.log(`JSON parse error: ${error}`); + return value; + } + } + return value; +}; +/** + * Converts a Postgres Array into a native JS array + * + * @example toArray('{}', 'int4') + * //=> [] + * @example toArray('{"[2021-01-01,2021-12-31)","(2021-01-01,2021-12-32]"}', 'daterange') + * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]'] + * @example toArray([1,2,3,4], 'int4') + * //=> [1,2,3,4] + */ +export const toArray = (value, type) => { + if (typeof value !== 'string') { + return value; + } + const lastIdx = value.length - 1; + const closeBrace = value[lastIdx]; + const openBrace = value[0]; + // Confirm value is a Postgres array by checking curly brackets + if (openBrace === '{' && closeBrace === '}') { + let arr; + const valTrim = value.slice(1, lastIdx); + // TODO: find a better solution to separate Postgres array data + try { + arr = JSON.parse('[' + valTrim + ']'); + } + catch (_) { + // WARNING: splitting on comma does not cover all edge cases + arr = valTrim ? valTrim.split(',') : []; + } + return arr.map((val) => convertCell(type, val)); + } + return value; +}; +/** + * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T' + * See https://github.com/supabase/supabase/issues/18 + * + * @example toTimestampString('2019-09-10 00:00:00') + * //=> '2019-09-10T00:00:00' + */ +export const toTimestampString = (value) => { + if (typeof value === 'string') { + return value.replace(' ', 'T'); + } + return value; +}; +//# sourceMappingURL=transformers.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/transformers.js.map b/node_modules/@supabase/realtime-js/dist/module/lib/transformers.js.map new file mode 100644 index 0000000..56f1325 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/transformers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transformers.js","sourceRoot":"","sources":["../../../src/lib/transformers.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,0EAA0E;AAC1E,yFAAyF;AAEzF,MAAM,CAAN,IAAY,aAyBX;AAzBD,WAAY,aAAa;IACvB,oCAAmB,CAAA;IACnB,8BAAa,CAAA;IACb,8BAAa,CAAA;IACb,wCAAuB,CAAA;IACvB,kCAAiB,CAAA;IACjB,kCAAiB,CAAA;IACjB,8BAAa,CAAA;IACb,8BAAa,CAAA;IACb,wCAAuB,CAAA;IACvB,8BAAa,CAAA;IACb,wCAAuB,CAAA;IACvB,8BAAa,CAAA;IACb,gCAAe,CAAA;IACf,gCAAe,CAAA;IACf,oCAAmB,CAAA;IACnB,4BAAW,CAAA;IACX,oCAAmB,CAAA;IACnB,8BAAa,CAAA;IACb,8BAAa,CAAA;IACb,wCAAuB,CAAA;IACvB,4CAA2B,CAAA;IAC3B,kCAAiB,CAAA;IACjB,oCAAmB,CAAA;IACnB,wCAAuB,CAAA;AACzB,CAAC,EAzBW,aAAa,KAAb,aAAa,QAyBxB;AAgBD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAC/B,OAAgB,EAChB,MAAc,EACd,UAAoC,EAAE,EAC9B,EAAE;;IACV,MAAM,SAAS,GAAG,MAAA,OAAO,CAAC,SAAS,mCAAI,EAAE,CAAA;IAEzC,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE;QACjD,GAAG,CAAC,OAAO,CAAC,GAAG,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,CAAC,CAAA;QACjE,OAAO,GAAG,CAAA;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vC,+DAA+D;QAC/D,IAAI;YACF,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,CAAC,CAAA;SACtC;QAAC,OAAO,CAAC,EAAE;YACV,4DAA4D;YAC5D,GAAG,GAAG,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;SACxC;QAED,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,GAAc,EAAE,EAAE,CAAC,WAAW,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;KAC3D;IAED,OAAO,KAAK,CAAA;AACd,CAAC,CAAA;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,KAAkB,EAAe,EAAE;IACnE,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC7B,OAAO,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;KAC/B;IAED,OAAO,KAAK,CAAA;AACd,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/version.d.ts b/node_modules/@supabase/realtime-js/dist/module/lib/version.d.ts new file mode 100644 index 0000000..b67fe60 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.7.3"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/version.d.ts.map b/node_modules/@supabase/realtime-js/dist/module/lib/version.d.ts.map new file mode 100644 index 0000000..7c1c990 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,oBAAoB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/version.js b/node_modules/@supabase/realtime-js/dist/module/lib/version.js new file mode 100644 index 0000000..2e84c71 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/version.js @@ -0,0 +1,2 @@ +export const version = '2.7.3'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/dist/module/lib/version.js.map b/node_modules/@supabase/realtime-js/dist/module/lib/version.js.map new file mode 100644 index 0000000..8a0d781 --- /dev/null +++ b/node_modules/@supabase/realtime-js/dist/module/lib/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,iBAAiB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/realtime-js/package.json b/node_modules/@supabase/realtime-js/package.json new file mode 100644 index 0000000..2d95f7b --- /dev/null +++ b/node_modules/@supabase/realtime-js/package.json @@ -0,0 +1,60 @@ +{ + "name": "@supabase/realtime-js", + "version": "2.7.3", + "description": "Listen to realtime updates to your PostgreSQL database", + "keywords": [ + "realtime", + "phoenix", + "elixir", + "javascript", + "typescript", + "firebase", + "supabase" + ], + "homepage": "https://github.com/supabase/realtime-js", + "bugs": "https://github.com/supabase/realtime-js/issues", + "files": [ + "dist", + "src" + ], + "main": "dist/main/index.js", + "module": "dist/module/index.js", + "types": "dist/module/index.d.ts", + "repository": "https://github.com/supabase/realtime-js", + "author": "Supabase", + "license": "MIT", + "scripts": { + "clean": "rimraf dist docs/v2", + "format": "prettier --write \"{src,test}/**/*.ts\"", + "build": "run-s clean format build:*", + "build:main": "tsc -p tsconfig.json", + "build:module": "tsc -p tsconfig.module.json", + "mocha": "node -r esm node_modules/.bin/mocha ./test/**/*.js -r jsdom-global/register", + "test": "run-s clean build mocha", + "docs": "typedoc src/index.ts --out docs/v2", + "docs:json": "typedoc --json docs/v2/spec.json --excludeExternals src/index.ts" + }, + "dependencies": { + "@types/phoenix": "^1.5.4", + "@types/websocket": "^1.0.3", + "websocket": "^1.0.34" + }, + "devDependencies": { + "@babel/runtime": "^7.9.2", + "babel-preset-env": "^1.7.0", + "babel-register": "^6.26.0", + "eslint": "^7.0.0", + "esm": "^3.2.25", + "jsdom": "^16.7.0", + "jsdom-global": "3.0.0", + "mocha": "^8.0.1", + "mock-socket": "^9.0.3", + "npm-run-all": "^4.1.5", + "nyc": "^15.1.0", + "prettier": "^2.1.2", + "semantic-release-plugin-update-version-in-files": "^1.1.0", + "sinon": "^9.0.2", + "typedoc": "^0.22.16", + "typescript": "^4.0.3" + } +} diff --git a/node_modules/@supabase/realtime-js/src/RealtimeChannel.ts b/node_modules/@supabase/realtime-js/src/RealtimeChannel.ts new file mode 100644 index 0000000..0324dc9 --- /dev/null +++ b/node_modules/@supabase/realtime-js/src/RealtimeChannel.ts @@ -0,0 +1,729 @@ +import { CHANNEL_EVENTS, CHANNEL_STATES } from './lib/constants' +import Push from './lib/push' +import type RealtimeClient from './RealtimeClient' +import Timer from './lib/timer' +import RealtimePresence, { + REALTIME_PRESENCE_LISTEN_EVENTS, +} from './RealtimePresence' +import type { + RealtimePresenceJoinPayload, + RealtimePresenceLeavePayload, + RealtimePresenceState, +} from './RealtimePresence' +import * as Transformers from './lib/transformers' + +export type RealtimeChannelOptions = { + config: { + /** + * self option enables client to receive message it broadcast + * ack option instructs server to acknowledge that broadcast message was received + */ + broadcast?: { self?: boolean; ack?: boolean } + /** + * key option is used to track presence payload across clients + */ + presence?: { key?: string } + } +} + +type RealtimePostgresChangesPayloadBase = { + schema: string + table: string + commit_timestamp: string + errors: string[] +} + +export type RealtimePostgresInsertPayload = + RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}` + new: T + old: {} + } + +export type RealtimePostgresUpdatePayload = + RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}` + new: T + old: Partial + } + +export type RealtimePostgresDeletePayload = + RealtimePostgresChangesPayloadBase & { + eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}` + new: {} + old: Partial + } + +export type RealtimePostgresChangesPayload = + | RealtimePostgresInsertPayload + | RealtimePostgresUpdatePayload + | RealtimePostgresDeletePayload + +export type RealtimePostgresChangesFilter< + T extends `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT}` +> = { + /** + * The type of database change to listen to. + */ + event: T + /** + * The database schema to listen to. + */ + schema: string + /** + * The database table to listen to. + */ + table?: string + /** + * Receive database changes when filter is matched. + */ + filter?: string +} + +export type RealtimeChannelSendResponse = 'ok' | 'timed out' | 'rate limited' + +export enum REALTIME_POSTGRES_CHANGES_LISTEN_EVENT { + ALL = '*', + INSERT = 'INSERT', + UPDATE = 'UPDATE', + DELETE = 'DELETE', +} + +export enum REALTIME_LISTEN_TYPES { + BROADCAST = 'broadcast', + PRESENCE = 'presence', + /** + * listen to Postgres changes. + */ + POSTGRES_CHANGES = 'postgres_changes', +} + +export enum REALTIME_SUBSCRIBE_STATES { + SUBSCRIBED = 'SUBSCRIBED', + TIMED_OUT = 'TIMED_OUT', + CLOSED = 'CLOSED', + CHANNEL_ERROR = 'CHANNEL_ERROR', +} + +/** A channel is the basic building block of Realtime + * and narrows the scope of data flow to subscribed clients. + * You can think of a channel as a chatroom where participants are able to see who's online + * and send and receive messages. + **/ +export default class RealtimeChannel { + bindings: { + [key: string]: { + type: string + filter: { [key: string]: any } + callback: Function + id?: string + }[] + } = {} + timeout: number + state = CHANNEL_STATES.closed + joinedOnce = false + joinPush: Push + rejoinTimer: Timer + pushBuffer: Push[] = [] + presence: RealtimePresence + + constructor( + /** Topic name can be any string. */ + public topic: string, + public params: RealtimeChannelOptions = { config: {} }, + public socket: RealtimeClient + ) { + this.params.config = { + ...{ + broadcast: { ack: false, self: false }, + presence: { key: '' }, + }, + ...params.config, + } + this.timeout = this.socket.timeout + this.joinPush = new Push( + this, + CHANNEL_EVENTS.join, + this.params, + this.timeout + ) + this.rejoinTimer = new Timer( + () => this._rejoinUntilConnected(), + this.socket.reconnectAfterMs + ) + this.joinPush.receive('ok', () => { + this.state = CHANNEL_STATES.joined + this.rejoinTimer.reset() + this.pushBuffer.forEach((pushEvent: Push) => pushEvent.send()) + this.pushBuffer = [] + }) + this._onClose(() => { + this.rejoinTimer.reset() + this.socket.log('channel', `close ${this.topic} ${this._joinRef()}`) + this.state = CHANNEL_STATES.closed + this.socket._remove(this) + }) + this._onError((reason: string) => { + if (this._isLeaving() || this._isClosed()) { + return + } + this.socket.log('channel', `error ${this.topic}`, reason) + this.state = CHANNEL_STATES.errored + this.rejoinTimer.scheduleTimeout() + }) + this.joinPush.receive('timeout', () => { + if (!this._isJoining()) { + return + } + this.socket.log('channel', `timeout ${this.topic}`, this.joinPush.timeout) + this.state = CHANNEL_STATES.errored + this.rejoinTimer.scheduleTimeout() + }) + this._on(CHANNEL_EVENTS.reply, {}, (payload: any, ref: string) => { + this._trigger(this._replyEventName(ref), payload) + }) + + this.presence = new RealtimePresence(this) + } + + /** Subscribe registers your client with the server */ + subscribe( + callback?: (status: `${REALTIME_SUBSCRIBE_STATES}`, err?: Error) => void, + timeout = this.timeout + ): RealtimeChannel { + if (this.joinedOnce) { + throw `tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance` + } else { + const { + config: { broadcast, presence }, + } = this.params + this._onError((e: Error) => callback && callback('CHANNEL_ERROR', e)) + this._onClose(() => callback && callback('CLOSED')) + + const accessTokenPayload: { access_token?: string } = {} + const config = { + broadcast, + presence, + postgres_changes: + this.bindings.postgres_changes?.map((r) => r.filter) ?? [], + } + + if (this.socket.accessToken) { + accessTokenPayload.access_token = this.socket.accessToken + } + + this.updateJoinPayload({ ...{ config }, ...accessTokenPayload }) + + this.joinedOnce = true + this._rejoin(timeout) + + this.joinPush + .receive( + 'ok', + ({ + postgres_changes: serverPostgresFilters, + }: { + postgres_changes: { + id: string + event: string + schema?: string + table?: string + filter?: string + }[] + }) => { + this.socket.accessToken && + this.socket.setAuth(this.socket.accessToken) + + if (serverPostgresFilters === undefined) { + callback && callback('SUBSCRIBED') + return + } else { + const clientPostgresBindings = this.bindings.postgres_changes + const bindingsLen = clientPostgresBindings?.length ?? 0 + const newPostgresBindings = [] + + for (let i = 0; i < bindingsLen; i++) { + const clientPostgresBinding = clientPostgresBindings[i] + const { + filter: { event, schema, table, filter }, + } = clientPostgresBinding + const serverPostgresFilter = + serverPostgresFilters && serverPostgresFilters[i] + + if ( + serverPostgresFilter && + serverPostgresFilter.event === event && + serverPostgresFilter.schema === schema && + serverPostgresFilter.table === table && + serverPostgresFilter.filter === filter + ) { + newPostgresBindings.push({ + ...clientPostgresBinding, + id: serverPostgresFilter.id, + }) + } else { + this.unsubscribe() + callback && + callback( + 'CHANNEL_ERROR', + new Error( + 'mismatch between server and client bindings for postgres changes' + ) + ) + return + } + } + + this.bindings.postgres_changes = newPostgresBindings + + callback && callback('SUBSCRIBED') + return + } + } + ) + .receive('error', (error: { [key: string]: any }) => { + callback && + callback( + 'CHANNEL_ERROR', + new Error( + JSON.stringify(Object.values(error).join(', ') || 'error') + ) + ) + return + }) + .receive('timeout', () => { + callback && callback('TIMED_OUT') + return + }) + } + + return this + } + + presenceState< + T extends { [key: string]: any } = {} + >(): RealtimePresenceState { + return this.presence.state as RealtimePresenceState + } + + async track( + payload: { [key: string]: any }, + opts: { [key: string]: any } = {} + ): Promise { + return await this.send( + { + type: 'presence', + event: 'track', + payload, + }, + opts.timeout || this.timeout + ) + } + + async untrack( + opts: { [key: string]: any } = {} + ): Promise { + return await this.send( + { + type: 'presence', + event: 'untrack', + }, + opts + ) + } + + /** + * Creates an event handler that listens to changes. + */ + on( + type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, + filter: { event: `${REALTIME_PRESENCE_LISTEN_EVENTS.SYNC}` }, + callback: () => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, + filter: { event: `${REALTIME_PRESENCE_LISTEN_EVENTS.JOIN}` }, + callback: (payload: RealtimePresenceJoinPayload) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.PRESENCE}`, + filter: { event: `${REALTIME_PRESENCE_LISTEN_EVENTS.LEAVE}` }, + callback: (payload: RealtimePresenceLeavePayload) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, + filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL}`>, + callback: (payload: RealtimePostgresChangesPayload) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, + filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`>, + callback: (payload: RealtimePostgresInsertPayload) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, + filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`>, + callback: (payload: RealtimePostgresUpdatePayload) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`, + filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`>, + callback: (payload: RealtimePostgresDeletePayload) => void + ): RealtimeChannel + /** + * The following is placed here to display on supabase.com/docs/reference/javascript/subscribe. + * @param type One of "broadcast", "presence", or "postgres_changes". + * @param filter Custom object specific to the Realtime feature detailing which payloads to receive. + * @param callback Function to be invoked when event handler is triggered. + */ + on( + type: `${REALTIME_LISTEN_TYPES.BROADCAST}`, + filter: { event: string }, + callback: (payload: { + type: `${REALTIME_LISTEN_TYPES.BROADCAST}` + event: string + [key: string]: any + }) => void + ): RealtimeChannel + on( + type: `${REALTIME_LISTEN_TYPES}`, + filter: { event: string; [key: string]: string }, + callback: (payload: any) => void + ): RealtimeChannel { + return this._on(type, filter, callback) + } + + send( + payload: { type: string; [key: string]: any }, + opts: { [key: string]: any } = {} + ): Promise { + return new Promise((resolve) => { + const push = this._push( + payload.type, + payload, + opts.timeout || this.timeout + ) + + if (push.rateLimited) { + resolve('rate limited') + } + + if ( + payload.type === 'broadcast' && + !this.params?.config?.broadcast?.ack + ) { + resolve('ok') + } + + push.receive('ok', () => resolve('ok')) + push.receive('timeout', () => resolve('timed out')) + }) + } + + updateJoinPayload(payload: { [key: string]: any }): void { + this.joinPush.updatePayload(payload) + } + + /** + * Leaves the channel. + * + * Unsubscribes from server events, and instructs channel to terminate on server. + * Triggers onClose() hooks. + * + * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: + * channel.unsubscribe().receive("ok", () => alert("left!") ) + */ + unsubscribe(timeout = this.timeout): Promise<'ok' | 'timed out' | 'error'> { + this.state = CHANNEL_STATES.leaving + const onClose = () => { + this.socket.log('channel', `leave ${this.topic}`) + this._trigger(CHANNEL_EVENTS.close, 'leave', this._joinRef()) + } + + this.rejoinTimer.reset() + // Destroy joinPush to avoid connection timeouts during unscription phase + this.joinPush.destroy() + + return new Promise((resolve) => { + const leavePush = new Push(this, CHANNEL_EVENTS.leave, {}, timeout) + + leavePush + .receive('ok', () => { + onClose() + resolve('ok') + }) + .receive('timeout', () => { + onClose() + resolve('timed out') + }) + .receive('error', () => { + resolve('error') + }) + + leavePush.send() + + if (!this._canPush()) { + leavePush.trigger('ok', {}) + } + }) + } + + /** @internal */ + _push( + event: string, + payload: { [key: string]: any }, + timeout = this.timeout + ) { + if (!this.joinedOnce) { + throw `tried to push '${event}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events` + } + let pushEvent = new Push(this, event, payload, timeout) + if (this._canPush()) { + pushEvent.send() + } else { + pushEvent.startTimeout() + this.pushBuffer.push(pushEvent) + } + + return pushEvent + } + + /** + * Overridable message hook + * + * Receives all events for specialized message handling before dispatching to the channel callbacks. + * Must return the payload, modified or unmodified. + * + * @internal + */ + _onMessage(_event: string, payload: any, _ref?: string) { + return payload + } + + /** @internal */ + _isMember(topic: string): boolean { + return this.topic === topic + } + + /** @internal */ + _joinRef(): string { + return this.joinPush.ref + } + + /** @internal */ + _trigger(type: string, payload?: any, ref?: string) { + const typeLower = type.toLocaleLowerCase() + const { close, error, leave, join } = CHANNEL_EVENTS + const events: string[] = [close, error, leave, join] + if (ref && events.indexOf(typeLower) >= 0 && ref !== this._joinRef()) { + return + } + let handledPayload = this._onMessage(typeLower, payload, ref) + if (payload && !handledPayload) { + throw 'channel onMessage callbacks must return the payload, modified or unmodified' + } + + if (['insert', 'update', 'delete'].includes(typeLower)) { + this.bindings.postgres_changes + ?.filter((bind) => { + return ( + bind.filter?.event === '*' || + bind.filter?.event?.toLocaleLowerCase() === typeLower + ) + }) + .map((bind) => bind.callback(handledPayload, ref)) + } else { + this.bindings[typeLower] + ?.filter((bind) => { + if ( + ['broadcast', 'presence', 'postgres_changes'].includes(typeLower) + ) { + if ('id' in bind) { + const bindId = bind.id + const bindEvent = bind.filter?.event + return ( + bindId && + payload.ids?.includes(bindId) && + (bindEvent === '*' || + bindEvent?.toLocaleLowerCase() === + payload.data?.type.toLocaleLowerCase()) + ) + } else { + const bindEvent = bind?.filter?.event?.toLocaleLowerCase() + return ( + bindEvent === '*' || + bindEvent === payload?.event?.toLocaleLowerCase() + ) + } + } else { + return bind.type.toLocaleLowerCase() === typeLower + } + }) + .map((bind) => { + if (typeof handledPayload === 'object' && 'ids' in handledPayload) { + const postgresChanges = handledPayload.data + const { schema, table, commit_timestamp, type, errors } = + postgresChanges + const enrichedPayload = { + schema: schema, + table: table, + commit_timestamp: commit_timestamp, + eventType: type, + new: {}, + old: {}, + errors: errors, + } + handledPayload = { + ...enrichedPayload, + ...this._getPayloadRecords(postgresChanges), + } + } + bind.callback(handledPayload, ref) + }) + } + } + + /** @internal */ + _isClosed(): boolean { + return this.state === CHANNEL_STATES.closed + } + + /** @internal */ + _isJoined(): boolean { + return this.state === CHANNEL_STATES.joined + } + + /** @internal */ + _isJoining(): boolean { + return this.state === CHANNEL_STATES.joining + } + + /** @internal */ + _isLeaving(): boolean { + return this.state === CHANNEL_STATES.leaving + } + + /** @internal */ + _replyEventName(ref: string): string { + return `chan_reply_${ref}` + } + + /** @internal */ + _on(type: string, filter: { [key: string]: any }, callback: Function) { + const typeLower = type.toLocaleLowerCase() + + const binding = { + type: typeLower, + filter: filter, + callback: callback, + } + + if (this.bindings[typeLower]) { + this.bindings[typeLower].push(binding) + } else { + this.bindings[typeLower] = [binding] + } + + return this + } + + /** @internal */ + _off(type: string, filter: { [key: string]: any }) { + const typeLower = type.toLocaleLowerCase() + + this.bindings[typeLower] = this.bindings[typeLower].filter((bind) => { + return !( + bind.type?.toLocaleLowerCase() === typeLower && + RealtimeChannel.isEqual(bind.filter, filter) + ) + }) + return this + } + + /** @internal */ + private static isEqual( + obj1: { [key: string]: string }, + obj2: { [key: string]: string } + ) { + if (Object.keys(obj1).length !== Object.keys(obj2).length) { + return false + } + + for (const k in obj1) { + if (obj1[k] !== obj2[k]) { + return false + } + } + + return true + } + + /** @internal */ + private _rejoinUntilConnected() { + this.rejoinTimer.scheduleTimeout() + if (this.socket.isConnected()) { + this._rejoin() + } + } + + /** + * Registers a callback that will be executed when the channel closes. + * + * @internal + */ + private _onClose(callback: Function) { + this._on(CHANNEL_EVENTS.close, {}, callback) + } + + /** + * Registers a callback that will be executed when the channel encounteres an error. + * + * @internal + */ + private _onError(callback: Function) { + this._on(CHANNEL_EVENTS.error, {}, (reason: string) => callback(reason)) + } + + /** + * Returns `true` if the socket is connected and the channel has been joined. + * + * @internal + */ + private _canPush(): boolean { + return this.socket.isConnected() && this._isJoined() + } + + /** @internal */ + private _rejoin(timeout = this.timeout): void { + if (this._isLeaving()) { + return + } + this.socket._leaveOpenTopic(this.topic) + this.state = CHANNEL_STATES.joining + this.joinPush.resend(timeout) + } + + /** @internal */ + private _getPayloadRecords(payload: any) { + const records = { + new: {}, + old: {}, + } + + if (payload.type === 'INSERT' || payload.type === 'UPDATE') { + records.new = Transformers.convertChangeData( + payload.columns, + payload.record + ) + } + + if (payload.type === 'UPDATE' || payload.type === 'DELETE') { + records.old = Transformers.convertChangeData( + payload.columns, + payload.old_record + ) + } + + return records + } +} diff --git a/node_modules/@supabase/realtime-js/src/RealtimeClient.ts b/node_modules/@supabase/realtime-js/src/RealtimeClient.ts new file mode 100644 index 0000000..b1728c4 --- /dev/null +++ b/node_modules/@supabase/realtime-js/src/RealtimeClient.ts @@ -0,0 +1,471 @@ +import { w3cwebsocket } from 'websocket' +import { + VSN, + CHANNEL_EVENTS, + TRANSPORTS, + SOCKET_STATES, + DEFAULT_TIMEOUT, + WS_CLOSE_NORMAL, + DEFAULT_HEADERS, + CONNECTION_STATE, +} from './lib/constants' +import Timer from './lib/timer' +import Serializer from './lib/serializer' +import RealtimeChannel from './RealtimeChannel' +import type { RealtimeChannelOptions } from './RealtimeChannel' + +export type RealtimeClientOptions = { + transport?: WebSocket + timeout?: number + heartbeatIntervalMs?: number + logger?: Function + encode?: Function + decode?: Function + reconnectAfterMs?: Function + headers?: { [key: string]: string } + params?: { [key: string]: any } + log_level?: 'info' | 'debug' | 'warn' | 'error' +} + +export type RealtimeMessage = { + topic: string + event: string + payload: any + ref: string + join_ref?: string +} + +export type RealtimeRemoveChannelResponse = 'ok' | 'timed out' | 'error' + +const noop = () => {} + +export default class RealtimeClient { + accessToken: string | null = null + channels: RealtimeChannel[] = [] + endPoint: string = '' + headers?: { [key: string]: string } = DEFAULT_HEADERS + params?: { [key: string]: string } = {} + timeout: number = DEFAULT_TIMEOUT + transport: any = w3cwebsocket + heartbeatIntervalMs: number = 30000 + heartbeatTimer: ReturnType | undefined = undefined + pendingHeartbeatRef: string | null = null + ref: number = 0 + reconnectTimer: Timer + logger: Function = noop + encode: Function + decode: Function + reconnectAfterMs: Function + conn: WebSocket | null = null + sendBuffer: Function[] = [] + serializer: Serializer = new Serializer() + stateChangeCallbacks: { + open: Function[] + close: Function[] + error: Function[] + message: Function[] + } = { + open: [], + close: [], + error: [], + message: [], + } + eventsPerSecondLimitMs: number = 100 + inThrottle: boolean = false + + /** + * Initializes the Socket. + * + * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) + * @param options.transport The Websocket Transport, for example WebSocket. + * @param options.timeout The default timeout in milliseconds to trigger push timeouts. + * @param options.params The optional params to pass when connecting. + * @param options.headers The optional headers to pass when connecting. + * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. + * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } + * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) + * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. + * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. + */ + constructor(endPoint: string, options?: RealtimeClientOptions) { + this.endPoint = `${endPoint}/${TRANSPORTS.websocket}` + + if (options?.params) this.params = options.params + if (options?.headers) this.headers = { ...this.headers, ...options.headers } + if (options?.timeout) this.timeout = options.timeout + if (options?.logger) this.logger = options.logger + if (options?.transport) this.transport = options.transport + if (options?.heartbeatIntervalMs) + this.heartbeatIntervalMs = options.heartbeatIntervalMs + + const eventsPerSecond = options?.params?.eventsPerSecond + if (eventsPerSecond) + this.eventsPerSecondLimitMs = Math.floor(1000 / eventsPerSecond) + + this.reconnectAfterMs = options?.reconnectAfterMs + ? options.reconnectAfterMs + : (tries: number) => { + return [1000, 2000, 5000, 10000][tries - 1] || 10000 + } + this.encode = options?.encode + ? options.encode + : (payload: JSON, callback: Function) => { + return callback(JSON.stringify(payload)) + } + this.decode = options?.decode + ? options.decode + : this.serializer.decode.bind(this.serializer) + this.reconnectTimer = new Timer(async () => { + this.disconnect() + this.connect() + }, this.reconnectAfterMs) + } + + /** + * Connects the socket, unless already connected. + */ + connect(): void { + if (this.conn) { + return + } + + this.conn = new this.transport(this._endPointURL(), [], null, this.headers) + + if (this.conn) { + this.conn.binaryType = 'arraybuffer' + this.conn.onopen = () => this._onConnOpen() + this.conn.onerror = (error) => this._onConnError(error as ErrorEvent) + this.conn.onmessage = (event) => this._onConnMessage(event) + this.conn.onclose = (event) => this._onConnClose(event) + } + } + + /** + * Disconnects the socket. + * + * @param code A numeric status code to send on disconnect. + * @param reason A custom reason for the disconnect. + */ + disconnect(code?: number, reason?: string): void { + if (this.conn) { + this.conn.onclose = function () {} // noop + if (code) { + this.conn.close(code, reason ?? '') + } else { + this.conn.close() + } + this.conn = null + // remove open handles + this.heartbeatTimer && clearInterval(this.heartbeatTimer) + this.reconnectTimer.reset() + } + } + + /** + * Returns all created channels + */ + getChannels(): RealtimeChannel[] { + return this.channels + } + + /** + * Unsubscribes and removes a single channel + * @param channel A RealtimeChannel instance + */ + async removeChannel( + channel: RealtimeChannel + ): Promise { + const status = await channel.unsubscribe() + if (this.channels.length === 0) { + this.disconnect() + } + return status + } + + /** + * Unsubscribes and removes all channels + */ + async removeAllChannels(): Promise { + const values_1 = await Promise.all( + this.channels.map((channel) => channel.unsubscribe()) + ) + this.disconnect() + return values_1 + } + + /** + * Logs the message. + * + * For customized logging, `this.logger` can be overridden. + */ + log(kind: string, msg: string, data?: any) { + this.logger(kind, msg, data) + } + + /** + * Returns the current state of the socket. + */ + connectionState(): CONNECTION_STATE { + switch (this.conn && this.conn.readyState) { + case SOCKET_STATES.connecting: + return CONNECTION_STATE.Connecting + case SOCKET_STATES.open: + return CONNECTION_STATE.Open + case SOCKET_STATES.closing: + return CONNECTION_STATE.Closing + default: + return CONNECTION_STATE.Closed + } + } + + /** + * Returns `true` is the connection is open. + */ + isConnected(): boolean { + return this.connectionState() === CONNECTION_STATE.Open + } + + channel( + topic: string, + params: RealtimeChannelOptions = { config: {} } + ): RealtimeChannel { + if (!this.isConnected()) { + this.connect() + } + + const chan = new RealtimeChannel(`realtime:${topic}`, params, this) + this.channels.push(chan) + return chan + } + + /** + * Push out a message if the socket is connected. + * + * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. + */ + push(data: RealtimeMessage): 'rate limited' | void { + const { topic, event, payload, ref } = data + let callback = () => { + this.encode(data, (result: any) => { + this.conn?.send(result) + }) + } + this.log('push', `${topic} ${event} (${ref})`, payload) + if (this.isConnected()) { + if (['broadcast', 'presence', 'postgres_changes'].includes(event)) { + const isThrottled = this._throttle(callback)() + if (isThrottled) { + return 'rate limited' + } + } else { + callback() + } + } else { + this.sendBuffer.push(callback) + } + } + + /** + * Sets the JWT access token used for channel subscription authorization and Realtime RLS. + * + * @param token A JWT string. + */ + setAuth(token: string | null): void { + this.accessToken = token + + this.channels.forEach((channel) => { + token && channel.updateJoinPayload({ access_token: token }) + + if (channel.joinedOnce && channel._isJoined()) { + channel._push(CHANNEL_EVENTS.access_token, { access_token: token }) + } + }) + } + + /** + * Return the next message ref, accounting for overflows + * + * @internal + */ + _makeRef(): string { + let newRef = this.ref + 1 + if (newRef === this.ref) { + this.ref = 0 + } else { + this.ref = newRef + } + + return this.ref.toString() + } + + /** + * Unsubscribe from channels with the specified topic. + * + * @internal + */ + _leaveOpenTopic(topic: string): void { + let dupChannel = this.channels.find( + (c) => c.topic === topic && (c._isJoined() || c._isJoining()) + ) + if (dupChannel) { + this.log('transport', `leaving duplicate topic "${topic}"`) + dupChannel.unsubscribe() + } + } + + /** + * Removes a subscription from the socket. + * + * @param channel An open subscription. + * + * @internal + */ + _remove(channel: RealtimeChannel) { + this.channels = this.channels.filter( + (c: RealtimeChannel) => c._joinRef() !== channel._joinRef() + ) + } + + /** + * Returns the URL of the websocket. + * + * @internal + */ + private _endPointURL(): string { + return this._appendParams( + this.endPoint, + Object.assign({}, this.params, { vsn: VSN }) + ) + } + + /** @internal */ + private _onConnMessage(rawMessage: { data: any }) { + this.decode(rawMessage.data, (msg: RealtimeMessage) => { + let { topic, event, payload, ref } = msg + + if ( + (ref && ref === this.pendingHeartbeatRef) || + event === payload?.type + ) { + this.pendingHeartbeatRef = null + } + + this.log( + 'receive', + `${payload.status || ''} ${topic} ${event} ${ + (ref && '(' + ref + ')') || '' + }`, + payload + ) + this.channels + .filter((channel: RealtimeChannel) => channel._isMember(topic)) + .forEach((channel: RealtimeChannel) => + channel._trigger(event, payload, ref) + ) + this.stateChangeCallbacks.message.forEach((callback) => callback(msg)) + }) + } + + /** @internal */ + private _onConnOpen() { + this.log('transport', `connected to ${this._endPointURL()}`) + this._flushSendBuffer() + this.reconnectTimer.reset() + this.heartbeatTimer && clearInterval(this.heartbeatTimer) + this.heartbeatTimer = setInterval( + () => this._sendHeartbeat(), + this.heartbeatIntervalMs + ) + this.stateChangeCallbacks.open.forEach((callback) => callback())! + } + + /** @internal */ + private _onConnClose(event: any) { + this.log('transport', 'close', event) + this._triggerChanError() + this.heartbeatTimer && clearInterval(this.heartbeatTimer) + this.reconnectTimer.scheduleTimeout() + this.stateChangeCallbacks.close.forEach((callback) => callback(event)) + } + + /** @internal */ + private _onConnError(error: ErrorEvent) { + this.log('transport', error.message) + this._triggerChanError() + this.stateChangeCallbacks.error.forEach((callback) => callback(error)) + } + + /** @internal */ + private _triggerChanError() { + this.channels.forEach((channel: RealtimeChannel) => + channel._trigger(CHANNEL_EVENTS.error) + ) + } + + /** @internal */ + private _appendParams( + url: string, + params: { [key: string]: string } + ): string { + if (Object.keys(params).length === 0) { + return url + } + const prefix = url.match(/\?/) ? '&' : '?' + const query = new URLSearchParams(params) + + return `${url}${prefix}${query}` + } + + /** @internal */ + private _flushSendBuffer() { + if (this.isConnected() && this.sendBuffer.length > 0) { + this.sendBuffer.forEach((callback) => callback()) + this.sendBuffer = [] + } + } + /** @internal */ + private _sendHeartbeat() { + if (!this.isConnected()) { + return + } + if (this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null + this.log( + 'transport', + 'heartbeat timeout. Attempting to re-establish connection' + ) + this.conn?.close(WS_CLOSE_NORMAL, 'hearbeat timeout') + return + } + this.pendingHeartbeatRef = this._makeRef() + this.push({ + topic: 'phoenix', + event: 'heartbeat', + payload: {}, + ref: this.pendingHeartbeatRef, + }) + this.setAuth(this.accessToken) + } + + /** @internal */ + private _throttle( + callback: Function, + eventsPerSecondLimitMs: number = this.eventsPerSecondLimitMs + ): () => boolean { + return () => { + if (this.inThrottle) return true + + callback() + + if (eventsPerSecondLimitMs > 0) { + this.inThrottle = true + + setTimeout(() => { + this.inThrottle = false + }, eventsPerSecondLimitMs) + } + + return false + } + } +} diff --git a/node_modules/@supabase/realtime-js/src/RealtimePresence.ts b/node_modules/@supabase/realtime-js/src/RealtimePresence.ts new file mode 100644 index 0000000..1c3eaf9 --- /dev/null +++ b/node_modules/@supabase/realtime-js/src/RealtimePresence.ts @@ -0,0 +1,364 @@ +/* + This file draws heavily from https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/assets/js/phoenix/presence.js + License: https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/LICENSE.md +*/ + +import type { + PresenceOpts, + PresenceOnJoinCallback, + PresenceOnLeaveCallback, +} from 'phoenix' +import type RealtimeChannel from './RealtimeChannel' + +type Presence = { + presence_ref: string +} & T + +export type RealtimePresenceState = { + [key: string]: Presence[] +} + +export type RealtimePresenceJoinPayload = { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.JOIN}` + key: string + currentPresences: Presence[] + newPresences: Presence[] +} + +export type RealtimePresenceLeavePayload = { + event: `${REALTIME_PRESENCE_LISTEN_EVENTS.LEAVE}` + key: string + currentPresences: Presence[] + leftPresences: Presence[] +} + +export enum REALTIME_PRESENCE_LISTEN_EVENTS { + SYNC = 'sync', + JOIN = 'join', + LEAVE = 'leave', +} + +type PresenceDiff = { + joins: RealtimePresenceState + leaves: RealtimePresenceState +} + +type RawPresenceState = { + [key: string]: { + metas: { + phx_ref?: string + phx_ref_prev?: string + [key: string]: any + }[] + } +} + +type RawPresenceDiff = { + joins: RawPresenceState + leaves: RawPresenceState +} + +type PresenceChooser = (key: string, presences: Presence[]) => T + +export default class RealtimePresence { + state: RealtimePresenceState = {} + pendingDiffs: RawPresenceDiff[] = [] + joinRef: string | null = null + caller: { + onJoin: PresenceOnJoinCallback + onLeave: PresenceOnLeaveCallback + onSync: () => void + } = { + onJoin: () => {}, + onLeave: () => {}, + onSync: () => {}, + } + + /** + * Initializes the Presence. + * + * @param channel - The RealtimeChannel + * @param opts - The options, + * for example `{events: {state: 'state', diff: 'diff'}}` + */ + constructor(public channel: RealtimeChannel, opts?: PresenceOpts) { + const events = opts?.events || { + state: 'presence_state', + diff: 'presence_diff', + } + + this.channel._on(events.state, {}, (newState: RawPresenceState) => { + const { onJoin, onLeave, onSync } = this.caller + + this.joinRef = this.channel._joinRef() + + this.state = RealtimePresence.syncState( + this.state, + newState, + onJoin, + onLeave + ) + + this.pendingDiffs.forEach((diff) => { + this.state = RealtimePresence.syncDiff( + this.state, + diff, + onJoin, + onLeave + ) + }) + + this.pendingDiffs = [] + + onSync() + }) + + this.channel._on(events.diff, {}, (diff: RawPresenceDiff) => { + const { onJoin, onLeave, onSync } = this.caller + + if (this.inPendingSyncState()) { + this.pendingDiffs.push(diff) + } else { + this.state = RealtimePresence.syncDiff( + this.state, + diff, + onJoin, + onLeave + ) + + onSync() + } + }) + + this.onJoin((key, currentPresences, newPresences) => { + this.channel._trigger('presence', { + event: 'join', + key, + currentPresences, + newPresences, + }) + }) + + this.onLeave((key, currentPresences, leftPresences) => { + this.channel._trigger('presence', { + event: 'leave', + key, + currentPresences, + leftPresences, + }) + }) + + this.onSync(() => { + this.channel._trigger('presence', { event: 'sync' }) + }) + } + + /** + * Used to sync the list of presences on the server with the + * client's state. + * + * An optional `onJoin` and `onLeave` callback can be provided to + * react to changes in the client's local presences across + * disconnects and reconnects with the server. + * + * @internal + */ + private static syncState( + currentState: RealtimePresenceState, + newState: RawPresenceState | RealtimePresenceState, + onJoin: PresenceOnJoinCallback, + onLeave: PresenceOnLeaveCallback + ): RealtimePresenceState { + const state = this.cloneDeep(currentState) + const transformedState = this.transformState(newState) + const joins: RealtimePresenceState = {} + const leaves: RealtimePresenceState = {} + + this.map(state, (key: string, presences: Presence[]) => { + if (!transformedState[key]) { + leaves[key] = presences + } + }) + + this.map(transformedState, (key, newPresences: Presence[]) => { + const currentPresences: Presence[] = state[key] + + if (currentPresences) { + const newPresenceRefs = newPresences.map( + (m: Presence) => m.presence_ref + ) + const curPresenceRefs = currentPresences.map( + (m: Presence) => m.presence_ref + ) + const joinedPresences: Presence[] = newPresences.filter( + (m: Presence) => curPresenceRefs.indexOf(m.presence_ref) < 0 + ) + const leftPresences: Presence[] = currentPresences.filter( + (m: Presence) => newPresenceRefs.indexOf(m.presence_ref) < 0 + ) + + if (joinedPresences.length > 0) { + joins[key] = joinedPresences + } + + if (leftPresences.length > 0) { + leaves[key] = leftPresences + } + } else { + joins[key] = newPresences + } + }) + + return this.syncDiff(state, { joins, leaves }, onJoin, onLeave) + } + + /** + * Used to sync a diff of presence join and leave events from the + * server, as they happen. + * + * Like `syncState`, `syncDiff` accepts optional `onJoin` and + * `onLeave` callbacks to react to a user joining or leaving from a + * device. + * + * @internal + */ + private static syncDiff( + state: RealtimePresenceState, + diff: RawPresenceDiff | PresenceDiff, + onJoin: PresenceOnJoinCallback, + onLeave: PresenceOnLeaveCallback + ): RealtimePresenceState { + const { joins, leaves } = { + joins: this.transformState(diff.joins), + leaves: this.transformState(diff.leaves), + } + + if (!onJoin) { + onJoin = () => {} + } + + if (!onLeave) { + onLeave = () => {} + } + + this.map(joins, (key, newPresences: Presence[]) => { + const currentPresences: Presence[] = state[key] ?? [] + state[key] = this.cloneDeep(newPresences) + + if (currentPresences.length > 0) { + const joinedPresenceRefs = state[key].map( + (m: Presence) => m.presence_ref + ) + const curPresences: Presence[] = currentPresences.filter( + (m: Presence) => joinedPresenceRefs.indexOf(m.presence_ref) < 0 + ) + + state[key].unshift(...curPresences) + } + + onJoin(key, currentPresences, newPresences) + }) + + this.map(leaves, (key, leftPresences: Presence[]) => { + let currentPresences: Presence[] = state[key] + + if (!currentPresences) return + + const presenceRefsToRemove = leftPresences.map( + (m: Presence) => m.presence_ref + ) + currentPresences = currentPresences.filter( + (m: Presence) => presenceRefsToRemove.indexOf(m.presence_ref) < 0 + ) + + state[key] = currentPresences + + onLeave(key, currentPresences, leftPresences) + + if (currentPresences.length === 0) delete state[key] + }) + + return state + } + + /** @internal */ + private static map( + obj: RealtimePresenceState, + func: PresenceChooser + ): T[] { + return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key])) + } + + /** + * Remove 'metas' key + * Change 'phx_ref' to 'presence_ref' + * Remove 'phx_ref' and 'phx_ref_prev' + * + * @example + * // returns { + * abc123: [ + * { presence_ref: '2', user_id: 1 }, + * { presence_ref: '3', user_id: 2 } + * ] + * } + * RealtimePresence.transformState({ + * abc123: { + * metas: [ + * { phx_ref: '2', phx_ref_prev: '1' user_id: 1 }, + * { phx_ref: '3', user_id: 2 } + * ] + * } + * }) + * + * @internal + */ + private static transformState( + state: RawPresenceState | RealtimePresenceState + ): RealtimePresenceState { + state = this.cloneDeep(state) + + return Object.getOwnPropertyNames(state).reduce((newState, key) => { + const presences = state[key] + + if ('metas' in presences) { + newState[key] = presences.metas.map((presence) => { + presence['presence_ref'] = presence['phx_ref'] + + delete presence['phx_ref'] + delete presence['phx_ref_prev'] + + return presence + }) as Presence[] + } else { + newState[key] = presences + } + + return newState + }, {} as RealtimePresenceState) + } + + /** @internal */ + private static cloneDeep(obj: { [key: string]: any }) { + return JSON.parse(JSON.stringify(obj)) + } + + /** @internal */ + private onJoin(callback: PresenceOnJoinCallback): void { + this.caller.onJoin = callback + } + + /** @internal */ + private onLeave(callback: PresenceOnLeaveCallback): void { + this.caller.onLeave = callback + } + + /** @internal */ + private onSync(callback: () => void): void { + this.caller.onSync = callback + } + + /** @internal */ + private inPendingSyncState(): boolean { + return !this.joinRef || this.joinRef !== this.channel._joinRef() + } +} diff --git a/node_modules/@supabase/realtime-js/src/index.ts b/node_modules/@supabase/realtime-js/src/index.ts new file mode 100644 index 0000000..220a6c4 --- /dev/null +++ b/node_modules/@supabase/realtime-js/src/index.ts @@ -0,0 +1,46 @@ +import RealtimeClient, { + RealtimeClientOptions, + RealtimeMessage, + RealtimeRemoveChannelResponse, +} from './RealtimeClient' +import RealtimeChannel, { + RealtimeChannelOptions, + RealtimeChannelSendResponse, + RealtimePostgresChangesFilter, + RealtimePostgresChangesPayload, + RealtimePostgresInsertPayload, + RealtimePostgresUpdatePayload, + RealtimePostgresDeletePayload, + REALTIME_LISTEN_TYPES, + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, + REALTIME_SUBSCRIBE_STATES, +} from './RealtimeChannel' +import RealtimePresence, { + RealtimePresenceState, + RealtimePresenceJoinPayload, + RealtimePresenceLeavePayload, + REALTIME_PRESENCE_LISTEN_EVENTS, +} from './RealtimePresence' + +export { + RealtimePresence, + RealtimeChannel, + RealtimeChannelOptions, + RealtimeChannelSendResponse, + RealtimeClient, + RealtimeClientOptions, + RealtimeMessage, + RealtimePostgresChangesFilter, + RealtimePostgresChangesPayload, + RealtimePostgresInsertPayload, + RealtimePostgresUpdatePayload, + RealtimePostgresDeletePayload, + RealtimePresenceJoinPayload, + RealtimePresenceLeavePayload, + RealtimePresenceState, + RealtimeRemoveChannelResponse, + REALTIME_LISTEN_TYPES, + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, + REALTIME_PRESENCE_LISTEN_EVENTS, + REALTIME_SUBSCRIBE_STATES, +} diff --git a/node_modules/@supabase/realtime-js/src/lib/constants.ts b/node_modules/@supabase/realtime-js/src/lib/constants.ts new file mode 100644 index 0000000..8b92dc6 --- /dev/null +++ b/node_modules/@supabase/realtime-js/src/lib/constants.ts @@ -0,0 +1,44 @@ +import { version } from './version' + +export const DEFAULT_HEADERS = { 'X-Client-Info': `realtime-js/${version}` } + +export const VSN: string = '1.0.0' + +export const DEFAULT_TIMEOUT = 10000 + +export const WS_CLOSE_NORMAL = 1000 + +export enum SOCKET_STATES { + connecting = 0, + open = 1, + closing = 2, + closed = 3, +} + +export enum CHANNEL_STATES { + closed = 'closed', + errored = 'errored', + joined = 'joined', + joining = 'joining', + leaving = 'leaving', +} + +export enum CHANNEL_EVENTS { + close = 'phx_close', + error = 'phx_error', + join = 'phx_join', + reply = 'phx_reply', + leave = 'phx_leave', + access_token = 'access_token', +} + +export enum TRANSPORTS { + websocket = 'websocket', +} + +export enum CONNECTION_STATE { + Connecting = 'connecting', + Open = 'open', + Closing = 'closing', + Closed = 'closed', +} diff --git a/node_modules/@supabase/realtime-js/src/lib/push.ts b/node_modules/@supabase/realtime-js/src/lib/push.ts new file mode 100644 index 0000000..48a961b --- /dev/null +++ b/node_modules/@supabase/realtime-js/src/lib/push.ts @@ -0,0 +1,134 @@ +import { DEFAULT_TIMEOUT } from '../lib/constants' +import type RealtimeChannel from '../RealtimeChannel' + +export default class Push { + sent: boolean = false + timeoutTimer: number | undefined = undefined + ref: string = '' + receivedResp: { + status: string + response: { [key: string]: any } + } | null = null + recHooks: { + status: string + callback: Function + }[] = [] + refEvent: string | null = null + rateLimited: boolean = false + + /** + * Initializes the Push + * + * @param channel The Channel + * @param event The event, for example `"phx_join"` + * @param payload The payload, for example `{user_id: 123}` + * @param timeout The push timeout in milliseconds + */ + constructor( + public channel: RealtimeChannel, + public event: string, + public payload: { [key: string]: any } = {}, + public timeout: number = DEFAULT_TIMEOUT + ) {} + + resend(timeout: number) { + this.timeout = timeout + this._cancelRefEvent() + this.ref = '' + this.refEvent = null + this.receivedResp = null + this.sent = false + this.send() + } + + send() { + if (this._hasReceived('timeout')) { + return + } + this.startTimeout() + this.sent = true + const status = this.channel.socket.push({ + topic: this.channel.topic, + event: this.event, + payload: this.payload, + ref: this.ref, + join_ref: this.channel._joinRef(), + }) + if (status === 'rate limited') { + this.rateLimited = true + } + } + + updatePayload(payload: { [key: string]: any }): void { + this.payload = { ...this.payload, ...payload } + } + + receive(status: string, callback: Function) { + if (this._hasReceived(status)) { + callback(this.receivedResp?.response) + } + + this.recHooks.push({ status, callback }) + return this + } + + startTimeout() { + if (this.timeoutTimer) { + return + } + this.ref = this.channel.socket._makeRef() + this.refEvent = this.channel._replyEventName(this.ref) + + const callback = (payload: any) => { + this._cancelRefEvent() + this._cancelTimeout() + this.receivedResp = payload + this._matchReceive(payload) + } + + this.channel._on(this.refEvent, {}, callback) + + this.timeoutTimer = setTimeout(() => { + this.trigger('timeout', {}) + }, this.timeout) + } + + trigger(status: string, response: any) { + if (this.refEvent) + this.channel._trigger(this.refEvent, { status, response }) + } + + destroy() { + this._cancelRefEvent() + this._cancelTimeout() + } + + private _cancelRefEvent() { + if (!this.refEvent) { + return + } + + this.channel._off(this.refEvent, {}) + } + + private _cancelTimeout() { + clearTimeout(this.timeoutTimer) + this.timeoutTimer = undefined + } + + private _matchReceive({ + status, + response, + }: { + status: string + response: Function + }) { + this.recHooks + .filter((h) => h.status === status) + .forEach((h) => h.callback(response)) + } + + private _hasReceived(status: string) { + return this.receivedResp && this.receivedResp.status === status + } +} diff --git a/node_modules/@supabase/realtime-js/src/lib/serializer.ts b/node_modules/@supabase/realtime-js/src/lib/serializer.ts new file mode 100644 index 0000000..66492f3 --- /dev/null +++ b/node_modules/@supabase/realtime-js/src/lib/serializer.ts @@ -0,0 +1,49 @@ +// This file draws heavily from https://github.com/phoenixframework/phoenix/commit/cf098e9cf7a44ee6479d31d911a97d3c7430c6fe +// License: https://github.com/phoenixframework/phoenix/blob/master/LICENSE.md + +export default class Serializer { + HEADER_LENGTH = 1 + + decode(rawPayload: ArrayBuffer | string, callback: Function) { + if (rawPayload.constructor === ArrayBuffer) { + return callback(this._binaryDecode(rawPayload)) + } + + if (typeof rawPayload === 'string') { + return callback(JSON.parse(rawPayload)) + } + + return callback({}) + } + + private _binaryDecode(buffer: ArrayBuffer) { + const view = new DataView(buffer) + const decoder = new TextDecoder() + + return this._decodeBroadcast(buffer, view, decoder) + } + + private _decodeBroadcast( + buffer: ArrayBuffer, + view: DataView, + decoder: TextDecoder + ): { + ref: null + topic: string + event: string + payload: { [key: string]: any } + } { + const topicSize = view.getUint8(1) + const eventSize = view.getUint8(2) + let offset = this.HEADER_LENGTH + 2 + const topic = decoder.decode(buffer.slice(offset, offset + topicSize)) + offset = offset + topicSize + const event = decoder.decode(buffer.slice(offset, offset + eventSize)) + offset = offset + eventSize + const data = JSON.parse( + decoder.decode(buffer.slice(offset, buffer.byteLength)) + ) + + return { ref: null, topic: topic, event: event, payload: data } + } +} diff --git a/node_modules/@supabase/realtime-js/src/lib/timer.ts b/node_modules/@supabase/realtime-js/src/lib/timer.ts new file mode 100644 index 0000000..8a3700f --- /dev/null +++ b/node_modules/@supabase/realtime-js/src/lib/timer.ts @@ -0,0 +1,36 @@ +/** + * Creates a timer that accepts a `timerCalc` function to perform calculated timeout retries, such as exponential backoff. + * + * @example + * let reconnectTimer = new Timer(() => this.connect(), function(tries){ + * return [1000, 5000, 10000][tries - 1] || 10000 + * }) + * reconnectTimer.scheduleTimeout() // fires after 1000 + * reconnectTimer.scheduleTimeout() // fires after 5000 + * reconnectTimer.reset() + * reconnectTimer.scheduleTimeout() // fires after 1000 + */ +export default class Timer { + timer: number | undefined = undefined + tries: number = 0 + + constructor(public callback: Function, public timerCalc: Function) { + this.callback = callback + this.timerCalc = timerCalc + } + + reset() { + this.tries = 0 + clearTimeout(this.timer) + } + + // Cancels any previous scheduleTimeout and schedules callback + scheduleTimeout() { + clearTimeout(this.timer) + + this.timer = setTimeout(() => { + this.tries = this.tries + 1 + this.callback() + }, this.timerCalc(this.tries + 1)) + } +} diff --git a/node_modules/@supabase/realtime-js/src/lib/transformers.ts b/node_modules/@supabase/realtime-js/src/lib/transformers.ts new file mode 100644 index 0000000..6dfa8c9 --- /dev/null +++ b/node_modules/@supabase/realtime-js/src/lib/transformers.ts @@ -0,0 +1,247 @@ +/** + * Helpers to convert the change Payload into native JS types. + */ + +// Adapted from epgsql (src/epgsql_binary.erl), this module licensed under +// 3-clause BSD found here: https://raw.githubusercontent.com/epgsql/epgsql/devel/LICENSE + +export enum PostgresTypes { + abstime = 'abstime', + bool = 'bool', + date = 'date', + daterange = 'daterange', + float4 = 'float4', + float8 = 'float8', + int2 = 'int2', + int4 = 'int4', + int4range = 'int4range', + int8 = 'int8', + int8range = 'int8range', + json = 'json', + jsonb = 'jsonb', + money = 'money', + numeric = 'numeric', + oid = 'oid', + reltime = 'reltime', + text = 'text', + time = 'time', + timestamp = 'timestamp', + timestamptz = 'timestamptz', + timetz = 'timetz', + tsrange = 'tsrange', + tstzrange = 'tstzrange', +} + +type Columns = { + name: string // the column name. eg: "user_id" + type: string // the column type. eg: "uuid" + flags?: string[] // any special flags for the column. eg: ["key"] + type_modifier?: number // the type modifier. eg: 4294967295 +}[] + +type BaseValue = null | string | number | boolean +type RecordValue = BaseValue | BaseValue[] + +type Record = { + [key: string]: RecordValue +} + +/** + * Takes an array of columns and an object of string values then converts each string value + * to its mapped type. + * + * @param {{name: String, type: String}[]} columns + * @param {Object} record + * @param {Object} options The map of various options that can be applied to the mapper + * @param {Array} options.skipTypes The array of types that should not be converted + * + * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {}) + * //=>{ first_name: 'Paul', age: 33 } + */ +export const convertChangeData = ( + columns: Columns, + record: Record, + options: { skipTypes?: string[] } = {} +): Record => { + const skipTypes = options.skipTypes ?? [] + + return Object.keys(record).reduce((acc, rec_key) => { + acc[rec_key] = convertColumn(rec_key, columns, record, skipTypes) + return acc + }, {} as Record) +} + +/** + * Converts the value of an individual column. + * + * @param {String} columnName The column that you want to convert + * @param {{name: String, type: String}[]} columns All of the columns + * @param {Object} record The map of string values + * @param {Array} skipTypes An array of types that should not be converted + * @return {object} Useless information + * + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, []) + * //=> 33 + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4']) + * //=> "33" + */ +export const convertColumn = ( + columnName: string, + columns: Columns, + record: Record, + skipTypes: string[] +): RecordValue => { + const column = columns.find((x) => x.name === columnName) + const colType = column?.type + const value = record[columnName] + + if (colType && !skipTypes.includes(colType)) { + return convertCell(colType, value) + } + + return noop(value) +} + +/** + * If the value of the cell is `null`, returns null. + * Otherwise converts the string value to the correct type. + * @param {String} type A postgres column type + * @param {String} value The cell value + * + * @example convertCell('bool', 't') + * //=> true + * @example convertCell('int8', '10') + * //=> 10 + * @example convertCell('_int4', '{1,2,3,4}') + * //=> [1,2,3,4] + */ +export const convertCell = (type: string, value: RecordValue): RecordValue => { + // if data type is an array + if (type.charAt(0) === '_') { + const dataType = type.slice(1, type.length) + return toArray(value, dataType) + } + + // If not null, convert to correct type. + switch (type) { + case PostgresTypes.bool: + return toBoolean(value) + case PostgresTypes.float4: + case PostgresTypes.float8: + case PostgresTypes.int2: + case PostgresTypes.int4: + case PostgresTypes.int8: + case PostgresTypes.numeric: + case PostgresTypes.oid: + return toNumber(value) + case PostgresTypes.json: + case PostgresTypes.jsonb: + return toJson(value) + case PostgresTypes.timestamp: + return toTimestampString(value) // Format to be consistent with PostgREST + case PostgresTypes.abstime: // To allow users to cast it based on Timezone + case PostgresTypes.date: // To allow users to cast it based on Timezone + case PostgresTypes.daterange: + case PostgresTypes.int4range: + case PostgresTypes.int8range: + case PostgresTypes.money: + case PostgresTypes.reltime: // To allow users to cast it based on Timezone + case PostgresTypes.text: + case PostgresTypes.time: // To allow users to cast it based on Timezone + case PostgresTypes.timestamptz: // To allow users to cast it based on Timezone + case PostgresTypes.timetz: // To allow users to cast it based on Timezone + case PostgresTypes.tsrange: + case PostgresTypes.tstzrange: + return noop(value) + default: + // Return the value for remaining types + return noop(value) + } +} + +const noop = (value: RecordValue): RecordValue => { + return value +} +export const toBoolean = (value: RecordValue): RecordValue => { + switch (value) { + case 't': + return true + case 'f': + return false + default: + return value + } +} +export const toNumber = (value: RecordValue): RecordValue => { + if (typeof value === 'string') { + const parsedValue = parseFloat(value) + if (!Number.isNaN(parsedValue)) { + return parsedValue + } + } + return value +} +export const toJson = (value: RecordValue): RecordValue => { + if (typeof value === 'string') { + try { + return JSON.parse(value) + } catch (error) { + console.log(`JSON parse error: ${error}`) + return value + } + } + return value +} + +/** + * Converts a Postgres Array into a native JS array + * + * @example toArray('{}', 'int4') + * //=> [] + * @example toArray('{"[2021-01-01,2021-12-31)","(2021-01-01,2021-12-32]"}', 'daterange') + * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]'] + * @example toArray([1,2,3,4], 'int4') + * //=> [1,2,3,4] + */ +export const toArray = (value: RecordValue, type: string): RecordValue => { + if (typeof value !== 'string') { + return value + } + + const lastIdx = value.length - 1 + const closeBrace = value[lastIdx] + const openBrace = value[0] + + // Confirm value is a Postgres array by checking curly brackets + if (openBrace === '{' && closeBrace === '}') { + let arr + const valTrim = value.slice(1, lastIdx) + + // TODO: find a better solution to separate Postgres array data + try { + arr = JSON.parse('[' + valTrim + ']') + } catch (_) { + // WARNING: splitting on comma does not cover all edge cases + arr = valTrim ? valTrim.split(',') : [] + } + + return arr.map((val: BaseValue) => convertCell(type, val)) + } + + return value +} + +/** + * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T' + * See https://github.com/supabase/supabase/issues/18 + * + * @example toTimestampString('2019-09-10 00:00:00') + * //=> '2019-09-10T00:00:00' + */ +export const toTimestampString = (value: RecordValue): RecordValue => { + if (typeof value === 'string') { + return value.replace(' ', 'T') + } + + return value +} diff --git a/node_modules/@supabase/realtime-js/src/lib/version.ts b/node_modules/@supabase/realtime-js/src/lib/version.ts new file mode 100644 index 0000000..ad0c3c1 --- /dev/null +++ b/node_modules/@supabase/realtime-js/src/lib/version.ts @@ -0,0 +1 @@ +export const version = '2.7.3' diff --git a/node_modules/@supabase/storage-js/LICENSE b/node_modules/@supabase/storage-js/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/node_modules/@supabase/storage-js/LICENSE @@ -0,0 +1,201 @@ + 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@supabase/storage-js/README.md b/node_modules/@supabase/storage-js/README.md new file mode 100644 index 0000000..d2188b5 --- /dev/null +++ b/node_modules/@supabase/storage-js/README.md @@ -0,0 +1,157 @@ +# `storage-js` + +JS Client library to interact with Supabase Storage. + +- Documentation: https://supabase.io/docs/reference/javascript/storage-createbucket + +## Quick Start Guide + +### Installing the module + +```bash +npm install @supabase/storage-js +``` + +### Connecting to the storage backend + +```js +import { StorageClient } from '@supabase/storage-js' + +const STORAGE_URL = 'https://.supabase.co/storage/v1' +const SERVICE_KEY = '' //! service key, not anon key + +const storageClient = new StorageClient(STORAGE_URL, { + apikey: SERVICE_KEY, + Authorization: `Bearer ${SERVICE_KEY}`, +}) +``` + +### Handling resources + +#### Handling Storage Buckets + +- Create a new Storage bucket: + + ```js + const { data, error } = await storageClient.createBucket( + 'test_bucket', // Bucket name (must be unique) + { public: false } // Bucket options + ) + ``` + +- Retrieve the details of an existing Storage bucket: + + ```js + const { data, error } = await storageClient.getBucket('test_bucket') + ``` + +- Update a new Storage bucket: + + ```js + const { data, error } = await storageClient.updateBucket( + 'test_bucket', // Bucket name + { public: false } // Bucket options + ) + ``` + +- Remove all objects inside a single bucket: + + ```js + const { data, error } = await storageClient.emptyBucket('test_bucket') + ``` + +- Delete an existing bucket (a bucket can't be deleted with existing objects inside it): + + ```js + const { data, error } = await storageClient.deleteBucket('test_bucket') + ``` + +- Retrieve the details of all Storage buckets within an existing project: + + ```js + const { data, error } = await storageClient.listBuckets() + ``` + +#### Handling Files + +- Upload a file to an existing bucket: + + ```js + const fileBody = ... // load your file here + + const { data, error } = await storageClient.from('bucket').upload('path/to/file', fileBody) + ``` + + > Note: + > The path in `data.Key` is prefixed by the bucket ID and is not the value which should be passed to the `download` method in order to fetch the file. + > To fetch the file via the `download` method, use `data.path` and `data.bucketId` as follows: + > + > ```javascript + > const { data, error } = await storageClient.from('bucket').upload('/folder/file.txt', fileBody) + > // check for errors + > const { data2, error2 } = await storageClient.from(data.bucketId).download(data.path) + > ``` + + > Note: The `upload` method also accepts a map of optional parameters. For a complete list see the [Supabase API reference](https://supabase.com/docs/reference/javascript/storage-from-upload). + +- Download a file from an exisiting bucket: + + ```js + const { data, error } = await storageClient.from('bucket').download('path/to/file') + ``` + +- List all the files within a bucket: + + ```js + const { data, error } = await storageClient.from('bucket').list('folder') + ``` + + > Note: The `list` method also accepts a map of optional parameters. For a complete list see the [Supabase API reference](https://supabase.com/docs/reference/javascript/storage-from-list). + +- Replace an existing file at the specified path with a new one: + + ```js + const fileBody = ... // load your file here + + const { data, error } = await storageClient + .from('bucket') + .update('path/to/file', fileBody) + ``` + + > Note: The `upload` method also accepts a map of optional parameters. For a complete list see the [Supabase API reference](https://supabase.com/docs/reference/javascript/storage-from-upload). + +- Move an existing file: + + ```js + const { data, error } = await storageClient + .from('bucket') + .move('old/path/to/file', 'new/path/to/file') + ``` + +- Delete files within the same bucket: + + ```js + const { data, error } = await storageClient.from('bucket').remove(['path/to/file']) + ``` + +- Create signed URL to download file without requiring permissions: + + ```js + const expireIn = 60 + + const { data, error } = await storageClient + .from('bucket') + .createSignedUrl('path/to/file', expireIn) + ``` + +- Retrieve URLs for assets in public buckets: + + ```js + const { data, error } = await storageClient.from('public-bucket').getPublicUrl('path/to/file') + ``` + +## Sponsors + +We are building the features of Firebase using enterprise-grade, open source products. We support existing communities wherever possible, and if the products don’t exist we build them and open source them ourselves. Thanks to these sponsors who are making the OSS ecosystem better for everyone. + +[![New Sponsor](https://user-images.githubusercontent.com/10214025/90518111-e74bbb00-e198-11ea-8f88-c9e3c1aa4b5b.png)](https://github.com/sponsors/supabase) diff --git a/node_modules/@supabase/storage-js/dist/main/StorageClient.d.ts b/node_modules/@supabase/storage-js/dist/main/StorageClient.d.ts new file mode 100644 index 0000000..c2aba35 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/StorageClient.d.ts @@ -0,0 +1,15 @@ +import StorageFileApi from './packages/StorageFileApi'; +import StorageBucketApi from './packages/StorageBucketApi'; +import { Fetch } from './lib/fetch'; +export declare class StorageClient extends StorageBucketApi { + constructor(url: string, headers?: { + [key: string]: string; + }, fetch?: Fetch); + /** + * Perform file operation in a bucket. + * + * @param id The bucket id to operate on. + */ + from(id: string): StorageFileApi; +} +//# sourceMappingURL=StorageClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/StorageClient.d.ts.map b/node_modules/@supabase/storage-js/dist/main/StorageClient.d.ts.map new file mode 100644 index 0000000..4caecbc --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/StorageClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"StorageClient.d.ts","sourceRoot":"","sources":["../../src/StorageClient.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,2BAA2B,CAAA;AACtD,OAAO,gBAAgB,MAAM,6BAA6B,CAAA;AAC1D,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AAEnC,qBAAa,aAAc,SAAQ,gBAAgB;gBACrC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAO,EAAE,KAAK,CAAC,EAAE,KAAK;IAI/E;;;;OAIG;IACH,IAAI,CAAC,EAAE,EAAE,MAAM,GAAG,cAAc;CAGjC"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/StorageClient.js b/node_modules/@supabase/storage-js/dist/main/StorageClient.js new file mode 100644 index 0000000..c5bcb4e --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/StorageClient.js @@ -0,0 +1,23 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StorageClient = void 0; +const StorageFileApi_1 = __importDefault(require("./packages/StorageFileApi")); +const StorageBucketApi_1 = __importDefault(require("./packages/StorageBucketApi")); +class StorageClient extends StorageBucketApi_1.default { + constructor(url, headers = {}, fetch) { + super(url, headers, fetch); + } + /** + * Perform file operation in a bucket. + * + * @param id The bucket id to operate on. + */ + from(id) { + return new StorageFileApi_1.default(this.url, this.headers, id, this.fetch); + } +} +exports.StorageClient = StorageClient; +//# sourceMappingURL=StorageClient.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/StorageClient.js.map b/node_modules/@supabase/storage-js/dist/main/StorageClient.js.map new file mode 100644 index 0000000..071ae9e --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/StorageClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"StorageClient.js","sourceRoot":"","sources":["../../src/StorageClient.ts"],"names":[],"mappings":";;;;;;AAAA,+EAAsD;AACtD,mFAA0D;AAG1D,MAAa,aAAc,SAAQ,0BAAgB;IACjD,YAAY,GAAW,EAAE,UAAqC,EAAE,EAAE,KAAa;QAC7E,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,CAAC,CAAA;IAC5B,CAAC;IAED;;;;OAIG;IACH,IAAI,CAAC,EAAU;QACb,OAAO,IAAI,wBAAc,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC,KAAK,CAAC,CAAA;IACnE,CAAC;CACF;AAbD,sCAaC"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/index.d.ts b/node_modules/@supabase/storage-js/dist/main/index.d.ts new file mode 100644 index 0000000..9548f97 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/index.d.ts @@ -0,0 +1,4 @@ +export { StorageClient as StorageClient } from './StorageClient'; +export * from './lib/types'; +export * from './lib/errors'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/index.d.ts.map b/node_modules/@supabase/storage-js/dist/main/index.d.ts.map new file mode 100644 index 0000000..6d4dcb7 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAChE,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/index.js b/node_modules/@supabase/storage-js/dist/main/index.js new file mode 100644 index 0000000..5bab957 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/index.js @@ -0,0 +1,22 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StorageClient = void 0; +var StorageClient_1 = require("./StorageClient"); +Object.defineProperty(exports, "StorageClient", { enumerable: true, get: function () { return StorageClient_1.StorageClient; } }); +__exportStar(require("./lib/types"), exports); +__exportStar(require("./lib/errors"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/index.js.map b/node_modules/@supabase/storage-js/dist/main/index.js.map new file mode 100644 index 0000000..a840cb9 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,iDAAgE;AAAvD,8GAAA,aAAa,OAAiB;AACvC,8CAA2B;AAC3B,+CAA4B"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/constants.d.ts b/node_modules/@supabase/storage-js/dist/main/lib/constants.d.ts new file mode 100644 index 0000000..12eb562 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/constants.d.ts @@ -0,0 +1,4 @@ +export declare const DEFAULT_HEADERS: { + 'X-Client-Info': string; +}; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/constants.d.ts.map b/node_modules/@supabase/storage-js/dist/main/lib/constants.d.ts.map new file mode 100644 index 0000000..ae818de --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,eAAe;;CAA+C,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/constants.js b/node_modules/@supabase/storage-js/dist/main/lib/constants.js new file mode 100644 index 0000000..b6be886 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/constants.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_HEADERS = void 0; +const version_1 = require("./version"); +exports.DEFAULT_HEADERS = { 'X-Client-Info': `storage-js/${version_1.version}` }; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/constants.js.map b/node_modules/@supabase/storage-js/dist/main/lib/constants.js.map new file mode 100644 index 0000000..a3a2df5 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":";;;AAAA,uCAAmC;AACtB,QAAA,eAAe,GAAG,EAAE,eAAe,EAAE,cAAc,iBAAO,EAAE,EAAE,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/errors.d.ts b/node_modules/@supabase/storage-js/dist/main/lib/errors.d.ts new file mode 100644 index 0000000..ac28bb7 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/errors.d.ts @@ -0,0 +1,19 @@ +export declare class StorageError extends Error { + protected __isStorageError: boolean; + constructor(message: string); +} +export declare function isStorageError(error: unknown): error is StorageError; +export declare class StorageApiError extends StorageError { + status: number; + constructor(message: string, status: number); + toJSON(): { + name: string; + message: string; + status: number; + }; +} +export declare class StorageUnknownError extends StorageError { + originalError: unknown; + constructor(message: string, originalError: unknown); +} +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/errors.d.ts.map b/node_modules/@supabase/storage-js/dist/main/lib/errors.d.ts.map new file mode 100644 index 0000000..13e5846 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,YAAa,SAAQ,KAAK;IACrC,SAAS,CAAC,gBAAgB,UAAO;gBAErB,OAAO,EAAE,MAAM;CAI5B;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,YAAY,CAEpE;AAED,qBAAa,eAAgB,SAAQ,YAAY;IAC/C,MAAM,EAAE,MAAM,CAAA;gBAEF,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAM3C,MAAM;;;;;CAOP;AAED,qBAAa,mBAAoB,SAAQ,YAAY;IACnD,aAAa,EAAE,OAAO,CAAA;gBAEV,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO;CAKpD"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/errors.js b/node_modules/@supabase/storage-js/dist/main/lib/errors.js new file mode 100644 index 0000000..6f48b35 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/errors.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StorageUnknownError = exports.StorageApiError = exports.isStorageError = exports.StorageError = void 0; +class StorageError extends Error { + constructor(message) { + super(message); + this.__isStorageError = true; + this.name = 'StorageError'; + } +} +exports.StorageError = StorageError; +function isStorageError(error) { + return typeof error === 'object' && error !== null && '__isStorageError' in error; +} +exports.isStorageError = isStorageError; +class StorageApiError extends StorageError { + constructor(message, status) { + super(message); + this.name = 'StorageApiError'; + this.status = status; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + }; + } +} +exports.StorageApiError = StorageApiError; +class StorageUnknownError extends StorageError { + constructor(message, originalError) { + super(message); + this.name = 'StorageUnknownError'; + this.originalError = originalError; + } +} +exports.StorageUnknownError = StorageUnknownError; +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/errors.js.map b/node_modules/@supabase/storage-js/dist/main/lib/errors.js.map new file mode 100644 index 0000000..a1c1040 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":";;;AAAA,MAAa,YAAa,SAAQ,KAAK;IAGrC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAA;QAHN,qBAAgB,GAAG,IAAI,CAAA;QAI/B,IAAI,CAAC,IAAI,GAAG,cAAc,CAAA;IAC5B,CAAC;CACF;AAPD,oCAOC;AAED,SAAgB,cAAc,CAAC,KAAc;IAC3C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,kBAAkB,IAAI,KAAK,CAAA;AACnF,CAAC;AAFD,wCAEC;AAED,MAAa,eAAgB,SAAQ,YAAY;IAG/C,YAAY,OAAe,EAAE,MAAc;QACzC,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAA;QAC7B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;IAED,MAAM;QACJ,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,MAAM,EAAE,IAAI,CAAC,MAAM;SACpB,CAAA;IACH,CAAC;CACF;AAhBD,0CAgBC;AAED,MAAa,mBAAoB,SAAQ,YAAY;IAGnD,YAAY,OAAe,EAAE,aAAsB;QACjD,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAA;QACjC,IAAI,CAAC,aAAa,GAAG,aAAa,CAAA;IACpC,CAAC;CACF;AARD,kDAQC"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/fetch.d.ts b/node_modules/@supabase/storage-js/dist/main/lib/fetch.d.ts new file mode 100644 index 0000000..045af69 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/fetch.d.ts @@ -0,0 +1,14 @@ +import { FetchParameters } from './types'; +export declare type Fetch = typeof fetch; +export interface FetchOptions { + headers?: { + [key: string]: string; + }; + noResolveJson?: boolean; +} +export declare type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'DELETE'; +export declare function get(fetcher: Fetch, url: string, options?: FetchOptions, parameters?: FetchParameters): Promise; +export declare function post(fetcher: Fetch, url: string, body: object, options?: FetchOptions, parameters?: FetchParameters): Promise; +export declare function put(fetcher: Fetch, url: string, body: object, options?: FetchOptions, parameters?: FetchParameters): Promise; +export declare function remove(fetcher: Fetch, url: string, body: object, options?: FetchOptions, parameters?: FetchParameters): Promise; +//# sourceMappingURL=fetch.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/fetch.d.ts.map b/node_modules/@supabase/storage-js/dist/main/lib/fetch.d.ts.map new file mode 100644 index 0000000..24d6b60 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/fetch.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAEzC,oBAAY,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC,MAAM,WAAW,YAAY;IAC3B,OAAO,CAAC,EAAE;QACR,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KACtB,CAAA;IACD,aAAa,CAAC,EAAE,OAAO,CAAA;CACxB;AAED,oBAAY,iBAAiB,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAA;AA2DjE,wBAAsB,GAAG,CACvB,OAAO,EAAE,KAAK,EACd,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,YAAY,EACtB,UAAU,CAAC,EAAE,eAAe,GAC3B,OAAO,CAAC,GAAG,CAAC,CAEd;AAED,wBAAsB,IAAI,CACxB,OAAO,EAAE,KAAK,EACd,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,YAAY,EACtB,UAAU,CAAC,EAAE,eAAe,GAC3B,OAAO,CAAC,GAAG,CAAC,CAEd;AAED,wBAAsB,GAAG,CACvB,OAAO,EAAE,KAAK,EACd,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,YAAY,EACtB,UAAU,CAAC,EAAE,eAAe,GAC3B,OAAO,CAAC,GAAG,CAAC,CAEd;AAED,wBAAsB,MAAM,CAC1B,OAAO,EAAE,KAAK,EACd,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,YAAY,EACtB,UAAU,CAAC,EAAE,eAAe,GAC3B,OAAO,CAAC,GAAG,CAAC,CAEd"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/fetch.js b/node_modules/@supabase/storage-js/dist/main/lib/fetch.js new file mode 100644 index 0000000..49e213b --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/fetch.js @@ -0,0 +1,81 @@ +"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 }); +exports.remove = exports.put = exports.post = exports.get = void 0; +const errors_1 = require("./errors"); +const helpers_1 = require("./helpers"); +const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); +const handleError = (error, reject) => __awaiter(void 0, void 0, void 0, function* () { + const Res = yield (0, helpers_1.resolveResponse)(); + if (error instanceof Res) { + error + .json() + .then((err) => { + reject(new errors_1.StorageApiError(_getErrorMessage(err), error.status || 500)); + }) + .catch((err) => { + reject(new errors_1.StorageUnknownError(_getErrorMessage(err), err)); + }); + } + else { + reject(new errors_1.StorageUnknownError(_getErrorMessage(error), error)); + } +}); +const _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === 'GET') { + return params; + } + params.headers = Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + return Object.assign(Object.assign({}, params), parameters); +}; +function _handleRequest(fetcher, method, url, options, parameters, body) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + fetcher(url, _getRequestParams(method, options, parameters, body)) + .then((result) => { + if (!result.ok) + throw result; + if (options === null || options === void 0 ? void 0 : options.noResolveJson) + return result; + return result.json(); + }) + .then((data) => resolve(data)) + .catch((error) => handleError(error, reject)); + }); + }); +} +function get(fetcher, url, options, parameters) { + return __awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'GET', url, options, parameters); + }); +} +exports.get = get; +function post(fetcher, url, body, options, parameters) { + return __awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'POST', url, options, parameters, body); + }); +} +exports.post = post; +function put(fetcher, url, body, options, parameters) { + return __awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'PUT', url, options, parameters, body); + }); +} +exports.put = put; +function remove(fetcher, url, body, options, parameters) { + return __awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'DELETE', url, options, parameters, body); + }); +} +exports.remove = remove; +//# sourceMappingURL=fetch.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/fetch.js.map b/node_modules/@supabase/storage-js/dist/main/lib/fetch.js.map new file mode 100644 index 0000000..4a2a3e1 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/fetch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,qCAA+D;AAC/D,uCAA2C;AAc3C,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAU,EAAE,CAC5C,GAAG,CAAC,GAAG,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d,GAAW,EACX,IAAY,EACZ,OAAsB,EACtB,UAA4B;;QAE5B,OAAO,cAAc,CAAC,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,CAAA;IACvE,CAAC;CAAA;AARD,kBAQC;AAED,SAAsB,MAAM,CAC1B,OAAc,EACd,GAAW,EACX,IAAY,EACZ,OAAsB,EACtB,UAA4B;;QAE5B,OAAO,cAAc,CAAC,OAAO,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,CAAA;IAC1E,CAAC;CAAA;AARD,wBAQC"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/helpers.d.ts b/node_modules/@supabase/storage-js/dist/main/lib/helpers.d.ts new file mode 100644 index 0000000..483ccc3 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/helpers.d.ts @@ -0,0 +1,10 @@ +declare type Fetch = typeof fetch; +export declare const resolveFetch: (customFetch?: typeof fetch | undefined) => Fetch; +export declare const resolveResponse: () => Promise<{ + new (body?: BodyInit | null | undefined, init?: ResponseInit | undefined): Response; + prototype: Response; + error(): Response; + redirect(url: string | URL, status?: number | undefined): Response; +}>; +export {}; +//# sourceMappingURL=helpers.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/helpers.d.ts.map b/node_modules/@supabase/storage-js/dist/main/lib/helpers.d.ts.map new file mode 100644 index 0000000..0c52432 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AAAA,aAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,8CAA0B,KAUlD,CAAA;AAED,eAAO,MAAM,eAAe;;;;;EAM3B,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/helpers.js b/node_modules/@supabase/storage-js/dist/main/lib/helpers.js new file mode 100644 index 0000000..c950e87 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/helpers.js @@ -0,0 +1,57 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +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 }); +exports.resolveResponse = exports.resolveFetch = void 0; +const resolveFetch = (customFetch) => { + let _fetch; + if (customFetch) { + _fetch = customFetch; + } + else if (typeof fetch === 'undefined') { + _fetch = (...args) => __awaiter(void 0, void 0, void 0, function* () { return yield (yield Promise.resolve().then(() => __importStar(require('cross-fetch')))).fetch(...args); }); + } + else { + _fetch = fetch; + } + return (...args) => _fetch(...args); +}; +exports.resolveFetch = resolveFetch; +const resolveResponse = () => __awaiter(void 0, void 0, void 0, function* () { + if (typeof Response === 'undefined') { + return (yield Promise.resolve().then(() => __importStar(require('cross-fetch')))).Response; + } + return Response; +}); +exports.resolveResponse = resolveResponse; +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/helpers.js.map b/node_modules/@supabase/storage-js/dist/main/lib/helpers.js.map new file mode 100644 index 0000000..2676c41 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEO,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAS,EAAE;IACzD,IAAI,MAAa,CAAA;IACjB,IAAI,WAAW,EAAE;QACf,MAAM,GAAG,WAAW,CAAA;KACrB;SAAM,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;QACvC,MAAM,GAAG,CAAO,GAAG,IAAI,EAAE,EAAE,kDAAC,OAAA,MAAM,CAAC,wDAAa,aAAa,GAAC,CAAC,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAA,GAAA,CAAA;KAC/E;SAAM;QACL,MAAM,GAAG,KAAK,CAAA;KACf;IACD,OAAO,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA;AAVY,QAAA,YAAY,gBAUxB;AAEM,MAAM,eAAe,GAAG,GAAS,EAAE;IACxC,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE;QACnC,OAAO,CAAC,wDAAa,aAAa,GAAC,CAAC,CAAC,QAAQ,CAAA;KAC9C;IAED,OAAO,QAAQ,CAAA;AACjB,CAAC,CAAA,CAAA;AANY,QAAA,eAAe,mBAM3B"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/index.d.ts b/node_modules/@supabase/storage-js/dist/main/lib/index.d.ts new file mode 100644 index 0000000..8e2d75b --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/index.d.ts @@ -0,0 +1,5 @@ +export * from '../packages/StorageBucketApi'; +export * from '../packages/StorageFileApi'; +export * from './types'; +export * from './constants'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/index.d.ts.map b/node_modules/@supabase/storage-js/dist/main/lib/index.d.ts.map new file mode 100644 index 0000000..99de246 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/lib/index.ts"],"names":[],"mappings":"AAAA,cAAc,8BAA8B,CAAA;AAC5C,cAAc,4BAA4B,CAAA;AAC1C,cAAc,SAAS,CAAA;AACvB,cAAc,aAAa,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/index.js b/node_modules/@supabase/storage-js/dist/main/lib/index.js new file mode 100644 index 0000000..8317f62 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/index.js @@ -0,0 +1,21 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("../packages/StorageBucketApi"), exports); +__exportStar(require("../packages/StorageFileApi"), exports); +__exportStar(require("./types"), exports); +__exportStar(require("./constants"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/index.js.map b/node_modules/@supabase/storage-js/dist/main/lib/index.js.map new file mode 100644 index 0000000..a65b036 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/lib/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,+DAA4C;AAC5C,6DAA0C;AAC1C,0CAAuB;AACvB,8CAA2B"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/types.d.ts b/node_modules/@supabase/storage-js/dist/main/lib/types.d.ts new file mode 100644 index 0000000..564ac2c --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/types.d.ts @@ -0,0 +1,101 @@ +export interface Bucket { + id: string; + name: string; + owner: string; + file_size_limit?: number; + allowed_mime_types?: string[]; + created_at: string; + updated_at: string; + public: boolean; +} +export interface FileObject { + name: string; + bucket_id: string; + owner: string; + id: string; + updated_at: string; + created_at: string; + last_accessed_at: string; + metadata: Record; + buckets: Bucket; +} +export interface SortBy { + column?: string; + order?: string; +} +export interface FileOptions { + /** + * The number of seconds the asset is cached in the browser and in the Supabase CDN. This is set in the `Cache-Control: max-age=` header. Defaults to 3600 seconds. + */ + cacheControl?: string; + /** + * the `Content-Type` header value. Should be specified if using a `fileBody` that is neither `Blob` nor `File` nor `FormData`, otherwise will default to `text/plain;charset=UTF-8`. + */ + contentType?: string; + /** + * When upsert is set to true, the file is overwritten if it exists. When set to false, an error is thrown if the object already exists. Defaults to false. + */ + upsert?: boolean; + /** + * The duplex option is a string parameter that enables or disables duplex streaming, allowing for both reading and writing data in the same stream. It can be passed as an option to the fetch() method. + */ + duplex?: string; +} +export interface SearchOptions { + /** + * The number of files you want to be returned. + */ + limit?: number; + /** + * The starting position. + */ + offset?: number; + /** + * The column to sort by. Can be any column inside a FileObject. + */ + sortBy?: SortBy; + /** + * The search string to filter files by. + */ + search?: string; +} +export interface FetchParameters { + /** + * Pass in an AbortController's signal to cancel the request. + */ + signal?: AbortSignal; +} +export interface Metadata { + name: string; +} +export interface TransformOptions { + /** + * The width of the image in pixels. + */ + width?: number; + /** + * The height of the image in pixels. + */ + height?: number; + /** + * The resize mode can be cover, contain or fill. Defaults to cover. + * Cover resizes the image to maintain it's aspect ratio while filling the entire width and height. + * Contain resizes the image to maintain it's aspect ratio while fitting the entire image within the width and height. + * Fill resizes the image to fill the entire width and height. If the object's aspect ratio does not match the width and height, the image will be stretched to fit. + */ + resize?: 'cover' | 'contain' | 'fill'; + /** + * Set the quality of the returned image. + * A number from 20 to 100, with 100 being the highest quality. + * Defaults to 80 + */ + quality?: number; + /** + * Specify the format of the image requested. + * + * When using 'origin' we force the format to be the same as the original image. + * When this option is not passed in, images are optimized to modern image formats like Webp. + */ + format?: 'origin'; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/types.d.ts.map b/node_modules/@supabase/storage-js/dist/main/lib/types.d.ts.map new file mode 100644 index 0000000..f50f81b --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,MAAM;IACrB,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;IACb,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,kBAAkB,CAAC,EAAE,MAAM,EAAE,CAAA;IAC7B,UAAU,EAAE,MAAM,CAAA;IAClB,UAAU,EAAE,MAAM,CAAA;IAClB,MAAM,EAAE,OAAO,CAAA;CAChB;AAED,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,MAA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;IACH,MAAM,CAAC,EAAE,QAAQ,CAAA;CAClB"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/types.js b/node_modules/@supabase/storage-js/dist/main/lib/types.js new file mode 100644 index 0000000..11e638d --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/types.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/types.js.map b/node_modules/@supabase/storage-js/dist/main/lib/types.js.map new file mode 100644 index 0000000..5bb5e4d --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/version.d.ts b/node_modules/@supabase/storage-js/dist/main/lib/version.d.ts new file mode 100644 index 0000000..be5367d --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.5.1"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/version.d.ts.map b/node_modules/@supabase/storage-js/dist/main/lib/version.d.ts.map new file mode 100644 index 0000000..808651b --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,OAAO,UAAU,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/version.js b/node_modules/@supabase/storage-js/dist/main/lib/version.js new file mode 100644 index 0000000..1126779 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/version.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.version = void 0; +// generated by genversion +exports.version = '2.5.1'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/lib/version.js.map b/node_modules/@supabase/storage-js/dist/main/lib/version.js.map new file mode 100644 index 0000000..e2c13c2 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/lib/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":";;;AAAA,0BAA0B;AACb,QAAA,OAAO,GAAG,OAAO,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/packages/StorageBucketApi.d.ts b/node_modules/@supabase/storage-js/dist/main/packages/StorageBucketApi.d.ts new file mode 100644 index 0000000..4c71b97 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/packages/StorageBucketApi.d.ts @@ -0,0 +1,114 @@ +import { StorageError } from '../lib/errors'; +import { Fetch } from '../lib/fetch'; +import { Bucket } from '../lib/types'; +export default class StorageBucketApi { + protected url: string; + protected headers: { + [key: string]: string; + }; + protected fetch: Fetch; + constructor(url: string, headers?: { + [key: string]: string; + }, fetch?: Fetch); + /** + * Retrieves the details of all Storage buckets within an existing project. + */ + listBuckets(): Promise<{ + data: Bucket[]; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Retrieves the details of an existing Storage bucket. + * + * @param id The unique identifier of the bucket you would like to retrieve. + */ + getBucket(id: string): Promise<{ + data: Bucket; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Creates a new Storage bucket + * + * @param id A unique identifier for the bucket you are creating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + * @returns newly created bucket id + */ + createBucket(id: string, options?: { + public: boolean; + fileSizeLimit?: number | string | null; + allowedMimeTypes?: string[] | null; + }): Promise<{ + data: Pick; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Updates a Storage bucket + * + * @param id A unique identifier for the bucket you are updating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + */ + updateBucket(id: string, options: { + public: boolean; + fileSizeLimit?: number | string | null; + allowedMimeTypes?: string[] | null; + }): Promise<{ + data: { + message: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Removes all objects inside a single bucket. + * + * @param id The unique identifier of the bucket you would like to empty. + */ + emptyBucket(id: string): Promise<{ + data: { + message: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. + * You must first `empty()` the bucket. + * + * @param id The unique identifier of the bucket you would like to delete. + */ + deleteBucket(id: string): Promise<{ + data: { + message: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; +} +//# sourceMappingURL=StorageBucketApi.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/packages/StorageBucketApi.d.ts.map b/node_modules/@supabase/storage-js/dist/main/packages/StorageBucketApi.d.ts.map new file mode 100644 index 0000000..5e555b4 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/packages/StorageBucketApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"StorageBucketApi.d.ts","sourceRoot":"","sources":["../../../src/packages/StorageB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I,CAAA;KACZ,GACD;QACE,IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;IAwBD;;;;;;;;;;;OAWG;IACG,YAAY,CAChB,EAAE,EAAE,MAAM,EACV,OAAO,EAAE;QACP,MAAM,EAAE,OAAO,CAAA;QACf,aAAa,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAA;QACtC,gBAAgB,CAAC,EAAE,MAAM,EAAE,GAAG,IAAI,CAAA;KACnC,GACA,OAAO,CACN;QACE,IAAI,EAAE;YAAE,OAAO,EAAE,MAAM,CAAA;SAAE,CAAA;QACzB,KAAK,EAAE,IAAI,CAAA;KACZ,GACD;QACE,IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;IAwBD;;;;OAIG;IACG,WAAW,CACf,EAAE,EAAE,MAAM,GACT,OAAO,CACN;QACE,IAAI,EAAE;YAAE,OAAO,EAAE,MAAM,CAAA;SAAE,CAAA;QACzB,KAAK,EAAE,IAAI,CAAA;KACZ,GACD;QACE,IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;IAkBD;;;;;OAKG;IACG,YAAY,CAChB,EAAE,EAAE,MAAM,GACT,OAAO,CACN;QACE,IAAI,EAAE;YAAE,OAAO,EAAE,MAAM,CAAA;SAAE,CAAA;QACzB,KAAK,EAAE,IAAI,CAAA;KACZ,GACD;QACE,IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;CAiBF"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/packages/StorageBucketApi.js b/node_modules/@supabase/storage-js/dist/main/packages/StorageBucketApi.js new file mode 100644 index 0000000..718675e --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/packages/StorageBucketApi.js @@ -0,0 +1,166 @@ +"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 constants_1 = require("../lib/constants"); +const errors_1 = require("../lib/errors"); +const fetch_1 = require("../lib/fetch"); +const helpers_1 = require("../lib/helpers"); +class StorageBucketApi { + constructor(url, headers = {}, fetch) { + this.url = url; + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch); + } + /** + * Retrieves the details of all Storage buckets within an existing project. + */ + listBuckets() { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket`, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Retrieves the details of an existing Storage bucket. + * + * @param id The unique identifier of the bucket you would like to retrieve. + */ + getBucket(id) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket/${id}`, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a new Storage bucket + * + * @param id A unique identifier for the bucket you are creating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + * @returns newly created bucket id + */ + createBucket(id, options = { + public: false, + }) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket`, { + id, + name: id, + public: options.public, + file_size_limit: options.fileSizeLimit, + allowed_mime_types: options.allowedMimeTypes, + }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Updates a Storage bucket + * + * @param id A unique identifier for the bucket you are updating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + */ + updateBucket(id, options) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.put)(this.fetch, `${this.url}/bucket/${id}`, { + id, + name: id, + public: options.public, + file_size_limit: options.fileSizeLimit, + allowed_mime_types: options.allowedMimeTypes, + }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Removes all objects inside a single bucket. + * + * @param id The unique identifier of the bucket you would like to empty. + */ + emptyBucket(id) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket/${id}/empty`, {}, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. + * You must first `empty()` the bucket. + * + * @param id The unique identifier of the bucket you would like to delete. + */ + deleteBucket(id) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/bucket/${id}`, {}, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } +} +exports.default = StorageBucketApi; +//# sourceMappingURL=StorageBucketApi.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/packages/StorageBucketApi.js.map b/node_modules/@supabase/storage-js/dist/main/packages/StorageBucketApi.js.map new file mode 100644 index 0000000..bf4f37d --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/packages/StorageBucketApi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"StorageBucketApi.js","sourceRoot":"","sources":["../../../src/packages/StorageBucketApi.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,gDAAkD;AAClD,0CAA4D;AAC5D,wCAA4D;AAC5D,4CAA6C;AAG7C,MAAqB,gBAAgB;IAKnC,YAAY,GAAW,EAAE,UAAqC,EAAE,EAAE,KAAa;QAC7E,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,OAAO,mCAAQ,2BAAe,GAAK,OAAO,CAAE,CAAA;QACjD,IAAI,CAAC,KAAK,GAAG,IAAA,sBAAY,EAAC,KAAK,CAAC,CAAA;IAClC,CAAC;IAED;;OAEG;IACG,WAAW;;YAUf,IAAI;gBACF,MAAM,IAAI,GAAG,MAAM,IAAA,WAAG,EAAC,IAAI,CAAC,KAAK,EAAE,GAAG,IAAI,CAAC,GAAG,SAAS,EAAE,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,CAAA;gBACnF,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;aAC7B;YAAC,OAAO,KAAK,EAAE;gBACd,IAAI,IAAA,uBAAc,EAAC,KAAK,CAAC,EAAE;oBACzB,OAAO,EAAE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YAWV,IAAI;gBACF,MAAM,IAAI,GAAG,MAAM,IAAA,cAAM,EACvB,IAAI,CAAC,KAAK,EACV,GAAG,IAAI,CAAC,GAAG,WAAW,EAAE,EAAE,EAC1B,EAAE,EACF,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAC1B,CAAA;gBACD,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;aAC7B;YAAC,OAAO,KAAK,EAAE;gBACd,IAAI,IAAA,uBAAc,EAAC,KAAK,CAAC,EAAE;oBACzB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;iBAC7B;gBAED,MAAM,KAAK,CAAA;aACZ;QACH,CAAC;KAAA;CACF;AAhPD,mCAgPC"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/packages/StorageFileApi.d.ts b/node_modules/@supabase/storage-js/dist/main/packages/StorageFileApi.d.ts new file mode 100644 index 0000000..210d2a1 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/packages/StorageFileApi.d.ts @@ -0,0 +1,224 @@ +/// +import { StorageError } from '../lib/errors'; +import { Fetch } from '../lib/fetch'; +import { FileObject, FileOptions, SearchOptions, FetchParameters, TransformOptions } from '../lib/types'; +declare type FileBody = ArrayBuffer | ArrayBufferView | Blob | Buffer | File | FormData | NodeJS.ReadableStream | ReadableStream | URLSearchParams | string; +export default class StorageFileApi { + protected url: string; + protected headers: { + [key: string]: string; + }; + protected bucketId?: string; + protected fetch: Fetch; + constructor(url: string, headers?: { + [key: string]: string; + }, bucketId?: string, fetch?: Fetch); + /** + * Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one. + * + * @param method HTTP method. + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + private uploadOrUpdate; + /** + * Uploads a file to an existing bucket. + * + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + upload(path: string, fileBody: FileBody, fileOptions?: FileOptions): Promise<{ + data: { + path: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Upload a file with a token generated from `createSignedUploadUrl`. + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param token The token generated from `createSignedUploadUrl` + * @param fileBody The body of the file to be stored in the bucket. + */ + uploadToSignedUrl(path: string, token: string, fileBody: FileBody, fileOptions?: FileOptions): Promise<{ + data: { + path: string; + }; + error: null; + } | { + data: null; + error: any; + }>; + /** + * Creates a signed upload URL. + * Signed upload URLs can be used to upload files to the bucket without further authentication. + * They are valid for one minute. + * @param path The file path, including the current file name. For example `folder/image.png`. + */ + createSignedUploadUrl(path: string): Promise<{ + data: { + signedUrl: string; + token: string; + path: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Replaces an existing file at the specified path with a new one. + * + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update. + * @param fileBody The body of the file to be stored in the bucket. + */ + update(path: string, fileBody: ArrayBuffer | ArrayBufferView | Blob | Buffer | File | FormData | NodeJS.ReadableStream | ReadableStream | URLSearchParams | string, fileOptions?: FileOptions): Promise<{ + data: { + path: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Moves an existing file to a new path in the same bucket. + * + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-new.png`. + */ + move(fromPath: string, toPath: string): Promise<{ + data: { + message: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Copies an existing file to a new path in the same bucket. + * + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-copy.png`. + */ + copy(fromPath: string, toPath: string): Promise<{ + data: { + path: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Creates a signed URL. Use a signed URL to share a file for a fixed amount of time. + * + * @param path The file path, including the current file name. For example `folder/image.png`. + * @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + */ + createSignedUrl(path: string, expiresIn: number, options?: { + download?: string | boolean; + transform?: TransformOptions; + }): Promise<{ + data: { + signedUrl: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time. + * + * @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`. + * @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + */ + createSignedUrls(paths: string[], expiresIn: number, options?: { + download: string | boolean; + }): Promise<{ + data: { + error: string | null; + path: string | null; + signedUrl: string; + }[]; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead. + * + * @param path The full path and file name of the file to be downloaded. For example `folder/image.png`. + * @param options.transform Transform the asset before serving it to the client. + */ + download(path: string, options?: { + transform?: TransformOptions; + }): Promise<{ + data: Blob; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset. + * This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset. + * + * @param path The path and name of the file to generate the public URL for. For example `folder/image.png`. + * @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + */ + getPublicUrl(path: string, options?: { + download?: string | boolean; + transform?: TransformOptions; + }): { + data: { + publicUrl: string; + }; + }; + /** + * Deletes files within the same bucket + * + * @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`]. + */ + remove(paths: string[]): Promise<{ + data: FileObject[]; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Get file metadata + * @param id the file id to retrieve metadata + */ + /** + * Update file metadata + * @param id the file id to update metadata + * @param meta the new file metadata + */ + /** + * Lists all the files within a bucket. + * @param path The folder path. + */ + list(path?: string, options?: SearchOptions, parameters?: FetchParameters): Promise<{ + data: FileObject[]; + error: null; + } | { + data: null; + error: StorageError; + }>; + private _getFinalPath; + private _removeEmptyFolders; + private transformOptsToQueryString; +} +export {}; +//# sourceMappingURL=StorageFileApi.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/packages/StorageFileApi.d.ts.map b/node_modules/@supabase/storage-js/dist/main/packages/StorageFileApi.d.ts.map new file mode 100644 index 0000000..ba43696 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/packages/StorageFileApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"StorageFileApi.d.ts","sourceRoot":"","sources":["../../../src/packages/StorageFileApi.ts"],"names":[],"mappings":";AAAA,OAAO,EAAkB,YAAY,EAAE,MAAM,eAAe,CAAA;AAC5D,OAAO,EAAE,KAAK,EAAqB,MAAM,cAAc,CAAA;AAEvD,OAAO,EACL,UAAU,EACV,WAAW,EACX,aAAa,EACb,eAAe,EACf,gBAAgB,EACjB,MAAM,cAAc,CAAA;AAiBrB,aAAK,QAAQ,GACT,WAAW,GACX,eAAe,GACf,IAAI,GACJ,MAAM,GACN,IAAI,GACJ,QAAQ,GACR,MAAM,CAAC,cAAc,GACrB,cAAc,CAAC,UAAU,CAAC,GAC1B,eAAe,GACf,MAAM,CAAA;AAEV,MAAM,CAAC,OAAO,OAAO,cAAc;IACjC,SAAS,CAAC,GAAG,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAA;IAC5C,SAAS,CAAC,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AAU,EAAE,CAAA;QAClB,KAAK,EAAE,IAAI,CAAA;KACZ,GACD;QACE,IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;IAoBD,OAAO,CAAC,aAAa;IAIrB,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,0BAA0B;CAwBnC"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/packages/StorageFileApi.js b/node_modules/@supabase/storage-js/dist/main/packages/StorageFileApi.js new file mode 100644 index 0000000..60365e1 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/packages/StorageFileApi.js @@ -0,0 +1,467 @@ +"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 errors_1 = require("../lib/errors"); +const fetch_1 = require("../lib/fetch"); +const helpers_1 = require("../lib/helpers"); +const DEFAULT_SEARCH_OPTIONS = { + limit: 100, + offset: 0, + sortBy: { + column: 'name', + order: 'asc', + }, +}; +const DEFAULT_FILE_OPTIONS = { + cacheControl: '3600', + contentType: 'text/plain;charset=UTF-8', + upsert: false, +}; +class StorageFileApi { + constructor(url, headers = {}, bucketId, fetch) { + this.url = url; + this.headers = headers; + this.bucketId = bucketId; + this.fetch = (0, helpers_1.resolveFetch)(fetch); + } + /** + * Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one. + * + * @param method HTTP method. + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + uploadOrUpdate(method, path, fileBody, fileOptions) { + return __awaiter(this, void 0, void 0, function* () { + try { + let body; + const options = Object.assign(Object.assign({}, DEFAULT_FILE_OPTIONS), fileOptions); + const headers = Object.assign(Object.assign({}, this.headers), (method === 'POST' && { 'x-upsert': String(options.upsert) })); + if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { + body = new FormData(); + body.append('cacheControl', options.cacheControl); + body.append('', fileBody); + } + else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { + body = fileBody; + body.append('cacheControl', options.cacheControl); + } + else { + body = fileBody; + headers['cache-control'] = `max-age=${options.cacheControl}`; + headers['content-type'] = options.contentType; + } + const cleanPath = this._removeEmptyFolders(path); + const _path = this._getFinalPath(cleanPath); + const res = yield this.fetch(`${this.url}/object/${_path}`, Object.assign({ method, body: body, headers }, ((options === null || options === void 0 ? void 0 : options.duplex) ? { duplex: options.duplex } : {}))); + if (res.ok) { + return { + data: { path: cleanPath }, + error: null, + }; + } + else { + const error = yield res.json(); + return { data: null, error }; + } + } + catch (error) { + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Uploads a file to an existing bucket. + * + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + upload(path, fileBody, fileOptions) { + return __awaiter(this, void 0, void 0, function* () { + return this.uploadOrUpdate('POST', path, fileBody, fileOptions); + }); + } + /** + * Upload a file with a token generated from `createSignedUploadUrl`. + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param token The token generated from `createSignedUploadUrl` + * @param fileBody The body of the file to be stored in the bucket. + */ + uploadToSignedUrl(path, token, fileBody, fileOptions) { + return __awaiter(this, void 0, void 0, function* () { + const cleanPath = this._removeEmptyFolders(path); + const _path = this._getFinalPath(cleanPath); + const url = new URL(this.url + `/object/upload/sign/${_path}`); + url.searchParams.set('token', token); + try { + let body; + const options = Object.assign({ upsert: DEFAULT_FILE_OPTIONS.upsert }, fileOptions); + const headers = Object.assign(Object.assign({}, this.headers), { 'x-upsert': String(options.upsert) }); + if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { + body = new FormData(); + body.append('cacheControl', options.cacheControl); + body.append('', fileBody); + } + else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { + body = fileBody; + body.append('cacheControl', options.cacheControl); + } + else { + body = fileBody; + headers['cache-control'] = `max-age=${options.cacheControl}`; + headers['content-type'] = options.contentType; + } + const res = yield this.fetch(url.toString(), { + method: 'PUT', + body: body, + headers, + }); + if (res.ok) { + return { + data: { path: cleanPath }, + error: null, + }; + } + else { + const error = yield res.json(); + return { data: null, error }; + } + } + catch (error) { + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a signed upload URL. + * Signed upload URLs can be used to upload files to the bucket without further authentication. + * They are valid for one minute. + * @param path The file path, including the current file name. For example `folder/image.png`. + */ + createSignedUploadUrl(path) { + return __awaiter(this, void 0, void 0, function* () { + try { + let _path = this._getFinalPath(path); + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/upload/sign/${_path}`, {}, { headers: this.headers }); + const url = new URL(this.url + data.url); + const token = url.searchParams.get('token'); + if (!token) { + throw new errors_1.StorageError('No token returned by API'); + } + return { data: { signedUrl: url.toString(), path, token }, error: null }; + } + catch (error) { + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Replaces an existing file at the specified path with a new one. + * + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update. + * @param fileBody The body of the file to be stored in the bucket. + */ + update(path, fileBody, fileOptions) { + return __awaiter(this, void 0, void 0, function* () { + return this.uploadOrUpdate('PUT', path, fileBody, fileOptions); + }); + } + /** + * Moves an existing file to a new path in the same bucket. + * + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-new.png`. + */ + move(fromPath, toPath) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/move`, { bucketId: this.bucketId, sourceKey: fromPath, destinationKey: toPath }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Copies an existing file to a new path in the same bucket. + * + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-copy.png`. + */ + copy(fromPath, toPath) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/copy`, { bucketId: this.bucketId, sourceKey: fromPath, destinationKey: toPath }, { headers: this.headers }); + return { data: { path: data.Key }, error: null }; + } + catch (error) { + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a signed URL. Use a signed URL to share a file for a fixed amount of time. + * + * @param path The file path, including the current file name. For example `folder/image.png`. + * @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + */ + createSignedUrl(path, expiresIn, options) { + return __awaiter(this, void 0, void 0, function* () { + try { + let _path = this._getFinalPath(path); + let data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${_path}`, Object.assign({ expiresIn }, ((options === null || options === void 0 ? void 0 : options.transform) ? { transform: options.transform } : {})), { headers: this.headers }); + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) + ? `&download=${options.download === true ? '' : options.download}` + : ''; + const signedUrl = encodeURI(`${this.url}${data.signedURL}${downloadQueryParam}`); + data = { signedUrl }; + return { data, error: null }; + } + catch (error) { + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time. + * + * @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`. + * @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + */ + createSignedUrls(paths, expiresIn, options) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${this.bucketId}`, { expiresIn, paths }, { headers: this.headers }); + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) + ? `&download=${options.download === true ? '' : options.download}` + : ''; + return { + data: data.map((datum) => (Object.assign(Object.assign({}, datum), { signedUrl: datum.signedURL + ? encodeURI(`${this.url}${datum.signedURL}${downloadQueryParam}`) + : null }))), + error: null, + }; + } + catch (error) { + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead. + * + * @param path The full path and file name of the file to be downloaded. For example `folder/image.png`. + * @param options.transform Transform the asset before serving it to the client. + */ + download(path, options) { + return __awaiter(this, void 0, void 0, function* () { + const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined'; + const renderPath = wantsTransformation ? 'render/image/authenticated' : 'object'; + const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); + const queryString = transformationQuery ? `?${transformationQuery}` : ''; + try { + const _path = this._getFinalPath(path); + const res = yield (0, fetch_1.get)(this.fetch, `${this.url}/${renderPath}/${_path}${queryString}`, { + headers: this.headers, + noResolveJson: true, + }); + const data = yield res.blob(); + return { data, error: null }; + } + catch (error) { + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset. + * This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset. + * + * @param path The path and name of the file to generate the public URL for. For example `folder/image.png`. + * @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + */ + getPublicUrl(path, options) { + const _path = this._getFinalPath(path); + const _queryString = []; + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) + ? `download=${options.download === true ? '' : options.download}` + : ''; + if (downloadQueryParam !== '') { + _queryString.push(downloadQueryParam); + } + const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined'; + const renderPath = wantsTransformation ? 'render/image' : 'object'; + const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); + if (transformationQuery !== '') { + _queryString.push(transformationQuery); + } + let queryString = _queryString.join('&'); + if (queryString !== '') { + queryString = `?${queryString}`; + } + return { + data: { publicUrl: encodeURI(`${this.url}/${renderPath}/public/${_path}${queryString}`) }, + }; + } + /** + * Deletes files within the same bucket + * + * @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`]. + */ + remove(paths) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/object/${this.bucketId}`, { prefixes: paths }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Get file metadata + * @param id the file id to retrieve metadata + */ + // async getMetadata( + // id: string + // ): Promise< + // | { + // data: Metadata + // error: null + // } + // | { + // data: null + // error: StorageError + // } + // > { + // try { + // const data = await get(this.fetch, `${this.url}/metadata/${id}`, { headers: this.headers }) + // return { data, error: null } + // } catch (error) { + // if (isStorageError(error)) { + // return { data: null, error } + // } + // throw error + // } + // } + /** + * Update file metadata + * @param id the file id to update metadata + * @param meta the new file metadata + */ + // async updateMetadata( + // id: string, + // meta: Metadata + // ): Promise< + // | { + // data: Metadata + // error: null + // } + // | { + // data: null + // error: StorageError + // } + // > { + // try { + // const data = await post( + // this.fetch, + // `${this.url}/metadata/${id}`, + // { ...meta }, + // { headers: this.headers } + // ) + // return { data, error: null } + // } catch (error) { + // if (isStorageError(error)) { + // return { data: null, error } + // } + // throw error + // } + // } + /** + * Lists all the files within a bucket. + * @param path The folder path. + */ + list(path, options, parameters) { + return __awaiter(this, void 0, void 0, function* () { + try { + const body = Object.assign(Object.assign(Object.assign({}, DEFAULT_SEARCH_OPTIONS), options), { prefix: path || '' }); + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/list/${this.bucketId}`, body, { headers: this.headers }, parameters); + return { data, error: null }; + } + catch (error) { + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + _getFinalPath(path) { + return `${this.bucketId}/${path}`; + } + _removeEmptyFolders(path) { + return path.replace(/^\/|\/$/g, '').replace(/\/+/g, '/'); + } + transformOptsToQueryString(transform) { + const params = []; + if (transform.width) { + params.push(`width=${transform.width}`); + } + if (transform.height) { + params.push(`height=${transform.height}`); + } + if (transform.resize) { + params.push(`resize=${transform.resize}`); + } + if (transform.format) { + params.push(`format=${transform.format}`); + } + if (transform.quality) { + params.push(`quality=${transform.quality}`); + } + return params.join('&'); + } +} +exports.default = StorageFileApi; +//# sourceMappingURL=StorageFileApi.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/main/packages/StorageFileApi.js.map b/node_modules/@supabase/storage-js/dist/main/packages/StorageFileApi.js.map new file mode 100644 index 0000000..6aaa0e3 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/main/packages/StorageFileApi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"StorageFileApi.js","sourceRoot":"","sources":["../../../src/packages/StorageFileApi.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,0CAA4D;AAC5D,wCAAuD;AACvD,4CAA6C;AAS7C,MAAM,sBAAsB,GAAG;IAC7B,KAAK,EAAE,GAAG;IACV,MAAM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AA;SACxC;QAED,IAAI,SAAS,CAAC,MAAM,EAAE;YACpB,MAAM,CAAC,IAAI,CAAC,UAAU,SAAS,CAAC,MAAM,EAAE,CAAC,CAAA;SAC1C;QAED,IAAI,SAAS,CAAC,MAAM,EAAE;YACpB,MAAM,CAAC,IAAI,CAAC,UAAU,SAAS,CAAC,MAAM,EAAE,CAAC,CAAA;SAC1C;QAED,IAAI,SAAS,CAAC,MAAM,EAAE;YACpB,MAAM,CAAC,IAAI,CAAC,UAAU,SAAS,CAAC,MAAM,EAAE,CAAC,CAAA;SAC1C;QAED,IAAI,SAAS,CAAC,OAAO,EAAE;YACrB,MAAM,CAAC,IAAI,CAAC,WAAW,SAAS,CAAC,OAAO,EAAE,CAAC,CAAA;SAC5C;QAED,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;IACzB,CAAC;CACF;AA7pBD,iCA6pBC"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/StorageClient.d.ts b/node_modules/@supabase/storage-js/dist/module/StorageClient.d.ts new file mode 100644 index 0000000..c2aba35 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/StorageClient.d.ts @@ -0,0 +1,15 @@ +import StorageFileApi from './packages/StorageFileApi'; +import StorageBucketApi from './packages/StorageBucketApi'; +import { Fetch } from './lib/fetch'; +export declare class StorageClient extends StorageBucketApi { + constructor(url: string, headers?: { + [key: string]: string; + }, fetch?: Fetch); + /** + * Perform file operation in a bucket. + * + * @param id The bucket id to operate on. + */ + from(id: string): StorageFileApi; +} +//# sourceMappingURL=StorageClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/StorageClient.d.ts.map b/node_modules/@supabase/storage-js/dist/module/StorageClient.d.ts.map new file mode 100644 index 0000000..4caecbc --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/StorageClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"StorageClient.d.ts","sourceRoot":"","sources":["../../src/StorageClient.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,2BAA2B,CAAA;AACtD,OAAO,gBAAgB,MAAM,6BAA6B,CAAA;AAC1D,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AAEnC,qBAAa,aAAc,SAAQ,gBAAgB;gBACrC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAO,EAAE,KAAK,CAAC,EAAE,KAAK;IAI/E;;;;OAIG;IACH,IAAI,CAAC,EAAE,EAAE,MAAM,GAAG,cAAc;CAGjC"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/StorageClient.js b/node_modules/@supabase/storage-js/dist/module/StorageClient.js new file mode 100644 index 0000000..39e819f --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/StorageClient.js @@ -0,0 +1,16 @@ +import StorageFileApi from './packages/StorageFileApi'; +import StorageBucketApi from './packages/StorageBucketApi'; +export class StorageClient extends StorageBucketApi { + constructor(url, headers = {}, fetch) { + super(url, headers, fetch); + } + /** + * Perform file operation in a bucket. + * + * @param id The bucket id to operate on. + */ + from(id) { + return new StorageFileApi(this.url, this.headers, id, this.fetch); + } +} +//# sourceMappingURL=StorageClient.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/StorageClient.js.map b/node_modules/@supabase/storage-js/dist/module/StorageClient.js.map new file mode 100644 index 0000000..1d02426 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/StorageClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"StorageClient.js","sourceRoot":"","sources":["../../src/StorageClient.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,2BAA2B,CAAA;AACtD,OAAO,gBAAgB,MAAM,6BAA6B,CAAA;AAG1D,MAAM,OAAO,aAAc,SAAQ,gBAAgB;IACjD,YAAY,GAAW,EAAE,UAAqC,EAAE,EAAE,KAAa;QAC7E,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,CAAC,CAAA;IAC5B,CAAC;IAED;;;;OAIG;IACH,IAAI,CAAC,EAAU;QACb,OAAO,IAAI,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC,KAAK,CAAC,CAAA;IACnE,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/index.d.ts b/node_modules/@supabase/storage-js/dist/module/index.d.ts new file mode 100644 index 0000000..9548f97 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/index.d.ts @@ -0,0 +1,4 @@ +export { StorageClient as StorageClient } from './StorageClient'; +export * from './lib/types'; +export * from './lib/errors'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/index.d.ts.map b/node_modules/@supabase/storage-js/dist/module/index.d.ts.map new file mode 100644 index 0000000..6d4dcb7 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAChE,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/index.js b/node_modules/@supabase/storage-js/dist/module/index.js new file mode 100644 index 0000000..4ca3452 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/index.js @@ -0,0 +1,4 @@ +export { StorageClient as StorageClient } from './StorageClient'; +export * from './lib/types'; +export * from './lib/errors'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/index.js.map b/node_modules/@supabase/storage-js/dist/module/index.js.map new file mode 100644 index 0000000..a2f53e8 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAChE,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/constants.d.ts b/node_modules/@supabase/storage-js/dist/module/lib/constants.d.ts new file mode 100644 index 0000000..12eb562 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/constants.d.ts @@ -0,0 +1,4 @@ +export declare const DEFAULT_HEADERS: { + 'X-Client-Info': string; +}; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/constants.d.ts.map b/node_modules/@supabase/storage-js/dist/module/lib/constants.d.ts.map new file mode 100644 index 0000000..ae818de --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,eAAe;;CAA+C,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/constants.js b/node_modules/@supabase/storage-js/dist/module/lib/constants.js new file mode 100644 index 0000000..0801769 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/constants.js @@ -0,0 +1,3 @@ +import { version } from './version'; +export const DEFAULT_HEADERS = { 'X-Client-Info': `storage-js/${version}` }; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/constants.js.map b/node_modules/@supabase/storage-js/dist/module/lib/constants.js.map new file mode 100644 index 0000000..1b5c14d --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACnC,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,eAAe,EAAE,cAAc,OAAO,EAAE,EAAE,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/errors.d.ts b/node_modules/@supabase/storage-js/dist/module/lib/errors.d.ts new file mode 100644 index 0000000..ac28bb7 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/errors.d.ts @@ -0,0 +1,19 @@ +export declare class StorageError extends Error { + protected __isStorageError: boolean; + constructor(message: string); +} +export declare function isStorageError(error: unknown): error is StorageError; +export declare class StorageApiError extends StorageError { + status: number; + constructor(message: string, status: number); + toJSON(): { + name: string; + message: string; + status: number; + }; +} +export declare class StorageUnknownError extends StorageError { + originalError: unknown; + constructor(message: string, originalError: unknown); +} +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/errors.d.ts.map b/node_modules/@supabase/storage-js/dist/module/lib/errors.d.ts.map new file mode 100644 index 0000000..13e5846 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,YAAa,SAAQ,KAAK;IACrC,SAAS,CAAC,gBAAgB,UAAO;gBAErB,OAAO,EAAE,MAAM;CAI5B;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,YAAY,CAEpE;AAED,qBAAa,eAAgB,SAAQ,YAAY;IAC/C,MAAM,EAAE,MAAM,CAAA;gBAEF,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAM3C,MAAM;;;;;CAOP;AAED,qBAAa,mBAAoB,SAAQ,YAAY;IACnD,aAAa,EAAE,OAAO,CAAA;gBAEV,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO;CAKpD"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/errors.js b/node_modules/@supabase/storage-js/dist/module/lib/errors.js new file mode 100644 index 0000000..0288fa3 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/errors.js @@ -0,0 +1,32 @@ +export class StorageError extends Error { + constructor(message) { + super(message); + this.__isStorageError = true; + this.name = 'StorageError'; + } +} +export function isStorageError(error) { + return typeof error === 'object' && error !== null && '__isStorageError' in error; +} +export class StorageApiError extends StorageError { + constructor(message, status) { + super(message); + this.name = 'StorageApiError'; + this.status = status; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + }; + } +} +export class StorageUnknownError extends StorageError { + constructor(message, originalError) { + super(message); + this.name = 'StorageUnknownError'; + this.originalError = originalError; + } +} +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/errors.js.map b/node_modules/@supabase/storage-js/dist/module/lib/errors.js.map new file mode 100644 index 0000000..ab54f13 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,YAAa,SAAQ,KAAK;IAGrC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAA;QAHN,qBAAgB,GAAG,IAAI,CAAA;QAI/B,IAAI,CAAC,IAAI,GAAG,cAAc,CAAA;IAC5B,CAAC;CACF;AAED,MAAM,UAAU,cAAc,CAAC,KAAc;IAC3C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,kBAAkB,IAAI,KAAK,CAAA;AACnF,CAAC;AAED,MAAM,OAAO,eAAgB,SAAQ,YAAY;IAG/C,YAAY,OAAe,EAAE,MAAc;QACzC,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAA;QAC7B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;IAED,MAAM;QACJ,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,MAAM,EAAE,IAAI,CAAC,MAAM;SACpB,CAAA;IACH,CAAC;CACF;AAED,MAAM,OAAO,mBAAoB,SAAQ,YAAY;IAGnD,YAAY,OAAe,EAAE,aAAsB;QACjD,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAA;QACjC,IAAI,CAAC,aAAa,GAAG,aAAa,CAAA;IACpC,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/fetch.d.ts b/node_modules/@supabase/storage-js/dist/module/lib/fetch.d.ts new file mode 100644 index 0000000..045af69 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/fetch.d.ts @@ -0,0 +1,14 @@ +import { FetchParameters } from './types'; +export declare type Fetch = typeof fetch; +export interface FetchOptions { + headers?: { + [key: string]: string; + }; + noResolveJson?: boolean; +} +export declare type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'DELETE'; +export declare function get(fetcher: Fetch, url: string, options?: FetchOptions, parameters?: FetchParameters): Promise; +export declare function post(fetcher: Fetch, url: string, body: object, options?: FetchOptions, parameters?: FetchParameters): Promise; +export declare function put(fetcher: Fetch, url: string, body: object, options?: FetchOptions, parameters?: FetchParameters): Promise; +export declare function remove(fetcher: Fetch, url: string, body: object, options?: FetchOptions, parameters?: FetchParameters): Promise; +//# sourceMappingURL=fetch.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/fetch.d.ts.map b/node_modules/@supabase/storage-js/dist/module/lib/fetch.d.ts.map new file mode 100644 index 0000000..24d6b60 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/fetch.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAEzC,oBAAY,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC,MAAM,WAAW,YAAY;IAC3B,OAAO,CAAC,EAAE;QACR,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KACtB,CAAA;IACD,aAAa,CAAC,EAAE,OAAO,CAAA;CACxB;AAED,oBAAY,iBAAiB,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAA;AA2DjE,wBAAsB,GAAG,CACvB,OAAO,EAAE,KAAK,EACd,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,YAAY,EACtB,UAAU,CAAC,EAAE,eAAe,GAC3B,OAAO,CAAC,GAAG,CAAC,CAEd;AAED,wBAAsB,IAAI,CACxB,OAAO,EAAE,KAAK,EACd,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,YAAY,EACtB,UAAU,CAAC,EAAE,eAAe,GAC3B,OAAO,CAAC,GAAG,CAAC,CAEd;AAED,wBAAsB,GAAG,CACvB,OAAO,EAAE,KAAK,EACd,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,YAAY,EACtB,UAAU,CAAC,EAAE,eAAe,GAC3B,OAAO,CAAC,GAAG,CAAC,CAEd;AAED,wBAAsB,MAAM,CAC1B,OAAO,EAAE,KAAK,EACd,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,YAAY,EACtB,UAAU,CAAC,EAAE,eAAe,GAC3B,OAAO,CAAC,GAAG,CAAC,CAEd"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/fetch.js b/node_modules/@supabase/storage-js/dist/module/lib/fetch.js new file mode 100644 index 0000000..58c3449 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/fetch.js @@ -0,0 +1,74 @@ +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 { StorageApiError, StorageUnknownError } from './errors'; +import { resolveResponse } from './helpers'; +const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); +const handleError = (error, reject) => __awaiter(void 0, void 0, void 0, function* () { + const Res = yield resolveResponse(); + if (error instanceof Res) { + error + .json() + .then((err) => { + reject(new StorageApiError(_getErrorMessage(err), error.status || 500)); + }) + .catch((err) => { + reject(new StorageUnknownError(_getErrorMessage(err), err)); + }); + } + else { + reject(new StorageUnknownError(_getErrorMessage(error), error)); + } +}); +const _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === 'GET') { + return params; + } + params.headers = Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + return Object.assign(Object.assign({}, params), parameters); +}; +function _handleRequest(fetcher, method, url, options, parameters, body) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + fetcher(url, _getRequestParams(method, options, parameters, body)) + .then((result) => { + if (!result.ok) + throw result; + if (options === null || options === void 0 ? void 0 : options.noResolveJson) + return result; + return result.json(); + }) + .then((data) => resolve(data)) + .catch((error) => handleError(error, reject)); + }); + }); +} +export function get(fetcher, url, options, parameters) { + return __awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'GET', url, options, parameters); + }); +} +export function post(fetcher, url, body, options, parameters) { + return __awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'POST', url, options, parameters, body); + }); +} +export function put(fetcher, url, body, options, parameters) { + return __awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'PUT', url, options, parameters, body); + }); +} +export function remove(fetcher, url, body, options, parameters) { + return __awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'DELETE', url, options, parameters, body); + }); +} +//# sourceMappingURL=fetch.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/fetch.js.map b/node_modules/@supabase/storage-js/dist/module/lib/fetch.js.map new file mode 100644 index 0000000..ceb6c68 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/fetch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAA;AAC/D,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAA;AAc3C,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAU,EAAE,CAC5C,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,OAAO,IAAI,GAAG,CAAC,iBAAiB,IAAI,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAA;AAErF,MAAM,WAAW,GAAG,CAAO,KAAc,EAAE,MAA8B,EAAE,EAAE;IAC3E,MAAM,GAAG,GAAG,MAAM,eAAe,EAAE,CAAA;IAEnC,IAAI,KAAK,YAAY,GAAG,EAAE;QACxB,KAAK;aACF,IAAI,EAAE;aACN,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE;YACZ,MAAM,CAAC,IAAI,eAAe,CAAC,gBAAgB,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAA;QACzE,CAAC,CAAC;aACD,KAAK,CAAC,CAA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MAAM,CAAA;gBACzC,OAAO,MAAM,CAAC,IAAI,EAAE,CAAA;YACtB,CAAC,CAAC;iBACD,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;iBAC7B,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,WAAW,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAA;QACjD,CAAC,CAAC,CAAA;IACJ,CAAC;CAAA;AAED,MAAM,UAAgB,GAAG,CACvB,OAAc,EACd,GAAW,EACX,OAAsB,EACtB,UAA4B;;QAE5B,OAAO,cAAc,CAAC,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,UAAU,CAAC,CAAA;IACjE,CAAC;CAAA;AAED,MAAM,UAAgB,IAAI,CACxB,OAAc,EACd,GAAW,EACX,IAAY,EACZ,OAAsB,EACtB,UAA4B;;QAE5B,OAAO,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,CAAA;IACxE,CAAC;CAAA;AAED,MAAM,UAAgB,GAAG,CACvB,OAAc,EACd,GAAW,EACX,IAAY,EACZ,OAAsB,EACtB,UAA4B;;QAE5B,OAAO,cAAc,CAAC,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,CAAA;IACvE,CAAC;CAAA;AAED,MAAM,UAAgB,MAAM,CAC1B,OAAc,EACd,GAAW,EACX,IAAY,EACZ,OAAsB,EACtB,UAA4B;;QAE5B,OAAO,cAAc,CAAC,OAAO,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,CAAA;IAC1E,CAAC;CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/helpers.d.ts b/node_modules/@supabase/storage-js/dist/module/lib/helpers.d.ts new file mode 100644 index 0000000..483ccc3 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/helpers.d.ts @@ -0,0 +1,10 @@ +declare type Fetch = typeof fetch; +export declare const resolveFetch: (customFetch?: typeof fetch | undefined) => Fetch; +export declare const resolveResponse: () => Promise<{ + new (body?: BodyInit | null | undefined, init?: ResponseInit | undefined): Response; + prototype: Response; + error(): Response; + redirect(url: string | URL, status?: number | undefined): Response; +}>; +export {}; +//# sourceMappingURL=helpers.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/helpers.d.ts.map b/node_modules/@supabase/storage-js/dist/module/lib/helpers.d.ts.map new file mode 100644 index 0000000..0c52432 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AAAA,aAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,8CAA0B,KAUlD,CAAA;AAED,eAAO,MAAM,eAAe;;;;;EAM3B,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/helpers.js b/node_modules/@supabase/storage-js/dist/module/lib/helpers.js new file mode 100644 index 0000000..3835e41 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/helpers.js @@ -0,0 +1,29 @@ +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()); + }); +}; +export const resolveFetch = (customFetch) => { + let _fetch; + if (customFetch) { + _fetch = customFetch; + } + else if (typeof fetch === 'undefined') { + _fetch = (...args) => __awaiter(void 0, void 0, void 0, function* () { return yield (yield import('cross-fetch')).fetch(...args); }); + } + else { + _fetch = fetch; + } + return (...args) => _fetch(...args); +}; +export const resolveResponse = () => __awaiter(void 0, void 0, void 0, function* () { + if (typeof Response === 'undefined') { + return (yield import('cross-fetch')).Response; + } + return Response; +}); +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/helpers.js.map b/node_modules/@supabase/storage-js/dist/module/lib/helpers.js.map new file mode 100644 index 0000000..6b64422 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":";;;;;;;;;AAEA,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAS,EAAE;IACzD,IAAI,MAAa,CAAA;IACjB,IAAI,WAAW,EAAE;QACf,MAAM,GAAG,WAAW,CAAA;KACrB;SAAM,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;QACvC,MAAM,GAAG,CAAO,GAAG,IAAI,EAAE,EAAE,kDAAC,OAAA,MAAM,CAAC,MAAM,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAA,GAAA,CAAA;KAC/E;SAAM;QACL,MAAM,GAAG,KAAK,CAAA;KACf;IACD,OAAO,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,eAAe,GAAG,GAAS,EAAE;IACxC,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE;QACnC,OAAO,CAAC,MAAM,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,QAAQ,CAAA;KAC9C;IAED,OAAO,QAAQ,CAAA;AACjB,CAAC,CAAA,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/index.d.ts b/node_modules/@supabase/storage-js/dist/module/lib/index.d.ts new file mode 100644 index 0000000..8e2d75b --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/index.d.ts @@ -0,0 +1,5 @@ +export * from '../packages/StorageBucketApi'; +export * from '../packages/StorageFileApi'; +export * from './types'; +export * from './constants'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/index.d.ts.map b/node_modules/@supabase/storage-js/dist/module/lib/index.d.ts.map new file mode 100644 index 0000000..99de246 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/lib/index.ts"],"names":[],"mappings":"AAAA,cAAc,8BAA8B,CAAA;AAC5C,cAAc,4BAA4B,CAAA;AAC1C,cAAc,SAAS,CAAA;AACvB,cAAc,aAAa,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/index.js b/node_modules/@supabase/storage-js/dist/module/lib/index.js new file mode 100644 index 0000000..51094d4 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/index.js @@ -0,0 +1,5 @@ +export * from '../packages/StorageBucketApi'; +export * from '../packages/StorageFileApi'; +export * from './types'; +export * from './constants'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/index.js.map b/node_modules/@supabase/storage-js/dist/module/lib/index.js.map new file mode 100644 index 0000000..368ef64 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/lib/index.ts"],"names":[],"mappings":"AAAA,cAAc,8BAA8B,CAAA;AAC5C,cAAc,4BAA4B,CAAA;AAC1C,cAAc,SAAS,CAAA;AACvB,cAAc,aAAa,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/types.d.ts b/node_modules/@supabase/storage-js/dist/module/lib/types.d.ts new file mode 100644 index 0000000..564ac2c --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/types.d.ts @@ -0,0 +1,101 @@ +export interface Bucket { + id: string; + name: string; + owner: string; + file_size_limit?: number; + allowed_mime_types?: string[]; + created_at: string; + updated_at: string; + public: boolean; +} +export interface FileObject { + name: string; + bucket_id: string; + owner: string; + id: string; + updated_at: string; + created_at: string; + last_accessed_at: string; + metadata: Record; + buckets: Bucket; +} +export interface SortBy { + column?: string; + order?: string; +} +export interface FileOptions { + /** + * The number of seconds the asset is cached in the browser and in the Supabase CDN. This is set in the `Cache-Control: max-age=` header. Defaults to 3600 seconds. + */ + cacheControl?: string; + /** + * the `Content-Type` header value. Should be specified if using a `fileBody` that is neither `Blob` nor `File` nor `FormData`, otherwise will default to `text/plain;charset=UTF-8`. + */ + contentType?: string; + /** + * When upsert is set to true, the file is overwritten if it exists. When set to false, an error is thrown if the object already exists. Defaults to false. + */ + upsert?: boolean; + /** + * The duplex option is a string parameter that enables or disables duplex streaming, allowing for both reading and writing data in the same stream. It can be passed as an option to the fetch() method. + */ + duplex?: string; +} +export interface SearchOptions { + /** + * The number of files you want to be returned. + */ + limit?: number; + /** + * The starting position. + */ + offset?: number; + /** + * The column to sort by. Can be any column inside a FileObject. + */ + sortBy?: SortBy; + /** + * The search string to filter files by. + */ + search?: string; +} +export interface FetchParameters { + /** + * Pass in an AbortController's signal to cancel the request. + */ + signal?: AbortSignal; +} +export interface Metadata { + name: string; +} +export interface TransformOptions { + /** + * The width of the image in pixels. + */ + width?: number; + /** + * The height of the image in pixels. + */ + height?: number; + /** + * The resize mode can be cover, contain or fill. Defaults to cover. + * Cover resizes the image to maintain it's aspect ratio while filling the entire width and height. + * Contain resizes the image to maintain it's aspect ratio while fitting the entire image within the width and height. + * Fill resizes the image to fill the entire width and height. If the object's aspect ratio does not match the width and height, the image will be stretched to fit. + */ + resize?: 'cover' | 'contain' | 'fill'; + /** + * Set the quality of the returned image. + * A number from 20 to 100, with 100 being the highest quality. + * Defaults to 80 + */ + quality?: number; + /** + * Specify the format of the image requested. + * + * When using 'origin' we force the format to be the same as the original image. + * When this option is not passed in, images are optimized to modern image formats like Webp. + */ + format?: 'origin'; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/types.d.ts.map b/node_modules/@supabase/storage-js/dist/module/lib/types.d.ts.map new file mode 100644 index 0000000..f50f81b --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,MAAM;IACrB,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;IACb,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,kBAAkB,CAAC,EAAE,MAAM,EAAE,CAAA;IAC7B,UAAU,EAAE,MAAM,CAAA;IAClB,UAAU,EAAE,MAAM,CAAA;IAClB,MAAM,EAAE,OAAO,CAAA;CAChB;AAED,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,MAAM,CAAA;IACZ,SAAS,EAAE,MAAM,CAAA;IACjB,KAAK,EAAE,MAAM,CAAA;IACb,EAAE,EAAE,MAAM,CAAA;IACV,UAAU,EAAE,MAAM,CAAA;IAClB,UAAU,EAAE,MAAM,CAAA;IAClB,gBAAgB,EAAE,MAAM,CAAA;IACxB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC7B,OAAO,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,WAAW,MAAM;IACrB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,KAAK,CAAC,EAAE,MAAM,CAAA;CACf;AAED,MAAM,WAAW,WAAW;IAC1B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB;;OAEG;IACH,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,WAAW,aAAa;IAC5B;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAA;IAEd;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IAEf;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IAEf;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,WAAW,eAAe;IAC9B;;OAEG;IACH,MAAM,CAAC,EAAE,WAAW,CAAA;CACrB;AAGD,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAA;CACb;AAED,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAA;IACd;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IACf;;;;;OAKG;IACH,MAAM,CAAC,EAAE,OAAO,GAAG,SAAS,GAAG,MAAM,CAAA;IACrC;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;;;;OAKG;IACH,MAAM,CAAC,EAAE,QAAQ,CAAA;CAClB"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/types.js b/node_modules/@supabase/storage-js/dist/module/lib/types.js new file mode 100644 index 0000000..718fd38 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/types.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/types.js.map b/node_modules/@supabase/storage-js/dist/module/lib/types.js.map new file mode 100644 index 0000000..5bb5e4d --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/version.d.ts b/node_modules/@supabase/storage-js/dist/module/lib/version.d.ts new file mode 100644 index 0000000..be5367d --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.5.1"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/version.d.ts.map b/node_modules/@supabase/storage-js/dist/module/lib/version.d.ts.map new file mode 100644 index 0000000..808651b --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,OAAO,UAAU,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/version.js b/node_modules/@supabase/storage-js/dist/module/lib/version.js new file mode 100644 index 0000000..184a263 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/version.js @@ -0,0 +1,3 @@ +// generated by genversion +export const version = '2.5.1'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/lib/version.js.map b/node_modules/@supabase/storage-js/dist/module/lib/version.js.map new file mode 100644 index 0000000..9f2f247 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/lib/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAAA,0BAA0B;AAC1B,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/packages/StorageBucketApi.d.ts b/node_modules/@supabase/storage-js/dist/module/packages/StorageBucketApi.d.ts new file mode 100644 index 0000000..4c71b97 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/packages/StorageBucketApi.d.ts @@ -0,0 +1,114 @@ +import { StorageError } from '../lib/errors'; +import { Fetch } from '../lib/fetch'; +import { Bucket } from '../lib/types'; +export default class StorageBucketApi { + protected url: string; + protected headers: { + [key: string]: string; + }; + protected fetch: Fetch; + constructor(url: string, headers?: { + [key: string]: string; + }, fetch?: Fetch); + /** + * Retrieves the details of all Storage buckets within an existing project. + */ + listBuckets(): Promise<{ + data: Bucket[]; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Retrieves the details of an existing Storage bucket. + * + * @param id The unique identifier of the bucket you would like to retrieve. + */ + getBucket(id: string): Promise<{ + data: Bucket; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Creates a new Storage bucket + * + * @param id A unique identifier for the bucket you are creating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + * @returns newly created bucket id + */ + createBucket(id: string, options?: { + public: boolean; + fileSizeLimit?: number | string | null; + allowedMimeTypes?: string[] | null; + }): Promise<{ + data: Pick; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Updates a Storage bucket + * + * @param id A unique identifier for the bucket you are updating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + */ + updateBucket(id: string, options: { + public: boolean; + fileSizeLimit?: number | string | null; + allowedMimeTypes?: string[] | null; + }): Promise<{ + data: { + message: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Removes all objects inside a single bucket. + * + * @param id The unique identifier of the bucket you would like to empty. + */ + emptyBucket(id: string): Promise<{ + data: { + message: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. + * You must first `empty()` the bucket. + * + * @param id The unique identifier of the bucket you would like to delete. + */ + deleteBucket(id: string): Promise<{ + data: { + message: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; +} +//# sourceMappingURL=StorageBucketApi.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/packages/StorageBucketApi.d.ts.map b/node_modules/@supabase/storage-js/dist/module/packages/StorageBucketApi.d.ts.map new file mode 100644 index 0000000..5e555b4 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/packages/StorageBucketApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"StorageBucketApi.d.ts","sourceRoot":"","sources":["../../../src/packages/StorageBucketApi.ts"],"names":[],"mappings":"AACA,OAAO,EAAkB,YAAY,EAAE,MAAM,eAAe,CAAA;AAC5D,OAAO,EAAE,KAAK,EAA0B,MAAM,cAAc,CAAA;AAE5D,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAErC,MAAM,CAAC,OAAO,OAAO,gBAAgB;IACnC,SAAS,CAAC,GAAG,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAA;IAC5C,SAAS,CAAC,KAAK,EAAE,KAAK,CAAA;gBAEV,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAO,EAAE,KAAK,CAAC,EAAE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D;;;;OAIG;IACG,WAAW,CACf,EAAE,EAAE,MAAM,GACT,OAAO,CACN;QACE,IAAI,EAAE;YAAE,OAAO,EAAE,MAAM,CAAA;SAAE,CAAA;QACzB,KAAK,EAAE,IAAI,CAAA;KACZ,GACD;QACE,IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;IAkBD;;;;;OAKG;IACG,YAAY,CAChB,EAAE,EAAE,MAAM,GACT,OAAO,CACN;QACE,IAAI,EAAE;YAAE,OAAO,EAAE,MAAM,CAAA;SAAE,CAAA;QACzB,KAAK,EAAE,IAAI,CAAA;KACZ,GACD;QACE,IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;CAiBF"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/packages/StorageBucketApi.js b/node_modules/@supabase/storage-js/dist/module/packages/StorageBucketApi.js new file mode 100644 index 0000000..6c6e3b7 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/packages/StorageBucketApi.js @@ -0,0 +1,163 @@ +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 { DEFAULT_HEADERS } from '../lib/constants'; +import { isStorageError } from '../lib/errors'; +import { get, post, put, remove } from '../lib/fetch'; +import { resolveFetch } from '../lib/helpers'; +export default class StorageBucketApi { + constructor(url, headers = {}, fetch) { + this.url = url; + this.headers = Object.assign(Object.assign({}, DEFAULT_HEADERS), headers); + this.fetch = resolveFetch(fetch); + } + /** + * Retrieves the details of all Storage buckets within an existing project. + */ + listBuckets() { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield get(this.fetch, `${this.url}/bucket`, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Retrieves the details of an existing Storage bucket. + * + * @param id The unique identifier of the bucket you would like to retrieve. + */ + getBucket(id) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield get(this.fetch, `${this.url}/bucket/${id}`, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a new Storage bucket + * + * @param id A unique identifier for the bucket you are creating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + * @returns newly created bucket id + */ + createBucket(id, options = { + public: false, + }) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield post(this.fetch, `${this.url}/bucket`, { + id, + name: id, + public: options.public, + file_size_limit: options.fileSizeLimit, + allowed_mime_types: options.allowedMimeTypes, + }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Updates a Storage bucket + * + * @param id A unique identifier for the bucket you are updating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + */ + updateBucket(id, options) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield put(this.fetch, `${this.url}/bucket/${id}`, { + id, + name: id, + public: options.public, + file_size_limit: options.fileSizeLimit, + allowed_mime_types: options.allowedMimeTypes, + }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Removes all objects inside a single bucket. + * + * @param id The unique identifier of the bucket you would like to empty. + */ + emptyBucket(id) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield post(this.fetch, `${this.url}/bucket/${id}/empty`, {}, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. + * You must first `empty()` the bucket. + * + * @param id The unique identifier of the bucket you would like to delete. + */ + deleteBucket(id) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield remove(this.fetch, `${this.url}/bucket/${id}`, {}, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } +} +//# sourceMappingURL=StorageBucketApi.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/packages/StorageBucketApi.js.map b/node_modules/@supabase/storage-js/dist/module/packages/StorageBucketApi.js.map new file mode 100644 index 0000000..fdf95cf --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/packages/StorageBucketApi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"StorageBucketApi.js","sourceRoot":"","sources":["../../../src/packages/StorageBucketApi.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAClD,OAAO,EAAE,cAAc,EAAgB,MAAM,eAAe,CAAA;AAC5D,OAAO,EAAS,GAAG,EAAE,IAAI,EAAE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KAAK,CAAC,EAAE;oBACzB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;iBAC7B;gBAED,MAAM,KAAK,CAAA;aACZ;QACH,CAAC;KAAA;IAED;;;;OAIG;IACG,WAAW,CACf,EAAU;;YAWV,IAAI;gBACF,MAAM,IAAI,GAAG,MAAM,IAAI,CACrB,IAAI,CAAC,KAAK,EACV,GAAG,IAAI,CAAC,GAAG,WAAW,EAAE,QAAQ,EAChC,EAAE,EACF,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAC1B,CAAA;gBACD,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;aAC7B;YAAC,OAAO,KAAK,EAAE;gBACd,IAAI,cAAc,CAAC,KAAK,CAAC,EAAE;oBACzB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;iBAC7B;gBAED,MAAM,KAAK,CAAA;aACZ;QACH,CAAC;KAAA;IAED;;;;;OAKG;IACG,YAAY,CAChB,EAAU;;YAWV,IAAI;gBACF,MAAM,IAAI,GAAG,MAAM,MAAM,CACvB,IAAI,CAAC,KAAK,EACV,GAAG,IAAI,CAAC,GAAG,WAAW,EAAE,EAAE,EAC1B,EAAE,EACF,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAC1B,CAAA;gBACD,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;aAC7B;YAAC,OAAO,KAAK,EAAE;gBACd,IAAI,cAAc,CAAC,KAAK,CAAC,EAAE;oBACzB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAA;iBAC7B;gBAED,MAAM,KAAK,CAAA;aACZ;QACH,CAAC;KAAA;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/packages/StorageFileApi.d.ts b/node_modules/@supabase/storage-js/dist/module/packages/StorageFileApi.d.ts new file mode 100644 index 0000000..210d2a1 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/packages/StorageFileApi.d.ts @@ -0,0 +1,224 @@ +/// +import { StorageError } from '../lib/errors'; +import { Fetch } from '../lib/fetch'; +import { FileObject, FileOptions, SearchOptions, FetchParameters, TransformOptions } from '../lib/types'; +declare type FileBody = ArrayBuffer | ArrayBufferView | Blob | Buffer | File | FormData | NodeJS.ReadableStream | ReadableStream | URLSearchParams | string; +export default class StorageFileApi { + protected url: string; + protected headers: { + [key: string]: string; + }; + protected bucketId?: string; + protected fetch: Fetch; + constructor(url: string, headers?: { + [key: string]: string; + }, bucketId?: string, fetch?: Fetch); + /** + * Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one. + * + * @param method HTTP method. + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + private uploadOrUpdate; + /** + * Uploads a file to an existing bucket. + * + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + upload(path: string, fileBody: FileBody, fileOptions?: FileOptions): Promise<{ + data: { + path: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Upload a file with a token generated from `createSignedUploadUrl`. + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param token The token generated from `createSignedUploadUrl` + * @param fileBody The body of the file to be stored in the bucket. + */ + uploadToSignedUrl(path: string, token: string, fileBody: FileBody, fileOptions?: FileOptions): Promise<{ + data: { + path: string; + }; + error: null; + } | { + data: null; + error: any; + }>; + /** + * Creates a signed upload URL. + * Signed upload URLs can be used to upload files to the bucket without further authentication. + * They are valid for one minute. + * @param path The file path, including the current file name. For example `folder/image.png`. + */ + createSignedUploadUrl(path: string): Promise<{ + data: { + signedUrl: string; + token: string; + path: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Replaces an existing file at the specified path with a new one. + * + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update. + * @param fileBody The body of the file to be stored in the bucket. + */ + update(path: string, fileBody: ArrayBuffer | ArrayBufferView | Blob | Buffer | File | FormData | NodeJS.ReadableStream | ReadableStream | URLSearchParams | string, fileOptions?: FileOptions): Promise<{ + data: { + path: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Moves an existing file to a new path in the same bucket. + * + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-new.png`. + */ + move(fromPath: string, toPath: string): Promise<{ + data: { + message: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Copies an existing file to a new path in the same bucket. + * + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-copy.png`. + */ + copy(fromPath: string, toPath: string): Promise<{ + data: { + path: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Creates a signed URL. Use a signed URL to share a file for a fixed amount of time. + * + * @param path The file path, including the current file name. For example `folder/image.png`. + * @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + */ + createSignedUrl(path: string, expiresIn: number, options?: { + download?: string | boolean; + transform?: TransformOptions; + }): Promise<{ + data: { + signedUrl: string; + }; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time. + * + * @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`. + * @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + */ + createSignedUrls(paths: string[], expiresIn: number, options?: { + download: string | boolean; + }): Promise<{ + data: { + error: string | null; + path: string | null; + signedUrl: string; + }[]; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead. + * + * @param path The full path and file name of the file to be downloaded. For example `folder/image.png`. + * @param options.transform Transform the asset before serving it to the client. + */ + download(path: string, options?: { + transform?: TransformOptions; + }): Promise<{ + data: Blob; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset. + * This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset. + * + * @param path The path and name of the file to generate the public URL for. For example `folder/image.png`. + * @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + */ + getPublicUrl(path: string, options?: { + download?: string | boolean; + transform?: TransformOptions; + }): { + data: { + publicUrl: string; + }; + }; + /** + * Deletes files within the same bucket + * + * @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`]. + */ + remove(paths: string[]): Promise<{ + data: FileObject[]; + error: null; + } | { + data: null; + error: StorageError; + }>; + /** + * Get file metadata + * @param id the file id to retrieve metadata + */ + /** + * Update file metadata + * @param id the file id to update metadata + * @param meta the new file metadata + */ + /** + * Lists all the files within a bucket. + * @param path The folder path. + */ + list(path?: string, options?: SearchOptions, parameters?: FetchParameters): Promise<{ + data: FileObject[]; + error: null; + } | { + data: null; + error: StorageError; + }>; + private _getFinalPath; + private _removeEmptyFolders; + private transformOptsToQueryString; +} +export {}; +//# sourceMappingURL=StorageFileApi.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/packages/StorageFileApi.d.ts.map b/node_modules/@supabase/storage-js/dist/module/packages/StorageFileApi.d.ts.map new file mode 100644 index 0000000..ba43696 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/packages/StorageFileApi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file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IACH,YAAY,CACV,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;QAAC,SAAS,CAAC,EAAE,gBAAgB,CAAA;KAAE,GACtE;QAAE,IAAI,EAAE;YAAE,SAAS,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE;IA8BlC;;;;OAIG;IACG,MAAM,CACV,KAAK,EAAE,MAAM,EAAE,GACd,OAAO,CACN;QACE,IAAI,EAAE,UAAU,EAAE,CAAA;QAClB,KAAK,EAAE,IAAI,CAAA;KACZ,GACD;QACE,IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;IAkBD;;;OAGG;IAyBH;;;;OAIG;IA+BH;;;OAGG;IACG,IAAI,CACR,IAAI,CAAC,EAAE,MAAM,EACb,OAAO,CAAC,EAAE,aAAa,EACvB,UAAU,CAAC,EAAE,eAAe,GAC3B,OAAO,CACN;QACE,IAAI,EAAE,UAAU,EAAE,CAAA;QAClB,KAAK,EAAE,IAAI,CAAA;KACZ,GACD;QACE,IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;IAoBD,OAAO,CAAC,aAAa;IAIrB,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,0BAA0B;CAwBnC"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/packages/StorageFileApi.js b/node_modules/@supabase/storage-js/dist/module/packages/StorageFileApi.js new file mode 100644 index 0000000..689fd9e --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/packages/StorageFileApi.js @@ -0,0 +1,464 @@ +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 { isStorageError, StorageError } from '../lib/errors'; +import { get, post, remove } from '../lib/fetch'; +import { resolveFetch } from '../lib/helpers'; +const DEFAULT_SEARCH_OPTIONS = { + limit: 100, + offset: 0, + sortBy: { + column: 'name', + order: 'asc', + }, +}; +const DEFAULT_FILE_OPTIONS = { + cacheControl: '3600', + contentType: 'text/plain;charset=UTF-8', + upsert: false, +}; +export default class StorageFileApi { + constructor(url, headers = {}, bucketId, fetch) { + this.url = url; + this.headers = headers; + this.bucketId = bucketId; + this.fetch = resolveFetch(fetch); + } + /** + * Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one. + * + * @param method HTTP method. + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + uploadOrUpdate(method, path, fileBody, fileOptions) { + return __awaiter(this, void 0, void 0, function* () { + try { + let body; + const options = Object.assign(Object.assign({}, DEFAULT_FILE_OPTIONS), fileOptions); + const headers = Object.assign(Object.assign({}, this.headers), (method === 'POST' && { 'x-upsert': String(options.upsert) })); + if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { + body = new FormData(); + body.append('cacheControl', options.cacheControl); + body.append('', fileBody); + } + else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { + body = fileBody; + body.append('cacheControl', options.cacheControl); + } + else { + body = fileBody; + headers['cache-control'] = `max-age=${options.cacheControl}`; + headers['content-type'] = options.contentType; + } + const cleanPath = this._removeEmptyFolders(path); + const _path = this._getFinalPath(cleanPath); + const res = yield this.fetch(`${this.url}/object/${_path}`, Object.assign({ method, body: body, headers }, ((options === null || options === void 0 ? void 0 : options.duplex) ? { duplex: options.duplex } : {}))); + if (res.ok) { + return { + data: { path: cleanPath }, + error: null, + }; + } + else { + const error = yield res.json(); + return { data: null, error }; + } + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Uploads a file to an existing bucket. + * + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + upload(path, fileBody, fileOptions) { + return __awaiter(this, void 0, void 0, function* () { + return this.uploadOrUpdate('POST', path, fileBody, fileOptions); + }); + } + /** + * Upload a file with a token generated from `createSignedUploadUrl`. + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param token The token generated from `createSignedUploadUrl` + * @param fileBody The body of the file to be stored in the bucket. + */ + uploadToSignedUrl(path, token, fileBody, fileOptions) { + return __awaiter(this, void 0, void 0, function* () { + const cleanPath = this._removeEmptyFolders(path); + const _path = this._getFinalPath(cleanPath); + const url = new URL(this.url + `/object/upload/sign/${_path}`); + url.searchParams.set('token', token); + try { + let body; + const options = Object.assign({ upsert: DEFAULT_FILE_OPTIONS.upsert }, fileOptions); + const headers = Object.assign(Object.assign({}, this.headers), { 'x-upsert': String(options.upsert) }); + if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { + body = new FormData(); + body.append('cacheControl', options.cacheControl); + body.append('', fileBody); + } + else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { + body = fileBody; + body.append('cacheControl', options.cacheControl); + } + else { + body = fileBody; + headers['cache-control'] = `max-age=${options.cacheControl}`; + headers['content-type'] = options.contentType; + } + const res = yield this.fetch(url.toString(), { + method: 'PUT', + body: body, + headers, + }); + if (res.ok) { + return { + data: { path: cleanPath }, + error: null, + }; + } + else { + const error = yield res.json(); + return { data: null, error }; + } + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a signed upload URL. + * Signed upload URLs can be used to upload files to the bucket without further authentication. + * They are valid for one minute. + * @param path The file path, including the current file name. For example `folder/image.png`. + */ + createSignedUploadUrl(path) { + return __awaiter(this, void 0, void 0, function* () { + try { + let _path = this._getFinalPath(path); + const data = yield post(this.fetch, `${this.url}/object/upload/sign/${_path}`, {}, { headers: this.headers }); + const url = new URL(this.url + data.url); + const token = url.searchParams.get('token'); + if (!token) { + throw new StorageError('No token returned by API'); + } + return { data: { signedUrl: url.toString(), path, token }, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Replaces an existing file at the specified path with a new one. + * + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update. + * @param fileBody The body of the file to be stored in the bucket. + */ + update(path, fileBody, fileOptions) { + return __awaiter(this, void 0, void 0, function* () { + return this.uploadOrUpdate('PUT', path, fileBody, fileOptions); + }); + } + /** + * Moves an existing file to a new path in the same bucket. + * + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-new.png`. + */ + move(fromPath, toPath) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield post(this.fetch, `${this.url}/object/move`, { bucketId: this.bucketId, sourceKey: fromPath, destinationKey: toPath }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Copies an existing file to a new path in the same bucket. + * + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-copy.png`. + */ + copy(fromPath, toPath) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield post(this.fetch, `${this.url}/object/copy`, { bucketId: this.bucketId, sourceKey: fromPath, destinationKey: toPath }, { headers: this.headers }); + return { data: { path: data.Key }, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a signed URL. Use a signed URL to share a file for a fixed amount of time. + * + * @param path The file path, including the current file name. For example `folder/image.png`. + * @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + */ + createSignedUrl(path, expiresIn, options) { + return __awaiter(this, void 0, void 0, function* () { + try { + let _path = this._getFinalPath(path); + let data = yield post(this.fetch, `${this.url}/object/sign/${_path}`, Object.assign({ expiresIn }, ((options === null || options === void 0 ? void 0 : options.transform) ? { transform: options.transform } : {})), { headers: this.headers }); + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) + ? `&download=${options.download === true ? '' : options.download}` + : ''; + const signedUrl = encodeURI(`${this.url}${data.signedURL}${downloadQueryParam}`); + data = { signedUrl }; + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time. + * + * @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`. + * @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + */ + createSignedUrls(paths, expiresIn, options) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield post(this.fetch, `${this.url}/object/sign/${this.bucketId}`, { expiresIn, paths }, { headers: this.headers }); + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) + ? `&download=${options.download === true ? '' : options.download}` + : ''; + return { + data: data.map((datum) => (Object.assign(Object.assign({}, datum), { signedUrl: datum.signedURL + ? encodeURI(`${this.url}${datum.signedURL}${downloadQueryParam}`) + : null }))), + error: null, + }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead. + * + * @param path The full path and file name of the file to be downloaded. For example `folder/image.png`. + * @param options.transform Transform the asset before serving it to the client. + */ + download(path, options) { + return __awaiter(this, void 0, void 0, function* () { + const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined'; + const renderPath = wantsTransformation ? 'render/image/authenticated' : 'object'; + const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); + const queryString = transformationQuery ? `?${transformationQuery}` : ''; + try { + const _path = this._getFinalPath(path); + const res = yield get(this.fetch, `${this.url}/${renderPath}/${_path}${queryString}`, { + headers: this.headers, + noResolveJson: true, + }); + const data = yield res.blob(); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset. + * This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset. + * + * @param path The path and name of the file to generate the public URL for. For example `folder/image.png`. + * @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + */ + getPublicUrl(path, options) { + const _path = this._getFinalPath(path); + const _queryString = []; + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) + ? `download=${options.download === true ? '' : options.download}` + : ''; + if (downloadQueryParam !== '') { + _queryString.push(downloadQueryParam); + } + const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined'; + const renderPath = wantsTransformation ? 'render/image' : 'object'; + const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); + if (transformationQuery !== '') { + _queryString.push(transformationQuery); + } + let queryString = _queryString.join('&'); + if (queryString !== '') { + queryString = `?${queryString}`; + } + return { + data: { publicUrl: encodeURI(`${this.url}/${renderPath}/public/${_path}${queryString}`) }, + }; + } + /** + * Deletes files within the same bucket + * + * @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`]. + */ + remove(paths) { + return __awaiter(this, void 0, void 0, function* () { + try { + const data = yield remove(this.fetch, `${this.url}/object/${this.bucketId}`, { prefixes: paths }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Get file metadata + * @param id the file id to retrieve metadata + */ + // async getMetadata( + // id: string + // ): Promise< + // | { + // data: Metadata + // error: null + // } + // | { + // data: null + // error: StorageError + // } + // > { + // try { + // const data = await get(this.fetch, `${this.url}/metadata/${id}`, { headers: this.headers }) + // return { data, error: null } + // } catch (error) { + // if (isStorageError(error)) { + // return { data: null, error } + // } + // throw error + // } + // } + /** + * Update file metadata + * @param id the file id to update metadata + * @param meta the new file metadata + */ + // async updateMetadata( + // id: string, + // meta: Metadata + // ): Promise< + // | { + // data: Metadata + // error: null + // } + // | { + // data: null + // error: StorageError + // } + // > { + // try { + // const data = await post( + // this.fetch, + // `${this.url}/metadata/${id}`, + // { ...meta }, + // { headers: this.headers } + // ) + // return { data, error: null } + // } catch (error) { + // if (isStorageError(error)) { + // return { data: null, error } + // } + // throw error + // } + // } + /** + * Lists all the files within a bucket. + * @param path The folder path. + */ + list(path, options, parameters) { + return __awaiter(this, void 0, void 0, function* () { + try { + const body = Object.assign(Object.assign(Object.assign({}, DEFAULT_SEARCH_OPTIONS), options), { prefix: path || '' }); + const data = yield post(this.fetch, `${this.url}/object/list/${this.bucketId}`, body, { headers: this.headers }, parameters); + return { data, error: null }; + } + catch (error) { + if (isStorageError(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + _getFinalPath(path) { + return `${this.bucketId}/${path}`; + } + _removeEmptyFolders(path) { + return path.replace(/^\/|\/$/g, '').replace(/\/+/g, '/'); + } + transformOptsToQueryString(transform) { + const params = []; + if (transform.width) { + params.push(`width=${transform.width}`); + } + if (transform.height) { + params.push(`height=${transform.height}`); + } + if (transform.resize) { + params.push(`resize=${transform.resize}`); + } + if (transform.format) { + params.push(`format=${transform.format}`); + } + if (transform.quality) { + params.push(`quality=${transform.quality}`); + } + return params.join('&'); + } +} +//# sourceMappingURL=StorageFileApi.js.map \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/module/packages/StorageFileApi.js.map b/node_modules/@supabase/storage-js/dist/module/packages/StorageFileApi.js.map new file mode 100644 index 0000000..8813787 --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/module/packages/StorageFileApi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"StorageFileApi.js","sourceRoot":"","sources":["../../../src/packages/StorageFileApi.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AAC5D,OAAO,EAAS,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAS7C,MAAM,sBAAsB,GAAG;IAC7B,KAAK,EAAE,GAAG;IACV,MAAM,EAAE,CAAC;IACT,MAAM,EAAE;QACN,MAAM,EAAE,MAAM;QACd,KAAK,EAAE,KAAK;KACb;CACF,CAAA;AAED,MAAM,oBAAoB,GAAgB;IACxC,YAAY,EAAE,MAAM;IACpB,WAAW,EAAE,0BAA0B;IACvC,MAAM,EAAE,KAAK;CACd,CAAA;AAcD,MAAM,CAAC,OAAO,OAAO,cAAc;IAMjC,YACE,GAAW,EACX,UAAqC,EAAE,EACvC,QAAiB,EACjB,KAAa;QAEb,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,KAAK,GAAG,YAAY,CAAC,KAAK,CAAC,CAAA;IAClC,CAAC;IAED;;;;;;OAMG;IACW,cAAc,CAC1B,MAAsB,EACtB,IAAY,EACZ,QAAkB,EAClB,WAAyB;;YAWzB,IAAI;gBACF,IAAI,IAAI,CAAA;gBACR,MAAM,OAAO,mCAAQ,oBAAoB,GAAK,WAAW,CAAE,CAAA;gBAC3D,MAAM,OAAO,mCACR,IAAI,CAAC,OAAO,GACZ,CAAC,MAAM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,GAAG,IAAI,CAAC,QAAQ,IAAI,IAAI,EAAE,CAAA;IACnC,CAAC;IAEO,mBAAmB,CAAC,IAAY;QACtC,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC1D,CAAC;IAEO,0BAA0B,CAAC,SAA2B;QAC5D,MAAM,MAAM,GAAG,EAAE,CAAA;QACjB,IAAI,SAAS,CAAC,KAAK,EAAE;YACnB,MAAM,CAAC,IAAI,CAAC,SAAS,SAAS,CAAC,KAAK,EAAE,CAAC,CAAA;SACxC;QAED,IAAI,SAAS,CAAC,MAAM,EAAE;YACpB,MAAM,CAAC,IAAI,CAAC,UAAU,SAAS,CAAC,MAAM,EAAE,CAAC,CAAA;SAC1C;QAED,IAAI,SAAS,CAAC,MAAM,EAAE;YACpB,MAAM,CAAC,IAAI,CAAC,UAAU,SAAS,CAAC,MAAM,EAAE,CAAC,CAAA;SAC1C;QAED,IAAI,SAAS,CAAC,MAAM,EAAE;YACpB,MAAM,CAAC,IAAI,CAAC,UAAU,SAAS,CAAC,MAAM,EAAE,CAAC,CAAA;SAC1C;QAED,IAAI,SAAS,CAAC,OAAO,EAAE;YACrB,MAAM,CAAC,IAAI,CAAC,WAAW,SAAS,CAAC,OAAO,EAAE,CAAC,CAAA;SAC5C;QAED,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;IACzB,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/dist/umd/supabase.js b/node_modules/@supabase/storage-js/dist/umd/supabase.js new file mode 100644 index 0000000..ac2cfbe --- /dev/null +++ b/node_modules/@supabase/storage-js/dist/umd/supabase.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.supabase=e():t.supabase=e()}(self,(()=>{return t={98:function(t,e){var r="undefined"!=typeof self?self:this,o=function(){function t(){this.fetch=!1,this.DOMException=r.DOMException}return t.prototype=r,new t}();!function(t){!function(e){var r="URLSearchParams"in t,o="Symbol"in t&&"iterator"in Symbol,n="FileReader"in t&&"Blob"in t&&function(){try{return new Blob,!0}catch(t){return!1}}(),i="FormData"in t,s="ArrayBuffer"in t;if(s)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],u=ArrayBuffer.isView||function(t){return t&&a.indexOf(Object.prototype.toString.call(t))>-1};function c(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function d(t){return"string"!=typeof t&&(t=String(t)),t}function h(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return o&&(e[Symbol.iterator]=function(){return e}),e}function l(t){this.map={},t instanceof l?t.forEach((function(t,e){this.append(e,t)}),this):Array.isArray(t)?t.forEach((function(t){this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(e){this.append(e,t[e])}),this)}function f(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function p(t){return new Promise((function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}}))}function y(t){var e=new FileReader,r=p(e);return e.readAsArrayBuffer(t),r}function b(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function v(){return this.bodyUsed=!1,this._initBody=function(t){var e;this._bodyInit=t,t?"string"==typeof t?this._bodyText=t:n&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:i&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:r&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():s&&n&&(e=t)&&DataView.prototype.isPrototypeOf(e)?(this._bodyArrayBuffer=b(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s&&(ArrayBuffer.prototype.isPrototypeOf(t)||u(t))?this._bodyArrayBuffer=b(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},n&&(this.blob=function(){var t=f(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?f(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(y)}),this.text=function(){var t,e,r,o=f(this);if(o)return o;if(this._bodyBlob)return t=this._bodyBlob,r=p(e=new FileReader),e.readAsText(t),r;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),r=new Array(e.length),o=0;o-1?o:r),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&n)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(n)}function w(t){var e=new FormData;return t.trim().split("&").forEach((function(t){if(t){var r=t.split("="),o=r.shift().replace(/\+/g," "),n=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(o),decodeURIComponent(n))}})),e}function _(t,e){e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new l(e.headers),this.url=e.url||"",this._initBody(t)}m.prototype.clone=function(){return new m(this,{body:this._bodyInit})},v.call(m.prototype),v.call(_.prototype),_.prototype.clone=function(){return new _(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new l(this.headers),url:this.url})},_.error=function(){var t=new _(null,{status:0,statusText:""});return t.type="error",t};var E=[301,302,303,307,308];_.redirect=function(t,e){if(-1===E.indexOf(e))throw new RangeError("Invalid status code");return new _(null,{status:e,headers:{location:t}})},e.DOMException=t.DOMException;try{new e.DOMException}catch(t){e.DOMException=function(t,e){this.message=t,this.name=e;var r=Error(t);this.stack=r.stack},e.DOMException.prototype=Object.create(Error.prototype),e.DOMException.prototype.constructor=e.DOMException}function O(t,r){return new Promise((function(o,i){var s=new m(t,r);if(s.signal&&s.signal.aborted)return i(new e.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function u(){a.abort()}a.onload=function(){var t,e,r={status:a.status,statusText:a.statusText,headers:(t=a.getAllResponseHeaders()||"",e=new l,t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(t){var r=t.split(":"),o=r.shift().trim();if(o){var n=r.join(":").trim();e.append(o,n)}})),e)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var n="response"in a?a.response:a.responseText;o(new _(n,r))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.onabort=function(){i(new e.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&n&&(a.responseType="blob"),s.headers.forEach((function(t,e){a.setRequestHeader(e,t)})),s.signal&&(s.signal.addEventListener("abort",u),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",u)}),a.send(void 0===s._bodyInit?null:s._bodyInit)}))}O.polyfill=!0,t.fetch||(t.fetch=O,t.Headers=l,t.Request=m,t.Response=_),e.Headers=l,e.Request=m,e.Response=_,e.fetch=O,Object.defineProperty(e,"__esModule",{value:!0})}({})}(o),o.fetch.ponyfill=!0,delete o.fetch.polyfill;var n=o;(e=n.fetch).default=n.fetch,e.fetch=n.fetch,e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response,t.exports=e},274:function(t,e,r){"use strict";var o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.StorageClient=void 0;const n=o(r(981)),i=o(r(436));class s extends i.default{constructor(t,e={},r){super(t,e,r)}from(t){return new n.default(this.url,this.headers,t,this.fetch)}}e.StorageClient=s},341:function(t,e,r){"use strict";var o=this&&this.__createBinding||(Object.create?function(t,e,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(e,r);n&&!("get"in n?!e.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,o,n)}:function(t,e,r,o){void 0===o&&(o=r),t[o]=e[r]}),n=this&&this.__exportStar||function(t,e){for(var r in t)"default"===r||Object.prototype.hasOwnProperty.call(e,r)||o(e,t,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.StorageClient=void 0;var i=r(274);Object.defineProperty(e,"StorageClient",{enumerable:!0,get:function(){return i.StorageClient}}),n(r(717),e),n(r(752),e)},678:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.DEFAULT_HEADERS=void 0;const o=r(506);e.DEFAULT_HEADERS={"X-Client-Info":`storage-js/${o.version}`}},752:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.StorageUnknownError=e.StorageApiError=e.isStorageError=e.StorageError=void 0;class r extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}e.StorageError=r,e.isStorageError=function(t){return"object"==typeof t&&null!==t&&"__isStorageError"in t},e.StorageApiError=class extends r{constructor(t,e){super(t),this.name="StorageApiError",this.status=e}toJSON(){return{name:this.name,message:this.message,status:this.status}}},e.StorageUnknownError=class extends r{constructor(t,e){super(t),this.name="StorageUnknownError",this.originalError=e}}},716:function(t,e,r){"use strict";var o=this&&this.__awaiter||function(t,e,r,o){return new(r||(r=Promise))((function(n,i){function s(t){try{u(o.next(t))}catch(t){i(t)}}function a(t){try{u(o.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?n(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(s,a)}u((o=o.apply(t,e||[])).next())}))};Object.defineProperty(e,"__esModule",{value:!0}),e.remove=e.put=e.post=e.get=void 0;const n=r(752),i=r(610),s=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t);function a(t,e,r,a,u,c){return o(this,void 0,void 0,(function*(){return new Promise(((d,h)=>{t(r,((t,e,r,o)=>{const n={method:t,headers:(null==e?void 0:e.headers)||{}};return"GET"===t?n:(n.headers=Object.assign({"Content-Type":"application/json"},null==e?void 0:e.headers),n.body=JSON.stringify(o),Object.assign(Object.assign({},n),r))})(e,a,u,c)).then((t=>{if(!t.ok)throw t;return(null==a?void 0:a.noResolveJson)?t:t.json()})).then((t=>d(t))).catch((t=>((t,e)=>o(void 0,void 0,void 0,(function*(){const r=yield(0,i.resolveResponse)();t instanceof r?t.json().then((r=>{e(new n.StorageApiError(s(r),t.status||500))})).catch((t=>{e(new n.StorageUnknownError(s(t),t))})):e(new n.StorageUnknownError(s(t),t))})))(t,h)))}))}))}e.get=function(t,e,r,n){return o(this,void 0,void 0,(function*(){return a(t,"GET",e,r,n)}))},e.post=function(t,e,r,n,i){return o(this,void 0,void 0,(function*(){return a(t,"POST",e,n,i,r)}))},e.put=function(t,e,r,n,i){return o(this,void 0,void 0,(function*(){return a(t,"PUT",e,n,i,r)}))},e.remove=function(t,e,r,n,i){return o(this,void 0,void 0,(function*(){return a(t,"DELETE",e,n,i,r)}))}},610:function(t,e,r){"use strict";var o=this&&this.__createBinding||(Object.create?function(t,e,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(e,r);n&&!("get"in n?!e.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,o,n)}:function(t,e,r,o){void 0===o&&(o=r),t[o]=e[r]}),n=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)"default"!==r&&Object.prototype.hasOwnProperty.call(t,r)&&o(e,t,r);return n(e,t),e},s=this&&this.__awaiter||function(t,e,r,o){return new(r||(r=Promise))((function(n,i){function s(t){try{u(o.next(t))}catch(t){i(t)}}function a(t){try{u(o.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?n(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(s,a)}u((o=o.apply(t,e||[])).next())}))};Object.defineProperty(e,"__esModule",{value:!0}),e.resolveResponse=e.resolveFetch=void 0,e.resolveFetch=t=>{let e;return e=t||("undefined"==typeof fetch?(...t)=>s(void 0,void 0,void 0,(function*(){return yield(yield Promise.resolve().then((()=>i(r(98))))).fetch(...t)})):fetch),(...t)=>e(...t)},e.resolveResponse=()=>s(void 0,void 0,void 0,(function*(){return"undefined"==typeof Response?(yield Promise.resolve().then((()=>i(r(98))))).Response:Response}))},717:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0})},506:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.version=void 0,e.version="0.0.0"},436:function(t,e,r){"use strict";var o=this&&this.__awaiter||function(t,e,r,o){return new(r||(r=Promise))((function(n,i){function s(t){try{u(o.next(t))}catch(t){i(t)}}function a(t){try{u(o.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?n(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(s,a)}u((o=o.apply(t,e||[])).next())}))};Object.defineProperty(e,"__esModule",{value:!0});const n=r(678),i=r(752),s=r(716),a=r(610);e.default=class{constructor(t,e={},r){this.url=t,this.headers=Object.assign(Object.assign({},n.DEFAULT_HEADERS),e),this.fetch=(0,a.resolveFetch)(r)}listBuckets(){return o(this,void 0,void 0,(function*(){try{return{data:yield(0,s.get)(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if((0,i.isStorageError)(t))return{data:null,error:t};throw t}}))}getBucket(t){return o(this,void 0,void 0,(function*(){try{return{data:yield(0,s.get)(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(t){if((0,i.isStorageError)(t))return{data:null,error:t};throw t}}))}createBucket(t,e={public:!1}){return o(this,void 0,void 0,(function*(){try{return{data:yield(0,s.post)(this.fetch,`${this.url}/bucket`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:this.headers}),error:null}}catch(t){if((0,i.isStorageError)(t))return{data:null,error:t};throw t}}))}updateBucket(t,e){return o(this,void 0,void 0,(function*(){try{return{data:yield(0,s.put)(this.fetch,`${this.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:this.headers}),error:null}}catch(t){if((0,i.isStorageError)(t))return{data:null,error:t};throw t}}))}emptyBucket(t){return o(this,void 0,void 0,(function*(){try{return{data:yield(0,s.post)(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(t){if((0,i.isStorageError)(t))return{data:null,error:t};throw t}}))}deleteBucket(t){return o(this,void 0,void 0,(function*(){try{return{data:yield(0,s.remove)(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(t){if((0,i.isStorageError)(t))return{data:null,error:t};throw t}}))}}},981:function(t,e,r){"use strict";var o=this&&this.__awaiter||function(t,e,r,o){return new(r||(r=Promise))((function(n,i){function s(t){try{u(o.next(t))}catch(t){i(t)}}function a(t){try{u(o.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?n(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(s,a)}u((o=o.apply(t,e||[])).next())}))};Object.defineProperty(e,"__esModule",{value:!0});const n=r(752),i=r(716),s=r(610),a={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},u={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};e.default=class{constructor(t,e={},r,o){this.url=t,this.headers=e,this.bucketId=r,this.fetch=(0,s.resolveFetch)(o)}uploadOrUpdate(t,e,r,i){return o(this,void 0,void 0,(function*(){try{let o;const n=Object.assign(Object.assign({},u),i),s=Object.assign(Object.assign({},this.headers),"POST"===t&&{"x-upsert":String(n.upsert)});"undefined"!=typeof Blob&&r instanceof Blob?(o=new FormData,o.append("cacheControl",n.cacheControl),o.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(o=r,o.append("cacheControl",n.cacheControl)):(o=r,s["cache-control"]=`max-age=${n.cacheControl}`,s["content-type"]=n.contentType);const a=this._removeEmptyFolders(e),c=this._getFinalPath(a),d=yield this.fetch(`${this.url}/object/${c}`,Object.assign({method:t,body:o,headers:s},(null==n?void 0:n.duplex)?{duplex:n.duplex}:{}));return d.ok?{data:{path:a},error:null}:{data:null,error:yield d.json()}}catch(t){if((0,n.isStorageError)(t))return{data:null,error:t};throw t}}))}upload(t,e,r){return o(this,void 0,void 0,(function*(){return this.uploadOrUpdate("POST",t,e,r)}))}uploadToSignedUrl(t,e,r,i){return o(this,void 0,void 0,(function*(){const o=this._removeEmptyFolders(t),s=this._getFinalPath(o),a=new URL(this.url+`/object/upload/sign/${s}`);a.searchParams.set("token",e);try{let t;const e=Object.assign({upsert:u.upsert},i),n=Object.assign(Object.assign({},this.headers),{"x-upsert":String(e.upsert)});"undefined"!=typeof Blob&&r instanceof Blob?(t=new FormData,t.append("cacheControl",e.cacheControl),t.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(t=r,t.append("cacheControl",e.cacheControl)):(t=r,n["cache-control"]=`max-age=${e.cacheControl}`,n["content-type"]=e.contentType);const s=yield this.fetch(a.toString(),{method:"PUT",body:t,headers:n});return s.ok?{data:{path:o},error:null}:{data:null,error:yield s.json()}}catch(t){if((0,n.isStorageError)(t))return{data:null,error:t};throw t}}))}createSignedUploadUrl(t){return o(this,void 0,void 0,(function*(){try{let e=this._getFinalPath(t);const r=yield(0,i.post)(this.fetch,`${this.url}/object/upload/sign/${e}`,{},{headers:this.headers}),o=new URL(this.url+r.url),s=o.searchParams.get("token");if(!s)throw new n.StorageError("No token returned by API");return{data:{signedUrl:o.toString(),path:t,token:s},error:null}}catch(t){if((0,n.isStorageError)(t))return{data:null,error:t};throw t}}))}update(t,e,r){return o(this,void 0,void 0,(function*(){return this.uploadOrUpdate("PUT",t,e,r)}))}move(t,e){return o(this,void 0,void 0,(function*(){try{return{data:yield(0,i.post)(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:t,destinationKey:e},{headers:this.headers}),error:null}}catch(t){if((0,n.isStorageError)(t))return{data:null,error:t};throw t}}))}copy(t,e){return o(this,void 0,void 0,(function*(){try{return{data:{path:(yield(0,i.post)(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:t,destinationKey:e},{headers:this.headers})).Key},error:null}}catch(t){if((0,n.isStorageError)(t))return{data:null,error:t};throw t}}))}createSignedUrl(t,e,r){return o(this,void 0,void 0,(function*(){try{let o=this._getFinalPath(t),n=yield(0,i.post)(this.fetch,`${this.url}/object/sign/${o}`,Object.assign({expiresIn:e},(null==r?void 0:r.transform)?{transform:r.transform}:{}),{headers:this.headers});const s=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${s}`)},{data:n,error:null}}catch(t){if((0,n.isStorageError)(t))return{data:null,error:t};throw t}}))}createSignedUrls(t,e,r){return o(this,void 0,void 0,(function*(){try{const o=yield(0,i.post)(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:e,paths:t},{headers:this.headers}),n=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return{data:o.map((t=>Object.assign(Object.assign({},t),{signedUrl:t.signedURL?encodeURI(`${this.url}${t.signedURL}${n}`):null}))),error:null}}catch(t){if((0,n.isStorageError)(t))return{data:null,error:t};throw t}}))}download(t,e){return o(this,void 0,void 0,(function*(){const r=void 0!==(null==e?void 0:e.transform)?"render/image/authenticated":"object",o=this.transformOptsToQueryString((null==e?void 0:e.transform)||{}),s=o?`?${o}`:"";try{const e=this._getFinalPath(t),o=yield(0,i.get)(this.fetch,`${this.url}/${r}/${e}${s}`,{headers:this.headers,noResolveJson:!0});return{data:yield o.blob(),error:null}}catch(t){if((0,n.isStorageError)(t))return{data:null,error:t};throw t}}))}getPublicUrl(t,e){const r=this._getFinalPath(t),o=[],n=(null==e?void 0:e.download)?`download=${!0===e.download?"":e.download}`:"";""!==n&&o.push(n);const i=void 0!==(null==e?void 0:e.transform)?"render/image":"object",s=this.transformOptsToQueryString((null==e?void 0:e.transform)||{});""!==s&&o.push(s);let a=o.join("&");return""!==a&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${a}`)}}}remove(t){return o(this,void 0,void 0,(function*(){try{return{data:yield(0,i.remove)(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(t){if((0,n.isStorageError)(t))return{data:null,error:t};throw t}}))}list(t,e,r){return o(this,void 0,void 0,(function*(){try{const o=Object.assign(Object.assign(Object.assign({},a),e),{prefix:t||""});return{data:yield(0,i.post)(this.fetch,`${this.url}/object/list/${this.bucketId}`,o,{headers:this.headers},r),error:null}}catch(t){if((0,n.isStorageError)(t))return{data:null,error:t};throw t}}))}_getFinalPath(t){return`${this.bucketId}/${t}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){const e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}}}},e={},function r(o){var n=e[o];if(void 0!==n)return n.exports;var i=e[o]={exports:{}};return t[o].call(i.exports,i,i.exports,r),i.exports}(341);var t,e})); \ No newline at end of file diff --git a/node_modules/@supabase/storage-js/package.json b/node_modules/@supabase/storage-js/package.json new file mode 100644 index 0000000..dda2be7 --- /dev/null +++ b/node_modules/@supabase/storage-js/package.json @@ -0,0 +1,70 @@ +{ + "name": "@supabase/storage-js", + "version": "2.5.1", + "description": "Isomorphic storage client for Supabase.", + "keywords": [ + "javascript", + "typescript", + "supabase" + ], + "homepage": "https://github.com/supabase/storage-js", + "bugs": "https://github.com/supabase/storage-js/issues", + "license": "MIT", + "author": "Supabase", + "files": [ + "dist", + "src" + ], + "main": "dist/main/index.js", + "module": "dist/module/index.js", + "types": "dist/module/index.d.ts", + "sideEffects": false, + "repository": "supabase/storage-js", + "scripts": { + "clean": "rimraf dist docs/v2", + "format": "prettier --write \"{src,test}/**/*.ts\"", + "build": "genversion src/lib/version.ts --es6 && run-s clean format build:*", + "build:main": "tsc -p tsconfig.json", + "build:module": "tsc -p tsconfig.module.json", + "build:umd": "webpack", + "types-generate": "dts-gen -m '@supabase/storage-js' -s", + "test": "run-s test:clean test:infra test:suite test:clean", + "test:suite": "jest --runInBand", + "test:infra": "cd infra && docker-compose down && docker-compose up -d && sleep 10", + "test:clean": "cd infra && docker-compose down --remove-orphans", + "docs": "typedoc --entryPoints src/index.ts --out docs/v2 --entryPoints src/packages/* --excludePrivate --excludeProtected", + "docs:json": "typedoc --json docs/v2/spec.json --entryPoints src/index.ts --entryPoints src/packages/* --excludePrivate --excludeExternals --excludeProtected" + }, + "dependencies": { + "cross-fetch": "^3.1.5" + }, + "devDependencies": { + "@types/jest": "^26.0.13", + "form-data": "^4.0.0", + "genversion": "^3.0.1", + "husky": "^4.3.0", + "jest": "^29.0.0", + "jest-environment-jsdom": "^29.5.0", + "npm-run-all": "^4.1.5", + "prettier": "^2.1.2", + "pretty-quick": "^3.1.0", + "rimraf": "^3.0.2", + "semantic-release-plugin-update-version-in-files": "^1.1.0", + "ts-jest": "^29.0.0", + "ts-loader": "^9.4.2", + "typedoc": "^0.22.16", + "typescript": "^4.6.3", + "webpack": "^5.75.0", + "webpack-cli": "^5.0.1" + }, + "husky": { + "hooks": { + "pre-commit": "pretty-quick --staged" + } + }, + "jsdelivr": "dist/umd/supabase.js", + "unpkg": "dist/umd/supabase.js", + "publishConfig": { + "access": "public" + } +} diff --git a/node_modules/@supabase/storage-js/src/StorageClient.ts b/node_modules/@supabase/storage-js/src/StorageClient.ts new file mode 100644 index 0000000..fbc35d1 --- /dev/null +++ b/node_modules/@supabase/storage-js/src/StorageClient.ts @@ -0,0 +1,18 @@ +import StorageFileApi from './packages/StorageFileApi' +import StorageBucketApi from './packages/StorageBucketApi' +import { Fetch } from './lib/fetch' + +export class StorageClient extends StorageBucketApi { + constructor(url: string, headers: { [key: string]: string } = {}, fetch?: Fetch) { + super(url, headers, fetch) + } + + /** + * Perform file operation in a bucket. + * + * @param id The bucket id to operate on. + */ + from(id: string): StorageFileApi { + return new StorageFileApi(this.url, this.headers, id, this.fetch) + } +} diff --git a/node_modules/@supabase/storage-js/src/index.ts b/node_modules/@supabase/storage-js/src/index.ts new file mode 100644 index 0000000..06c35d5 --- /dev/null +++ b/node_modules/@supabase/storage-js/src/index.ts @@ -0,0 +1,3 @@ +export { StorageClient as StorageClient } from './StorageClient' +export * from './lib/types' +export * from './lib/errors' diff --git a/node_modules/@supabase/storage-js/src/lib/constants.ts b/node_modules/@supabase/storage-js/src/lib/constants.ts new file mode 100644 index 0000000..dc81a34 --- /dev/null +++ b/node_modules/@supabase/storage-js/src/lib/constants.ts @@ -0,0 +1,2 @@ +import { version } from './version' +export const DEFAULT_HEADERS = { 'X-Client-Info': `storage-js/${version}` } diff --git a/node_modules/@supabase/storage-js/src/lib/errors.ts b/node_modules/@supabase/storage-js/src/lib/errors.ts new file mode 100644 index 0000000..dabef49 --- /dev/null +++ b/node_modules/@supabase/storage-js/src/lib/errors.ts @@ -0,0 +1,40 @@ +export class StorageError extends Error { + protected __isStorageError = true + + constructor(message: string) { + super(message) + this.name = 'StorageError' + } +} + +export function isStorageError(error: unknown): error is StorageError { + return typeof error === 'object' && error !== null && '__isStorageError' in error +} + +export class StorageApiError extends StorageError { + status: number + + constructor(message: string, status: number) { + super(message) + this.name = 'StorageApiError' + this.status = status + } + + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + } + } +} + +export class StorageUnknownError extends StorageError { + originalError: unknown + + constructor(message: string, originalError: unknown) { + super(message) + this.name = 'StorageUnknownError' + this.originalError = originalError + } +} diff --git a/node_modules/@supabase/storage-js/src/lib/fetch.ts b/node_modules/@supabase/storage-js/src/lib/fetch.ts new file mode 100644 index 0000000..2468126 --- /dev/null +++ b/node_modules/@supabase/storage-js/src/lib/fetch.ts @@ -0,0 +1,110 @@ +import { StorageApiError, StorageUnknownError } from './errors' +import { resolveResponse } from './helpers' +import { FetchParameters } from './types' + +export type Fetch = typeof fetch + +export interface FetchOptions { + headers?: { + [key: string]: string + } + noResolveJson?: boolean +} + +export type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'DELETE' + +const _getErrorMessage = (err: any): string => + err.msg || err.message || err.error_description || err.error || JSON.stringify(err) + +const handleError = async (error: unknown, reject: (reason?: any) => void) => { + const Res = await resolveResponse() + + if (error instanceof Res) { + error + .json() + .then((err) => { + reject(new StorageApiError(_getErrorMessage(err), error.status || 500)) + }) + .catch((err) => { + reject(new StorageUnknownError(_getErrorMessage(err), err)) + }) + } else { + reject(new StorageUnknownError(_getErrorMessage(error), error)) + } +} + +const _getRequestParams = ( + method: RequestMethodType, + options?: FetchOptions, + parameters?: FetchParameters, + body?: object +) => { + const params: { [k: string]: any } = { method, headers: options?.headers || {} } + + if (method === 'GET') { + return params + } + + params.headers = { 'Content-Type': 'application/json', ...options?.headers } + params.body = JSON.stringify(body) + return { ...params, ...parameters } +} + +async function _handleRequest( + fetcher: Fetch, + method: RequestMethodType, + url: string, + options?: FetchOptions, + parameters?: FetchParameters, + body?: object +): Promise { + return new Promise((resolve, reject) => { + fetcher(url, _getRequestParams(method, options, parameters, body)) + .then((result) => { + if (!result.ok) throw result + if (options?.noResolveJson) return result + return result.json() + }) + .then((data) => resolve(data)) + .catch((error) => handleError(error, reject)) + }) +} + +export async function get( + fetcher: Fetch, + url: string, + options?: FetchOptions, + parameters?: FetchParameters +): Promise { + return _handleRequest(fetcher, 'GET', url, options, parameters) +} + +export async function post( + fetcher: Fetch, + url: string, + body: object, + options?: FetchOptions, + parameters?: FetchParameters +): Promise { + return _handleRequest(fetcher, 'POST', url, options, parameters, body) +} + +export async function put( + fetcher: Fetch, + url: string, + body: object, + options?: FetchOptions, + parameters?: FetchParameters +): Promise { + return _handleRequest(fetcher, 'PUT', url, options, parameters, body) +} + +export async function remove( + fetcher: Fetch, + url: string, + body: object, + options?: FetchOptions, + parameters?: FetchParameters +): Promise { + return _handleRequest(fetcher, 'DELETE', url, options, parameters, body) +} diff --git a/node_modules/@supabase/storage-js/src/lib/helpers.ts b/node_modules/@supabase/storage-js/src/lib/helpers.ts new file mode 100644 index 0000000..1c6ece6 --- /dev/null +++ b/node_modules/@supabase/storage-js/src/lib/helpers.ts @@ -0,0 +1,21 @@ +type Fetch = typeof fetch + +export const resolveFetch = (customFetch?: Fetch): Fetch => { + let _fetch: Fetch + if (customFetch) { + _fetch = customFetch + } else if (typeof fetch === 'undefined') { + _fetch = async (...args) => await (await import('cross-fetch')).fetch(...args) + } else { + _fetch = fetch + } + return (...args) => _fetch(...args) +} + +export const resolveResponse = async () => { + if (typeof Response === 'undefined') { + return (await import('cross-fetch')).Response + } + + return Response +} diff --git a/node_modules/@supabase/storage-js/src/lib/index.ts b/node_modules/@supabase/storage-js/src/lib/index.ts new file mode 100644 index 0000000..fb0c997 --- /dev/null +++ b/node_modules/@supabase/storage-js/src/lib/index.ts @@ -0,0 +1,4 @@ +export * from '../packages/StorageBucketApi' +export * from '../packages/StorageFileApi' +export * from './types' +export * from './constants' diff --git a/node_modules/@supabase/storage-js/src/lib/types.ts b/node_modules/@supabase/storage-js/src/lib/types.ts new file mode 100644 index 0000000..fbccbb9 --- /dev/null +++ b/node_modules/@supabase/storage-js/src/lib/types.ts @@ -0,0 +1,111 @@ +export interface Bucket { + id: string + name: string + owner: string + file_size_limit?: number + allowed_mime_types?: string[] + created_at: string + updated_at: string + public: boolean +} + +export interface FileObject { + name: string + bucket_id: string + owner: string + id: string + updated_at: string + created_at: string + last_accessed_at: string + metadata: Record + buckets: Bucket +} + +export interface SortBy { + column?: string + order?: string +} + +export interface FileOptions { + /** + * The number of seconds the asset is cached in the browser and in the Supabase CDN. This is set in the `Cache-Control: max-age=` header. Defaults to 3600 seconds. + */ + cacheControl?: string + /** + * the `Content-Type` header value. Should be specified if using a `fileBody` that is neither `Blob` nor `File` nor `FormData`, otherwise will default to `text/plain;charset=UTF-8`. + */ + contentType?: string + /** + * When upsert is set to true, the file is overwritten if it exists. When set to false, an error is thrown if the object already exists. Defaults to false. + */ + upsert?: boolean + /** + * The duplex option is a string parameter that enables or disables duplex streaming, allowing for both reading and writing data in the same stream. It can be passed as an option to the fetch() method. + */ + duplex?: string +} + +export interface SearchOptions { + /** + * The number of files you want to be returned. + */ + limit?: number + + /** + * The starting position. + */ + offset?: number + + /** + * The column to sort by. Can be any column inside a FileObject. + */ + sortBy?: SortBy + + /** + * The search string to filter files by. + */ + search?: string +} + +export interface FetchParameters { + /** + * Pass in an AbortController's signal to cancel the request. + */ + signal?: AbortSignal +} + +// TODO: need to check for metadata props. The api swagger doesnt have. +export interface Metadata { + name: string +} + +export interface TransformOptions { + /** + * The width of the image in pixels. + */ + width?: number + /** + * The height of the image in pixels. + */ + height?: number + /** + * The resize mode can be cover, contain or fill. Defaults to cover. + * Cover resizes the image to maintain it's aspect ratio while filling the entire width and height. + * Contain resizes the image to maintain it's aspect ratio while fitting the entire image within the width and height. + * Fill resizes the image to fill the entire width and height. If the object's aspect ratio does not match the width and height, the image will be stretched to fit. + */ + resize?: 'cover' | 'contain' | 'fill' + /** + * Set the quality of the returned image. + * A number from 20 to 100, with 100 being the highest quality. + * Defaults to 80 + */ + quality?: number + /** + * Specify the format of the image requested. + * + * When using 'origin' we force the format to be the same as the original image. + * When this option is not passed in, images are optimized to modern image formats like Webp. + */ + format?: 'origin' +} diff --git a/node_modules/@supabase/storage-js/src/lib/version.ts b/node_modules/@supabase/storage-js/src/lib/version.ts new file mode 100644 index 0000000..374a4fc --- /dev/null +++ b/node_modules/@supabase/storage-js/src/lib/version.ts @@ -0,0 +1,2 @@ +// generated by genversion +export const version = '2.5.1' diff --git a/node_modules/@supabase/storage-js/src/packages/StorageBucketApi.ts b/node_modules/@supabase/storage-js/src/packages/StorageBucketApi.ts new file mode 100644 index 0000000..3a36b82 --- /dev/null +++ b/node_modules/@supabase/storage-js/src/packages/StorageBucketApi.ts @@ -0,0 +1,247 @@ +import { DEFAULT_HEADERS } from '../lib/constants' +import { isStorageError, StorageError } from '../lib/errors' +import { Fetch, get, post, put, remove } from '../lib/fetch' +import { resolveFetch } from '../lib/helpers' +import { Bucket } from '../lib/types' + +export default class StorageBucketApi { + protected url: string + protected headers: { [key: string]: string } + protected fetch: Fetch + + constructor(url: string, headers: { [key: string]: string } = {}, fetch?: Fetch) { + this.url = url + this.headers = { ...DEFAULT_HEADERS, ...headers } + this.fetch = resolveFetch(fetch) + } + + /** + * Retrieves the details of all Storage buckets within an existing project. + */ + async listBuckets(): Promise< + | { + data: Bucket[] + error: null + } + | { + data: null + error: StorageError + } + > { + try { + const data = await get(this.fetch, `${this.url}/bucket`, { headers: this.headers }) + return { data, error: null } + } catch (error) { + if (isStorageError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Retrieves the details of an existing Storage bucket. + * + * @param id The unique identifier of the bucket you would like to retrieve. + */ + async getBucket( + id: string + ): Promise< + | { + data: Bucket + error: null + } + | { + data: null + error: StorageError + } + > { + try { + const data = await get(this.fetch, `${this.url}/bucket/${id}`, { headers: this.headers }) + return { data, error: null } + } catch (error) { + if (isStorageError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Creates a new Storage bucket + * + * @param id A unique identifier for the bucket you are creating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + * @returns newly created bucket id + */ + async createBucket( + id: string, + options: { + public: boolean + fileSizeLimit?: number | string | null + allowedMimeTypes?: string[] | null + } = { + public: false, + } + ): Promise< + | { + data: Pick + error: null + } + | { + data: null + error: StorageError + } + > { + try { + const data = await post( + this.fetch, + `${this.url}/bucket`, + { + id, + name: id, + public: options.public, + file_size_limit: options.fileSizeLimit, + allowed_mime_types: options.allowedMimeTypes, + }, + { headers: this.headers } + ) + return { data, error: null } + } catch (error) { + if (isStorageError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Updates a Storage bucket + * + * @param id A unique identifier for the bucket you are updating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + */ + async updateBucket( + id: string, + options: { + public: boolean + fileSizeLimit?: number | string | null + allowedMimeTypes?: string[] | null + } + ): Promise< + | { + data: { message: string } + error: null + } + | { + data: null + error: StorageError + } + > { + try { + const data = await put( + this.fetch, + `${this.url}/bucket/${id}`, + { + id, + name: id, + public: options.public, + file_size_limit: options.fileSizeLimit, + allowed_mime_types: options.allowedMimeTypes, + }, + { headers: this.headers } + ) + return { data, error: null } + } catch (error) { + if (isStorageError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Removes all objects inside a single bucket. + * + * @param id The unique identifier of the bucket you would like to empty. + */ + async emptyBucket( + id: string + ): Promise< + | { + data: { message: string } + error: null + } + | { + data: null + error: StorageError + } + > { + try { + const data = await post( + this.fetch, + `${this.url}/bucket/${id}/empty`, + {}, + { headers: this.headers } + ) + return { data, error: null } + } catch (error) { + if (isStorageError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. + * You must first `empty()` the bucket. + * + * @param id The unique identifier of the bucket you would like to delete. + */ + async deleteBucket( + id: string + ): Promise< + | { + data: { message: string } + error: null + } + | { + data: null + error: StorageError + } + > { + try { + const data = await remove( + this.fetch, + `${this.url}/bucket/${id}`, + {}, + { headers: this.headers } + ) + return { data, error: null } + } catch (error) { + if (isStorageError(error)) { + return { data: null, error } + } + + throw error + } + } +} diff --git a/node_modules/@supabase/storage-js/src/packages/StorageFileApi.ts b/node_modules/@supabase/storage-js/src/packages/StorageFileApi.ts new file mode 100644 index 0000000..d10c804 --- /dev/null +++ b/node_modules/@supabase/storage-js/src/packages/StorageFileApi.ts @@ -0,0 +1,708 @@ +import { isStorageError, StorageError } from '../lib/errors' +import { Fetch, get, post, remove } from '../lib/fetch' +import { resolveFetch } from '../lib/helpers' +import { + FileObject, + FileOptions, + SearchOptions, + FetchParameters, + TransformOptions, +} from '../lib/types' + +const DEFAULT_SEARCH_OPTIONS = { + limit: 100, + offset: 0, + sortBy: { + column: 'name', + order: 'asc', + }, +} + +const DEFAULT_FILE_OPTIONS: FileOptions = { + cacheControl: '3600', + contentType: 'text/plain;charset=UTF-8', + upsert: false, +} + +type FileBody = + | ArrayBuffer + | ArrayBufferView + | Blob + | Buffer + | File + | FormData + | NodeJS.ReadableStream + | ReadableStream + | URLSearchParams + | string + +export default class StorageFileApi { + protected url: string + protected headers: { [key: string]: string } + protected bucketId?: string + protected fetch: Fetch + + constructor( + url: string, + headers: { [key: string]: string } = {}, + bucketId?: string, + fetch?: Fetch + ) { + this.url = url + this.headers = headers + this.bucketId = bucketId + this.fetch = resolveFetch(fetch) + } + + /** + * Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one. + * + * @param method HTTP method. + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + private async uploadOrUpdate( + method: 'POST' | 'PUT', + path: string, + fileBody: FileBody, + fileOptions?: FileOptions + ): Promise< + | { + data: { path: string } + error: null + } + | { + data: null + error: StorageError + } + > { + try { + let body + const options = { ...DEFAULT_FILE_OPTIONS, ...fileOptions } + const headers: Record = { + ...this.headers, + ...(method === 'POST' && { 'x-upsert': String(options.upsert as boolean) }), + } + + if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { + body = new FormData() + body.append('cacheControl', options.cacheControl as string) + body.append('', fileBody) + } else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { + body = fileBody + body.append('cacheControl', options.cacheControl as string) + } else { + body = fileBody + headers['cache-control'] = `max-age=${options.cacheControl}` + headers['content-type'] = options.contentType as string + } + + const cleanPath = this._removeEmptyFolders(path) + const _path = this._getFinalPath(cleanPath) + const res = await this.fetch(`${this.url}/object/${_path}`, { + method, + body: body as BodyInit, + headers, + ...(options?.duplex ? { duplex: options.duplex } : {}), + }) + + if (res.ok) { + return { + data: { path: cleanPath }, + error: null, + } + } else { + const error = await res.json() + return { data: null, error } + } + } catch (error) { + if (isStorageError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Uploads a file to an existing bucket. + * + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + async upload( + path: string, + fileBody: FileBody, + fileOptions?: FileOptions + ): Promise< + | { + data: { path: string } + error: null + } + | { + data: null + error: StorageError + } + > { + return this.uploadOrUpdate('POST', path, fileBody, fileOptions) + } + + /** + * Upload a file with a token generated from `createSignedUploadUrl`. + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param token The token generated from `createSignedUploadUrl` + * @param fileBody The body of the file to be stored in the bucket. + */ + async uploadToSignedUrl( + path: string, + token: string, + fileBody: FileBody, + fileOptions?: FileOptions + ) { + const cleanPath = this._removeEmptyFolders(path) + const _path = this._getFinalPath(cleanPath) + + const url = new URL(this.url + `/object/upload/sign/${_path}`) + url.searchParams.set('token', token) + + try { + let body + const options = { upsert: DEFAULT_FILE_OPTIONS.upsert, ...fileOptions } + const headers: Record = { + ...this.headers, + ...{ 'x-upsert': String(options.upsert as boolean) }, + } + + if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { + body = new FormData() + body.append('cacheControl', options.cacheControl as string) + body.append('', fileBody) + } else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { + body = fileBody + body.append('cacheControl', options.cacheControl as string) + } else { + body = fileBody + headers['cache-control'] = `max-age=${options.cacheControl}` + headers['content-type'] = options.contentType as string + } + + const res = await this.fetch(url.toString(), { + method: 'PUT', + body: body as BodyInit, + headers, + }) + + if (res.ok) { + return { + data: { path: cleanPath }, + error: null, + } + } else { + const error = await res.json() + return { data: null, error } + } + } catch (error) { + if (isStorageError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Creates a signed upload URL. + * Signed upload URLs can be used to upload files to the bucket without further authentication. + * They are valid for one minute. + * @param path The file path, including the current file name. For example `folder/image.png`. + */ + async createSignedUploadUrl( + path: string + ): Promise< + | { + data: { signedUrl: string; token: string; path: string } + error: null + } + | { + data: null + error: StorageError + } + > { + try { + let _path = this._getFinalPath(path) + + const data = await post( + this.fetch, + `${this.url}/object/upload/sign/${_path}`, + {}, + { headers: this.headers } + ) + + const url = new URL(this.url + data.url) + + const token = url.searchParams.get('token') + + if (!token) { + throw new StorageError('No token returned by API') + } + + return { data: { signedUrl: url.toString(), path, token }, error: null } + } catch (error) { + if (isStorageError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Replaces an existing file at the specified path with a new one. + * + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update. + * @param fileBody The body of the file to be stored in the bucket. + */ + async update( + path: string, + fileBody: + | ArrayBuffer + | ArrayBufferView + | Blob + | Buffer + | File + | FormData + | NodeJS.ReadableStream + | ReadableStream + | URLSearchParams + | string, + fileOptions?: FileOptions + ): Promise< + | { + data: { path: string } + error: null + } + | { + data: null + error: StorageError + } + > { + return this.uploadOrUpdate('PUT', path, fileBody, fileOptions) + } + + /** + * Moves an existing file to a new path in the same bucket. + * + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-new.png`. + */ + async move( + fromPath: string, + toPath: string + ): Promise< + | { + data: { message: string } + error: null + } + | { + data: null + error: StorageError + } + > { + try { + const data = await post( + this.fetch, + `${this.url}/object/move`, + { bucketId: this.bucketId, sourceKey: fromPath, destinationKey: toPath }, + { headers: this.headers } + ) + return { data, error: null } + } catch (error) { + if (isStorageError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Copies an existing file to a new path in the same bucket. + * + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-copy.png`. + */ + async copy( + fromPath: string, + toPath: string + ): Promise< + | { + data: { path: string } + error: null + } + | { + data: null + error: StorageError + } + > { + try { + const data = await post( + this.fetch, + `${this.url}/object/copy`, + { bucketId: this.bucketId, sourceKey: fromPath, destinationKey: toPath }, + { headers: this.headers } + ) + return { data: { path: data.Key }, error: null } + } catch (error) { + if (isStorageError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Creates a signed URL. Use a signed URL to share a file for a fixed amount of time. + * + * @param path The file path, including the current file name. For example `folder/image.png`. + * @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + */ + async createSignedUrl( + path: string, + expiresIn: number, + options?: { download?: string | boolean; transform?: TransformOptions } + ): Promise< + | { + data: { signedUrl: string } + error: null + } + | { + data: null + error: StorageError + } + > { + try { + let _path = this._getFinalPath(path) + + let data = await post( + this.fetch, + `${this.url}/object/sign/${_path}`, + { expiresIn, ...(options?.transform ? { transform: options.transform } : {}) }, + { headers: this.headers } + ) + const downloadQueryParam = options?.download + ? `&download=${options.download === true ? '' : options.download}` + : '' + const signedUrl = encodeURI(`${this.url}${data.signedURL}${downloadQueryParam}`) + data = { signedUrl } + return { data, error: null } + } catch (error) { + if (isStorageError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time. + * + * @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`. + * @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + */ + async createSignedUrls( + paths: string[], + expiresIn: number, + options?: { download: string | boolean } + ): Promise< + | { + data: { error: string | null; path: string | null; signedUrl: string }[] + error: null + } + | { + data: null + error: StorageError + } + > { + try { + const data = await post( + this.fetch, + `${this.url}/object/sign/${this.bucketId}`, + { expiresIn, paths }, + { headers: this.headers } + ) + + const downloadQueryParam = options?.download + ? `&download=${options.download === true ? '' : options.download}` + : '' + return { + data: data.map((datum: { signedURL: string }) => ({ + ...datum, + signedUrl: datum.signedURL + ? encodeURI(`${this.url}${datum.signedURL}${downloadQueryParam}`) + : null, + })), + error: null, + } + } catch (error) { + if (isStorageError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead. + * + * @param path The full path and file name of the file to be downloaded. For example `folder/image.png`. + * @param options.transform Transform the asset before serving it to the client. + */ + async download( + path: string, + options?: { transform?: TransformOptions } + ): Promise< + | { + data: Blob + error: null + } + | { + data: null + error: StorageError + } + > { + const wantsTransformation = typeof options?.transform !== 'undefined' + const renderPath = wantsTransformation ? 'render/image/authenticated' : 'object' + const transformationQuery = this.transformOptsToQueryString(options?.transform || {}) + const queryString = transformationQuery ? `?${transformationQuery}` : '' + + try { + const _path = this._getFinalPath(path) + const res = await get(this.fetch, `${this.url}/${renderPath}/${_path}${queryString}`, { + headers: this.headers, + noResolveJson: true, + }) + const data = await res.blob() + return { data, error: null } + } catch (error) { + if (isStorageError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset. + * This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset. + * + * @param path The path and name of the file to generate the public URL for. For example `folder/image.png`. + * @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + */ + getPublicUrl( + path: string, + options?: { download?: string | boolean; transform?: TransformOptions } + ): { data: { publicUrl: string } } { + const _path = this._getFinalPath(path) + const _queryString = [] + + const downloadQueryParam = options?.download + ? `download=${options.download === true ? '' : options.download}` + : '' + + if (downloadQueryParam !== '') { + _queryString.push(downloadQueryParam) + } + + const wantsTransformation = typeof options?.transform !== 'undefined' + const renderPath = wantsTransformation ? 'render/image' : 'object' + const transformationQuery = this.transformOptsToQueryString(options?.transform || {}) + + if (transformationQuery !== '') { + _queryString.push(transformationQuery) + } + + let queryString = _queryString.join('&') + if (queryString !== '') { + queryString = `?${queryString}` + } + + return { + data: { publicUrl: encodeURI(`${this.url}/${renderPath}/public/${_path}${queryString}`) }, + } + } + + /** + * Deletes files within the same bucket + * + * @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`]. + */ + async remove( + paths: string[] + ): Promise< + | { + data: FileObject[] + error: null + } + | { + data: null + error: StorageError + } + > { + try { + const data = await remove( + this.fetch, + `${this.url}/object/${this.bucketId}`, + { prefixes: paths }, + { headers: this.headers } + ) + return { data, error: null } + } catch (error) { + if (isStorageError(error)) { + return { data: null, error } + } + + throw error + } + } + + /** + * Get file metadata + * @param id the file id to retrieve metadata + */ + // async getMetadata( + // id: string + // ): Promise< + // | { + // data: Metadata + // error: null + // } + // | { + // data: null + // error: StorageError + // } + // > { + // try { + // const data = await get(this.fetch, `${this.url}/metadata/${id}`, { headers: this.headers }) + // return { data, error: null } + // } catch (error) { + // if (isStorageError(error)) { + // return { data: null, error } + // } + + // throw error + // } + // } + + /** + * Update file metadata + * @param id the file id to update metadata + * @param meta the new file metadata + */ + // async updateMetadata( + // id: string, + // meta: Metadata + // ): Promise< + // | { + // data: Metadata + // error: null + // } + // | { + // data: null + // error: StorageError + // } + // > { + // try { + // const data = await post( + // this.fetch, + // `${this.url}/metadata/${id}`, + // { ...meta }, + // { headers: this.headers } + // ) + // return { data, error: null } + // } catch (error) { + // if (isStorageError(error)) { + // return { data: null, error } + // } + + // throw error + // } + // } + + /** + * Lists all the files within a bucket. + * @param path The folder path. + */ + async list( + path?: string, + options?: SearchOptions, + parameters?: FetchParameters + ): Promise< + | { + data: FileObject[] + error: null + } + | { + data: null + error: StorageError + } + > { + try { + const body = { ...DEFAULT_SEARCH_OPTIONS, ...options, prefix: path || '' } + const data = await post( + this.fetch, + `${this.url}/object/list/${this.bucketId}`, + body, + { headers: this.headers }, + parameters + ) + return { data, error: null } + } catch (error) { + if (isStorageError(error)) { + return { data: null, error } + } + + throw error + } + } + + private _getFinalPath(path: string) { + return `${this.bucketId}/${path}` + } + + private _removeEmptyFolders(path: string) { + return path.replace(/^\/|\/$/g, '').replace(/\/+/g, '/') + } + + private transformOptsToQueryString(transform: TransformOptions) { + const params = [] + if (transform.width) { + params.push(`width=${transform.width}`) + } + + if (transform.height) { + params.push(`height=${transform.height}`) + } + + if (transform.resize) { + params.push(`resize=${transform.resize}`) + } + + if (transform.format) { + params.push(`format=${transform.format}`) + } + + if (transform.quality) { + params.push(`quality=${transform.quality}`) + } + + return params.join('&') + } +} diff --git a/node_modules/@supabase/supabase-js/LICENSE b/node_modules/@supabase/supabase-js/LICENSE new file mode 100644 index 0000000..ddeba6a --- /dev/null +++ b/node_modules/@supabase/supabase-js/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Supabase + +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/@supabase/supabase-js/README.md b/node_modules/@supabase/supabase-js/README.md new file mode 100644 index 0000000..50ac1b5 --- /dev/null +++ b/node_modules/@supabase/supabase-js/README.md @@ -0,0 +1,86 @@ +# `supabase-js` + +[![Coverage Status](https://coveralls.io/repos/github/supabase/supabase-js/badge.svg?branch=master)](https://coveralls.io/github/supabase/supabase-js?branch=master) + +An isomorphic JavaScript client for Supabase. + +- **Documentation:** https://supabase.com/docs/reference +- TypeDoc: https://supabase.github.io/supabase-js/v2/ + +## Usage + +First of all, you need to install the library: + +```sh +npm install @supabase/supabase-js +``` + +Then you're able to import the library and establish the connection with the database: + +```js +import { createClient } from '@supabase/supabase-js' + +// Create a single supabase client for interacting with your database +const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key') +``` + +### UMD + +You can now use plain ` +``` + +or even: + +```html + +``` + +Then you can use it from a global `supabase` variable: + +```html + +``` + +### ESM + +You can now use type="module" ` +``` + +### Custom `fetch` implementation + +`supabase-js` uses the [`cross-fetch`](https://www.npmjs.com/package/cross-fetch) library to make HTTP requests, but an alternative `fetch` implementation can be provided as an option. This is most useful in environments where `cross-fetch` is not compatible, for instance Cloudflare Workers: + +```js +import { createClient } from '@supabase/supabase-js' + +// Provide a custom `fetch` implementation as an option +const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key', { + global: { + fetch: (...args) => fetch(...args), + }, +}) +``` + +## Sponsors + +We are building the features of Firebase using enterprise-grade, open source products. We support existing communities wherever possible, and if the products don’t exist we build them and open source them ourselves. Thanks to these sponsors who are making the OSS ecosystem better for everyone. + +[![New Sponsor](https://user-images.githubusercontent.com/10214025/90518111-e74bbb00-e198-11ea-8f88-c9e3c1aa4b5b.png)](https://github.com/sponsors/supabase) diff --git a/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.d.ts b/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.d.ts new file mode 100644 index 0000000..a7f0ba4 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.d.ts @@ -0,0 +1,109 @@ +import { FunctionsClient } from '@supabase/functions-js'; +import { PostgrestClient, PostgrestFilterBuilder, PostgrestQueryBuilder } from '@supabase/postgrest-js'; +import { RealtimeChannel, RealtimeChannelOptions, RealtimeClient } from '@supabase/realtime-js'; +import { StorageClient as SupabaseStorageClient } from '@supabase/storage-js'; +import { SupabaseAuthClient } from './lib/SupabaseAuthClient'; +import { Fetch, GenericSchema, SupabaseClientOptions } from './lib/types'; +/** + * Supabase Client. + * + * An isomorphic Javascript client for interacting with Postgres. + */ +export default class SupabaseClient { + protected supabaseUrl: string; + protected supabaseKey: string; + /** + * Supabase Auth allows you to create and manage user sessions for access to data that is secured by access policies. + */ + auth: SupabaseAuthClient; + realtime: RealtimeClient; + protected realtimeUrl: string; + protected authUrl: string; + protected storageUrl: string; + protected functionsUrl: string; + protected rest: PostgrestClient; + protected storageKey: string; + protected fetch?: Fetch; + protected changedAccessToken?: string; + protected headers: { + [key: string]: string; + }; + /** + * Create a new client for use in the browser. + * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. + * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. + * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. + * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. + * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. + * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. + * @param options.realtime Options passed along to realtime-js constructor. + * @param options.global.fetch A custom fetch implementation. + * @param options.global.headers Any additional headers to send with each network request. + */ + constructor(supabaseUrl: string, supabaseKey: string, options?: SupabaseClientOptions); + /** + * Supabase Functions allows you to deploy and invoke edge functions. + */ + get functions(): FunctionsClient; + /** + * Supabase Storage allows you to manage user-generated content, such as photos or videos. + */ + get storage(): SupabaseStorageClient; + from(relation: TableName): PostgrestQueryBuilder; + from(relation: ViewName): PostgrestQueryBuilder; + from(relation: string): PostgrestQueryBuilder; + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn: FunctionName, args?: Function_['Args'], options?: { + head?: boolean; + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder ? Function_['Returns'][number] : never : never, Function_['Returns']>; + /** + * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. + * + * @param {string} name - The name of the Realtime channel. + * @param {Object} opts - The options to pass to the Realtime channel. + * + */ + channel(name: string, opts?: RealtimeChannelOptions): RealtimeChannel; + /** + * Returns all Realtime channels. + */ + getChannels(): RealtimeChannel[]; + /** + * Unsubscribes and removes Realtime channel from Realtime client. + * + * @param {RealtimeChannel} channel - The name of the Realtime channel. + * + */ + removeChannel(channel: RealtimeChannel): Promise<'ok' | 'timed out' | 'error'>; + /** + * Unsubscribes and removes all Realtime channels from Realtime client. + */ + removeAllChannels(): Promise<('ok' | 'timed out' | 'error')[]>; + private _getAccessToken; + private _initSupabaseAuthClient; + private _initRealtimeClient; + private _listenForAuthEvents; + private _handleTokenChanged; +} +//# sourceMappingURL=SupabaseClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.d.ts.map b/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.d.ts.map new file mode 100644 index 0000000..deefd8d --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SupabaseClient.d.ts","sourceRoot":"","sources":["../../src/SupabaseClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAA;AAExD,OAAO,EACL,eAAe,EACf,sBAAsB,EACtB,qBAAqB,EACtB,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EACL,eAAe,EACf,sBAAsB,EACtB,cAAc,EAEf,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAE,aAAa,IAAI,qBAAqB,EAAE,MAAM,sBAAsB,CAAA;AAI7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AAC7D,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,qBAAqB,EAA6B,MAAM,aAAa,CAAA;AAmBpG;;;;GAIG;AACH,MA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G,OAAO,CAAC;IAI9E;;OAEG;IACH,iBAAiB,IAAI,OAAO,CAAC,CAAC,IAAI,GAAG,WAAW,GAAG,OAAO,CAAC,EAAE,CAAC;YAIhD,eAAe;IAM7B,OAAO,CAAC,uBAAuB;IA+B/B,OAAO,CAAC,mBAAmB;IAO3B,OAAO,CAAC,oBAAoB;IAO5B,OAAO,CAAC,mBAAmB;CAoB5B"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.js b/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.js new file mode 100644 index 0000000..e191bff --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.js @@ -0,0 +1,214 @@ +"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 functions_js_1 = require("@supabase/functions-js"); +const postgrest_js_1 = require("@supabase/postgrest-js"); +const realtime_js_1 = require("@supabase/realtime-js"); +const storage_js_1 = require("@supabase/storage-js"); +const constants_1 = require("./lib/constants"); +const fetch_1 = require("./lib/fetch"); +const helpers_1 = require("./lib/helpers"); +const SupabaseAuthClient_1 = require("./lib/SupabaseAuthClient"); +const DEFAULT_GLOBAL_OPTIONS = { + headers: constants_1.DEFAULT_HEADERS, +}; +const DEFAULT_DB_OPTIONS = { + schema: 'public', +}; +const DEFAULT_AUTH_OPTIONS = { + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + flowType: 'implicit', +}; +const DEFAULT_REALTIME_OPTIONS = {}; +/** + * Supabase Client. + * + * An isomorphic Javascript client for interacting with Postgres. + */ +class SupabaseClient { + /** + * Create a new client for use in the browser. + * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. + * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. + * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. + * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. + * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. + * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. + * @param options.realtime Options passed along to realtime-js constructor. + * @param options.global.fetch A custom fetch implementation. + * @param options.global.headers Any additional headers to send with each network request. + */ + constructor(supabaseUrl, supabaseKey, options) { + var _a, _b, _c, _d, _e, _f, _g, _h; + this.supabaseUrl = supabaseUrl; + this.supabaseKey = supabaseKey; + if (!supabaseUrl) + throw new Error('supabaseUrl is required.'); + if (!supabaseKey) + throw new Error('supabaseKey is required.'); + const _supabaseUrl = (0, helpers_1.stripTrailingSlash)(supabaseUrl); + this.realtimeUrl = `${_supabaseUrl}/realtime/v1`.replace(/^http/i, 'ws'); + this.authUrl = `${_supabaseUrl}/auth/v1`; + this.storageUrl = `${_supabaseUrl}/storage/v1`; + this.functionsUrl = `${_supabaseUrl}/functions/v1`; + // default storage key uses the supabase project ref as a namespace + const defaultStorageKey = `sb-${new URL(this.authUrl).hostname.split('.')[0]}-auth-token`; + const DEFAULTS = { + db: DEFAULT_DB_OPTIONS, + realtime: DEFAULT_REALTIME_OPTIONS, + auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), { storageKey: defaultStorageKey }), + global: DEFAULT_GLOBAL_OPTIONS, + }; + const settings = (0, helpers_1.applySettingDefaults)(options !== null && options !== void 0 ? options : {}, DEFAULTS); + this.storageKey = (_b = (_a = settings.auth) === null || _a === void 0 ? void 0 : _a.storageKey) !== null && _b !== void 0 ? _b : ''; + this.headers = (_d = (_c = settings.global) === null || _c === void 0 ? void 0 : _c.headers) !== null && _d !== void 0 ? _d : {}; + this.auth = this._initSupabaseAuthClient((_e = settings.auth) !== null && _e !== void 0 ? _e : {}, this.headers, (_f = settings.global) === null || _f === void 0 ? void 0 : _f.fetch); + this.fetch = (0, fetch_1.fetchWithAuth)(supabaseKey, this._getAccessToken.bind(this), (_g = settings.global) === null || _g === void 0 ? void 0 : _g.fetch); + this.realtime = this._initRealtimeClient(Object.assign({ headers: this.headers }, settings.realtime)); + this.rest = new postgrest_js_1.PostgrestClient(`${_supabaseUrl}/rest/v1`, { + headers: this.headers, + schema: (_h = settings.db) === null || _h === void 0 ? void 0 : _h.schema, + fetch: this.fetch, + }); + this._listenForAuthEvents(); + } + /** + * Supabase Functions allows you to deploy and invoke edge functions. + */ + get functions() { + return new functions_js_1.FunctionsClient(this.functionsUrl, { + headers: this.headers, + customFetch: this.fetch, + }); + } + /** + * Supabase Storage allows you to manage user-generated content, such as photos or videos. + */ + get storage() { + return new storage_js_1.StorageClient(this.storageUrl, this.headers, this.fetch); + } + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + return this.rest.from(relation); + } + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn, args = {}, options) { + return this.rest.rpc(fn, args, options); + } + /** + * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. + * + * @param {string} name - The name of the Realtime channel. + * @param {Object} opts - The options to pass to the Realtime channel. + * + */ + channel(name, opts = { config: {} }) { + return this.realtime.channel(name, opts); + } + /** + * Returns all Realtime channels. + */ + getChannels() { + return this.realtime.getChannels(); + } + /** + * Unsubscribes and removes Realtime channel from Realtime client. + * + * @param {RealtimeChannel} channel - The name of the Realtime channel. + * + */ + removeChannel(channel) { + return this.realtime.removeChannel(channel); + } + /** + * Unsubscribes and removes all Realtime channels from Realtime client. + */ + removeAllChannels() { + return this.realtime.removeAllChannels(); + } + _getAccessToken() { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + const { data } = yield this.auth.getSession(); + return (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : null; + }); + } + _initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, storageKey, flowType, debug, }, headers, fetch) { + const authHeaders = { + Authorization: `Bearer ${this.supabaseKey}`, + apikey: `${this.supabaseKey}`, + }; + return new SupabaseAuthClient_1.SupabaseAuthClient({ + url: this.authUrl, + headers: Object.assign(Object.assign({}, authHeaders), headers), + storageKey: storageKey, + autoRefreshToken, + persistSession, + detectSessionInUrl, + storage, + flowType, + debug, + fetch, + }); + } + _initRealtimeClient(options) { + return new realtime_js_1.RealtimeClient(this.realtimeUrl, Object.assign(Object.assign({}, options), { params: Object.assign({ apikey: this.supabaseKey }, options === null || options === void 0 ? void 0 : options.params) })); + } + _listenForAuthEvents() { + let data = this.auth.onAuthStateChange((event, session) => { + this._handleTokenChanged(event, 'CLIENT', session === null || session === void 0 ? void 0 : session.access_token); + }); + return data; + } + _handleTokenChanged(event, source, token) { + if ((event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') && + this.changedAccessToken !== token) { + // Token has changed + this.realtime.setAuth(token !== null && token !== void 0 ? token : null); + this.changedAccessToken = token; + } + else if (event === 'SIGNED_OUT') { + // Token is removed + this.realtime.setAuth(this.supabaseKey); + if (source == 'STORAGE') + this.auth.signOut(); + this.changedAccessToken = undefined; + } + } +} +exports.default = SupabaseClient; +//# sourceMappingURL=SupabaseClient.js.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.js.map b/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.js.map new file mode 100644 index 0000000..25ad8d2 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/SupabaseClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SupabaseClient.js","sourceRoot":"","sources":["../../src/SupabaseClient.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,yDAAwD;AAExD,yDAI+B;AAC/B,uDAK8B;AAC9B,qDAA6E;AAC7E,+CAAiD;AACjD,uCAA2C;AAC3C,2CAAwE;AACxE,iEAA6D;AAG7D,MAAM,sBAAsB,GAAG;IAC7B,OAAO,EAAE,2BAAe;CACzB,CAAA;AAED,MAAM,kBAAkB,GAAG;IACzB,MAAM,EAAE,QAAQ;CACjB,CAAA;AAED,MAAM,oBAAoB,GAA8B;IACtD,gBAAgB,EAAE,IAAI;IACtB,cAAc,EAAE,IAAI;IACpB,kBAAkB,EAAE,IAAI;IACxB,QAAQ,EAAE,UAAU;CACrB,CAAA;AAED,MAAM,wBAAwB,GAA0B,EAAE,CAAA;AAE1D;;;;GAIG;AACH,MAAqB,cAAc;IA4BjC;;;;;;;;;;;OAWG;IACH,YACY,WAAmB,EACnB,WAAmB,EAC7B,OAA2C;;QAFjC,gBAAW,GAAX,WAAW,CAAQ;QACnB,gBAAW,GAAX,WAAW,CAAQ;QAG7B,IAAI,CAAC,WAAW;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QAC7D,IAAI,CAAC,WAAW;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QAE7D,MAAM,YAAY,GAAG,IAAA,4BAAkB,EAAC,WAAW,CAAC,CAAA;QAEpD,IAAI,CAAC,WAAW,GAAG,GAAG,YAAY,cAAc,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;QACxE,IAAI,CAAC,OAAO,GAAG,GAAG,YAAY,UAAU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mBAAmB,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,CAAC,CAAA;QAClE,CAAC,CAAC,CAAA;QACF,OAAO,IAAI,CAAA;IACb,CAAC;IAEO,mBAAmB,CACzB,KAAsB,EACtB,MAA4B,EAC5B,KAAc;QAEd,IACE,CAAC,KAAK,KAAK,iBAAiB,IAAI,KAAK,KAAK,WAAW,CAAC;YACtD,IAAI,CAAC,kBAAkB,KAAK,KAAK,EACjC;YACA,oBAAoB;YACpB,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,IAAI,CAAC,CAAA;YAEpC,IAAI,CAAC,kBAAkB,GAAG,KAAK,CAAA;SAChC;aAAM,IAAI,KAAK,KAAK,YAAY,EAAE;YACjC,mBAAmB;YACnB,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAA;YACvC,IAAI,MAAM,IAAI,SAAS;gBAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAA;YAC5C,IAAI,CAAC,kBAAkB,GAAG,SAAS,CAAA;SACpC;IACH,CAAC;CACF;AA7QD,iCA6QC"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/index.d.ts b/node_modules/@supabase/supabase-js/dist/main/index.d.ts new file mode 100644 index 0000000..9b11864 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/index.d.ts @@ -0,0 +1,14 @@ +import SupabaseClient from './SupabaseClient'; +import type { GenericSchema, SupabaseClientOptions } from './lib/types'; +export * from '@supabase/gotrue-js'; +export type { User as AuthUser, Session as AuthSession } from '@supabase/gotrue-js'; +export type { PostgrestResponse, PostgrestSingleResponse, PostgrestMaybeSingleResponse, PostgrestError, } from '@supabase/postgrest-js'; +export { FunctionsHttpError, FunctionsFetchError, FunctionsRelayError, FunctionsError, } from '@supabase/functions-js'; +export * from '@supabase/realtime-js'; +export { default as SupabaseClient } from './SupabaseClient'; +export type { SupabaseClientOptions } from './lib/types'; +/** + * Creates a new Supabase Client. + */ +export declare const createClient: (supabaseUrl: string, supabaseKey: string, options?: SupabaseClientOptions | undefined) => SupabaseClient; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/index.d.ts.map b/node_modules/@supabase/supabase-js/dist/main/index.d.ts.map new file mode 100644 index 0000000..f3209c4 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAC7C,OAAO,KAAK,EAAE,aAAa,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAA;AAEvE,cAAc,qBAAqB,CAAA;AACnC,YAAY,EAAE,IAAI,IAAI,QAAQ,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,qBAAqB,CAAA;AACnF,YAAY,EACV,iBAAiB,EACjB,uBAAuB,EACvB,4BAA4B,EAC5B,cAAc,GACf,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,EACnB,cAAc,GACf,MAAM,wBAAwB,CAAA;AAC/B,cAAc,uBAAuB,CAAA;AACrC,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,kBAAkB,CAAA;AAC5D,YAAY,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAA;AAExD;;GAEG;AACH,eAAO,MAAM,YAAY,2PASV,MAAM,eACN,MAAM,0GAIpB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/index.js b/node_modules/@supabase/supabase-js/dist/main/index.js new file mode 100644 index 0000000..44cbc97 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/index.js @@ -0,0 +1,38 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createClient = exports.SupabaseClient = exports.FunctionsError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsHttpError = void 0; +const SupabaseClient_1 = __importDefault(require("./SupabaseClient")); +__exportStar(require("@supabase/gotrue-js"), exports); +var functions_js_1 = require("@supabase/functions-js"); +Object.defineProperty(exports, "FunctionsHttpError", { enumerable: true, get: function () { return functions_js_1.FunctionsHttpError; } }); +Object.defineProperty(exports, "FunctionsFetchError", { enumerable: true, get: function () { return functions_js_1.FunctionsFetchError; } }); +Object.defineProperty(exports, "FunctionsRelayError", { enumerable: true, get: function () { return functions_js_1.FunctionsRelayError; } }); +Object.defineProperty(exports, "FunctionsError", { enumerable: true, get: function () { return functions_js_1.FunctionsError; } }); +__exportStar(require("@supabase/realtime-js"), exports); +var SupabaseClient_2 = require("./SupabaseClient"); +Object.defineProperty(exports, "SupabaseClient", { enumerable: true, get: function () { return __importDefault(SupabaseClient_2).default; } }); +/** + * Creates a new Supabase Client. + */ +const createClient = (supabaseUrl, supabaseKey, options) => { + return new SupabaseClient_1.default(supabaseUrl, supabaseKey, options); +}; +exports.createClient = createClient; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/index.js.map b/node_modules/@supabase/supabase-js/dist/main/index.js.map new file mode 100644 index 0000000..3a93819 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,sEAA6C;AAG7C,sDAAmC;AAQnC,uDAK+B;AAJ7B,kHAAA,kBAAkB,OAAA;AAClB,mHAAA,mBAAmB,OAAA;AACnB,mHAAA,mBAAmB,OAAA;AACnB,8GAAA,cAAc,OAAA;AAEhB,wDAAqC;AACrC,mDAA4D;AAAnD,iIAAA,OAAO,OAAkB;AAGlC;;GAEG;AACI,MAAM,YAAY,GAAG,CAS1B,WAAmB,EACnB,WAAmB,EACnB,OAA2C,EACG,EAAE;IAChD,OAAO,IAAI,wBAAc,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,CAAC,CAAA;AAC9D,CAAC,CAAA;AAdY,QAAA,YAAY,gBAcxB"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.d.ts b/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.d.ts new file mode 100644 index 0000000..24b89b8 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.d.ts @@ -0,0 +1,6 @@ +import { GoTrueClient } from '@supabase/gotrue-js'; +import { SupabaseAuthClientOptions } from './types'; +export declare class SupabaseAuthClient extends GoTrueClient { + constructor(options: SupabaseAuthClientOptions); +} +//# sourceMappingURL=SupabaseAuthClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.d.ts.map b/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.d.ts.map new file mode 100644 index 0000000..ca506a9 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SupabaseAuthClient.d.ts","sourceRoot":"","sources":["../../../src/lib/SupabaseAuthClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAA;AAEnD,qBAAa,kBAAmB,SAAQ,YAAY;gBACtC,OAAO,EAAE,yBAAyB;CAG/C"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.js b/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.js new file mode 100644 index 0000000..2887ea6 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SupabaseAuthClient = void 0; +const gotrue_js_1 = require("@supabase/gotrue-js"); +class SupabaseAuthClient extends gotrue_js_1.GoTrueClient { + constructor(options) { + super(options); + } +} +exports.SupabaseAuthClient = SupabaseAuthClient; +//# sourceMappingURL=SupabaseAuthClient.js.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.js.map b/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.js.map new file mode 100644 index 0000000..8d83c99 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SupabaseAuthClient.js","sourceRoot":"","sources":["../../../src/lib/SupabaseAuthClient.ts"],"names":[],"mappings":";;;AAAA,mDAAkD;AAGlD,MAAa,kBAAmB,SAAQ,wBAAY;IAClD,YAAY,OAAkC;QAC5C,KAAK,CAAC,OAAO,CAAC,CAAA;IAChB,CAAC;CACF;AAJD,gDAIC"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/constants.d.ts b/node_modules/@supabase/supabase-js/dist/main/lib/constants.d.ts new file mode 100644 index 0000000..12eb562 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/constants.d.ts @@ -0,0 +1,4 @@ +export declare const DEFAULT_HEADERS: { + 'X-Client-Info': string; +}; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/constants.d.ts.map b/node_modules/@supabase/supabase-js/dist/main/lib/constants.d.ts.map new file mode 100644 index 0000000..369da41 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe;;CAAgD,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/constants.js b/node_modules/@supabase/supabase-js/dist/main/lib/constants.js new file mode 100644 index 0000000..8a29f5f --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/constants.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_HEADERS = void 0; +// constants.ts +const version_1 = require("./version"); +exports.DEFAULT_HEADERS = { 'X-Client-Info': `supabase-js/${version_1.version}` }; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/constants.js.map b/node_modules/@supabase/supabase-js/dist/main/lib/constants.js.map new file mode 100644 index 0000000..0b25ff3 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":";;;AAAA,eAAe;AACf,uCAAmC;AACtB,QAAA,eAAe,GAAG,EAAE,eAAe,EAAE,eAAe,iBAAO,EAAE,EAAE,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/fetch.d.ts b/node_modules/@supabase/supabase-js/dist/main/lib/fetch.d.ts new file mode 100644 index 0000000..a75140f --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/fetch.d.ts @@ -0,0 +1,9 @@ +declare type Fetch = typeof fetch; +export declare const resolveFetch: (customFetch?: Fetch) => Fetch; +export declare const resolveHeadersConstructor: () => { + new (init?: HeadersInit | undefined): Headers; + prototype: Headers; +}; +export declare const fetchWithAuth: (supabaseKey: string, getAccessToken: () => Promise, customFetch?: Fetch) => Fetch; +export {}; +//# sourceMappingURL=fetch.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/fetch.d.ts.map b/node_modules/@supabase/supabase-js/dist/main/lib/fetch.d.ts.map new file mode 100644 index 0000000..99da343 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/fetch.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AAEA,aAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,iBAAkB,KAAK,KAAG,KAUlD,CAAA;AAED,eAAO,MAAM,yBAAyB;;;CAMrC,CAAA;AAED,eAAO,MAAM,aAAa,gBACX,MAAM,kBACH,MAAM,QAAQ,MAAM,GAAG,IAAI,CAAC,gBAC9B,KAAK,KAClB,KAkBF,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/fetch.js b/node_modules/@supabase/supabase-js/dist/main/lib/fetch.js new file mode 100644 index 0000000..66bc70d --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/fetch.js @@ -0,0 +1,75 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +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 }); +exports.fetchWithAuth = exports.resolveHeadersConstructor = exports.resolveFetch = void 0; +const cross_fetch_1 = __importStar(require("cross-fetch")); +const resolveFetch = (customFetch) => { + let _fetch; + if (customFetch) { + _fetch = customFetch; + } + else if (typeof fetch === 'undefined') { + _fetch = cross_fetch_1.default; + } + else { + _fetch = fetch; + } + return (...args) => _fetch(...args); +}; +exports.resolveFetch = resolveFetch; +const resolveHeadersConstructor = () => { + if (typeof Headers === 'undefined') { + return cross_fetch_1.Headers; + } + return Headers; +}; +exports.resolveHeadersConstructor = resolveHeadersConstructor; +const fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => { + const fetch = (0, exports.resolveFetch)(customFetch); + const HeadersConstructor = (0, exports.resolveHeadersConstructor)(); + return (input, init) => __awaiter(void 0, void 0, void 0, function* () { + var _a; + const accessToken = (_a = (yield getAccessToken())) !== null && _a !== void 0 ? _a : supabaseKey; + let headers = new HeadersConstructor(init === null || init === void 0 ? void 0 : init.headers); + if (!headers.has('apikey')) { + headers.set('apikey', supabaseKey); + } + if (!headers.has('Authorization')) { + headers.set('Authorization', `Bearer ${accessToken}`); + } + return fetch(input, Object.assign(Object.assign({}, init), { headers })); + }); +}; +exports.fetchWithAuth = fetchWithAuth; +//# sourceMappingURL=fetch.js.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/fetch.js.map b/node_modules/@supabase/supabase-js/dist/main/lib/fetch.js.map new file mode 100644 index 0000000..aaf8fb5 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/fetch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2DAAsE;AAI/D,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAS,EAAE;IACzD,IAAI,MAAa,CAAA;IACjB,IAAI,WAAW,EAAE;QACf,MAAM,GAAG,WAAW,CAAA;KACrB;SAAM,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;QACvC,MAAM,GAAG,qBAA8B,CAAA;KACxC;SAAM;QACL,MAAM,GAAG,KAAK,CAAA;KACf;IACD,OAAO,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA;AAVY,QAAA,YAAY,gBAUxB;AAEM,MAAM,yBAAyB,GAAG,GAAG,EAAE;IAC5C,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;QAClC,OAAO,qBAAiB,CAAA;KACzB;IAED,OAAO,OAAO,CAAA;AAChB,CAAC,CAAA;AANY,QAAA,yBAAyB,6BAMrC;AAEM,MAAM,aAAa,GAAG,CAC3B,WAAmB,EACnB,cAA4C,EAC5C,WAAmB,EACZ,EAAE;IACT,MAAM,KAAK,GAAG,IAAA,oBAAY,EAAC,WAAW,CAAC,CAAA;IACvC,MAAM,kBAAkB,GAAG,IAAA,iCAAyB,GAAE,CAAA;IAEtD,OAAO,CAAO,KAAK,EAAE,IAAI,EAAE,EAAE;;QAC3B,MAAM,WAAW,GAAG,MAAA,CAAC,MAAM,cAAc,EAAE,CAAC,mCAAI,WAAW,CAAA;QAC3D,IAAI,OAAO,GAAG,IAAI,kBAAkB,CAAC,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,CAAC,CAAA;QAEnD,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE;YAC1B,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAA;SACnC;QAED,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE;YACjC,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,WAAW,EAAE,CAAC,CAAA;SACtD;QAED,OAAO,KAAK,CAAC,KAAK,kCAAO,IAAI,KAAE,OAAO,IAAG,CAAA;IAC3C,CAAC,CAAA,CAAA;AACH,CAAC,CAAA;AAtBY,QAAA,aAAa,iBAsBzB"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/helpers.d.ts b/node_modules/@supabase/supabase-js/dist/main/lib/helpers.d.ts new file mode 100644 index 0000000..c54283a --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/helpers.d.ts @@ -0,0 +1,6 @@ +import { SupabaseClientOptions } from './types'; +export declare function uuid(): string; +export declare function stripTrailingSlash(url: string): string; +export declare const isBrowser: () => boolean; +export declare function applySettingDefaults(options: SupabaseClientOptions, defaults: SupabaseClientOptions): SupabaseClientOptions; +//# sourceMappingURL=helpers.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/helpers.d.ts.map b/node_modules/@supabase/supabase-js/dist/main/lib/helpers.d.ts.map new file mode 100644 index 0000000..2fbe2ba --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAA;AAE/C,wBAAgB,IAAI,WAMnB;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEtD;AAED,eAAO,MAAM,SAAS,eAAsC,CAAA;AAE5D,wBAAgB,oBAAoB,CAClC,QAAQ,GAAG,GAAG,EACd,UAAU,SAAS,MAAM,GAAG,MAAM,QAAQ,GAAG,QAAQ,SAAS,MAAM,QAAQ,GACxE,QAAQ,GACR,MAAM,GAAG,MAAM,QAAQ,EAE3B,OAAO,EAAE,qBAAqB,CAAC,UAAU,CAAC,EAC1C,QAAQ,EAAE,qBAAqB,CAAC,GAAG,CAAC,GACnC,qBAAqB,CAAC,UAAU,CAAC,CAgCnC"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/helpers.js b/node_modules/@supabase/supabase-js/dist/main/lib/helpers.js new file mode 100644 index 0000000..8d02cf4 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/helpers.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.applySettingDefaults = exports.isBrowser = exports.stripTrailingSlash = exports.uuid = void 0; +function uuid() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +} +exports.uuid = uuid; +function stripTrailingSlash(url) { + return url.replace(/\/$/, ''); +} +exports.stripTrailingSlash = stripTrailingSlash; +const isBrowser = () => typeof window !== 'undefined'; +exports.isBrowser = isBrowser; +function applySettingDefaults(options, defaults) { + const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions, } = options; + const { db: DEFAULT_DB_OPTIONS, auth: DEFAULT_AUTH_OPTIONS, realtime: DEFAULT_REALTIME_OPTIONS, global: DEFAULT_GLOBAL_OPTIONS, } = defaults; + return { + db: Object.assign(Object.assign({}, DEFAULT_DB_OPTIONS), dbOptions), + auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), authOptions), + realtime: Object.assign(Object.assign({}, DEFAULT_REALTIME_OPTIONS), realtimeOptions), + global: Object.assign(Object.assign({}, DEFAULT_GLOBAL_OPTIONS), globalOptions), + }; +} +exports.applySettingDefaults = applySettingDefaults; +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/helpers.js.map b/node_modules/@supabase/supabase-js/dist/main/lib/helpers.js.map new file mode 100644 index 0000000..21ea74d --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":";;;AAGA,SAAgB,IAAI;IAClB,OAAO,sCAAsC,CAAC,OAAO,CAAC,OAAO,EAAE,UAAU,CAAC;QACxE,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EAC9B,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,GAAG,GAAG,CAAA;QACpC,OAAO,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAA;IACvB,CAAC,CAAC,CAAA;AACJ,CAAC;AAND,oBAMC;AAED,SAAgB,kBAAkB,CAAC,GAAW;IAC5C,OAAO,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAA;AAC/B,CAAC;AAFD,gDAEC;AAEM,MAAM,SAAS,GAAG,GAAG,EAAE,CAAC,OAAO,MAAM,KAAK,WAAW,CAAA;AAA/C,QAAA,SAAS,aAAsC;AAE5D,SAAgB,oBAAoB,CAMlC,OAA0C,EAC1C,QAAoC;IAEpC,MAAM,EACJ,EAAE,EAAE,SAAS,EACb,IAAI,EAAE,WAAW,EACjB,QAAQ,EAAE,eAAe,EACzB,MAAM,EAAE,aAAa,GACtB,GAAG,OAAO,CAAA;IACX,MAAM,EACJ,EAAE,EAAE,kBAAkB,EACtB,IAAI,EAAE,oBAAoB,EAC1B,QAAQ,EAAE,wBAAwB,EAClC,MAAM,EAAE,sBAAsB,GAC/B,GAAG,QAAQ,CAAA;IAEZ,OAAO;QACL,EAAE,kCACG,kBAAkB,GAClB,SAAS,CACb;QACD,IAAI,kCACC,oBAAoB,GACpB,WAAW,CACf;QACD,QAAQ,kCACH,wBAAwB,GACxB,eAAe,CACnB;QACD,MAAM,kCACD,sBAAsB,GACtB,aAAa,CACjB;KACF,CAAA;AACH,CAAC;AAxCD,oDAwCC"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/types.d.ts b/node_modules/@supabase/supabase-js/dist/main/lib/types.d.ts new file mode 100644 index 0000000..af5481d --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/types.d.ts @@ -0,0 +1,83 @@ +import { GoTrueClient } from '@supabase/gotrue-js'; +import { RealtimeClientOptions } from '@supabase/realtime-js'; +declare type GoTrueClientOptions = ConstructorParameters[0]; +export interface SupabaseAuthClientOptions extends GoTrueClientOptions { +} +export declare type Fetch = typeof fetch; +export declare type SupabaseClientOptions = { + /** + * The Postgres schema which your tables belong to. Must be on the list of exposed schemas in Supabase. Defaults to `public`. + */ + db?: { + schema?: SchemaName; + }; + auth?: { + /** + * Automatically refreshes the token for logged-in users. Defaults to true. + */ + autoRefreshToken?: boolean; + /** + * Optional key name used for storing tokens in local storage. + */ + storageKey?: string; + /** + * Whether to persist a logged-in session to storage. Defaults to true. + */ + persistSession?: boolean; + /** + * Detect a session from the URL. Used for OAuth login callbacks. Defaults to true. + */ + detectSessionInUrl?: boolean; + /** + * A storage provider. Used to store the logged-in session. + */ + storage?: SupabaseAuthClientOptions['storage']; + /** + * OAuth flow to use - defaults to implicit flow. PKCE is recommended for mobile and server-side applications. + */ + flowType?: SupabaseAuthClientOptions['flowType']; + /** + * If debug messages for authentication client are emitted. Can be used to inspect the behavior of the library. + */ + debug?: boolean; + }; + /** + * Options passed to the realtime-js instance + */ + realtime?: RealtimeClientOptions; + global?: { + /** + * A custom `fetch` implementation. + */ + fetch?: Fetch; + /** + * Optional headers for initializing the client. + */ + headers?: Record; + }; +}; +export declare type GenericTable = { + Row: Record; + Insert: Record; + Update: Record; +}; +export declare type GenericUpdatableView = { + Row: Record; + Insert: Record; + Update: Record; +}; +export declare type GenericNonUpdatableView = { + Row: Record; +}; +export declare type GenericView = GenericUpdatableView | GenericNonUpdatableView; +export declare type GenericFunction = { + Args: Record; + Returns: unknown; +}; +export declare type GenericSchema = { + Tables: Record; + Views: Record; + Functions: Record; +}; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/types.d.ts.map b/node_modules/@supabase/supabase-js/dist/main/lib/types.d.ts.map new file mode 100644 index 0000000..3a25742 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAA;AAE7D,aAAK,mBAAmB,GAAG,qBAAqB,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,CAAA;AAExE,MAAM,WAAW,yBAA0B,SAAQ,mBAAmB;CAAG;AAEzE,oBAAY,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC,oBAAY,qBAAqB,CAAC,UAAU,IAAI;IAC9C;;OAEG;IACH,EAAE,CAAC,EAAE;QACH,MAAM,CAAC,EAAE,UAAU,CAAA;KACpB,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uB,CAAA;AAExE,oBAAY,eAAe,GAAG;IAC5B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC7B,OAAO,EAAE,OAAO,CAAA;CACjB,CAAA;AAED,oBAAY,aAAa,GAAG;IAC1B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAA;IACpC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAA;IAClC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAA;CAC3C,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/types.js b/node_modules/@supabase/supabase-js/dist/main/lib/types.js new file mode 100644 index 0000000..11e638d --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/types.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/types.js.map b/node_modules/@supabase/supabase-js/dist/main/lib/types.js.map new file mode 100644 index 0000000..5bb5e4d --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/version.d.ts b/node_modules/@supabase/supabase-js/dist/main/lib/version.d.ts new file mode 100644 index 0000000..f7ec3d5 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.31.0"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/version.d.ts.map b/node_modules/@supabase/supabase-js/dist/main/lib/version.d.ts.map new file mode 100644 index 0000000..7c1c990 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,oBAAoB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/version.js b/node_modules/@supabase/supabase-js/dist/main/lib/version.js new file mode 100644 index 0000000..6c71902 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/version.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.version = void 0; +exports.version = '2.31.0'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/main/lib/version.js.map b/node_modules/@supabase/supabase-js/dist/main/lib/version.js.map new file mode 100644 index 0000000..a69abef --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/main/lib/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":";;;AAAa,QAAA,OAAO,GAAG,iBAAiB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.d.ts b/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.d.ts new file mode 100644 index 0000000..a7f0ba4 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.d.ts @@ -0,0 +1,109 @@ +import { FunctionsClient } from '@supabase/functions-js'; +import { PostgrestClient, PostgrestFilterBuilder, PostgrestQueryBuilder } from '@supabase/postgrest-js'; +import { RealtimeChannel, RealtimeChannelOptions, RealtimeClient } from '@supabase/realtime-js'; +import { StorageClient as SupabaseStorageClient } from '@supabase/storage-js'; +import { SupabaseAuthClient } from './lib/SupabaseAuthClient'; +import { Fetch, GenericSchema, SupabaseClientOptions } from './lib/types'; +/** + * Supabase Client. + * + * An isomorphic Javascript client for interacting with Postgres. + */ +export default class SupabaseClient { + protected supabaseUrl: string; + protected supabaseKey: string; + /** + * Supabase Auth allows you to create and manage user sessions for access to data that is secured by access policies. + */ + auth: SupabaseAuthClient; + realtime: RealtimeClient; + protected realtimeUrl: string; + protected authUrl: string; + protected storageUrl: string; + protected functionsUrl: string; + protected rest: PostgrestClient; + protected storageKey: string; + protected fetch?: Fetch; + protected changedAccessToken?: string; + protected headers: { + [key: string]: string; + }; + /** + * Create a new client for use in the browser. + * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. + * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. + * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. + * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. + * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. + * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. + * @param options.realtime Options passed along to realtime-js constructor. + * @param options.global.fetch A custom fetch implementation. + * @param options.global.headers Any additional headers to send with each network request. + */ + constructor(supabaseUrl: string, supabaseKey: string, options?: SupabaseClientOptions); + /** + * Supabase Functions allows you to deploy and invoke edge functions. + */ + get functions(): FunctionsClient; + /** + * Supabase Storage allows you to manage user-generated content, such as photos or videos. + */ + get storage(): SupabaseStorageClient; + from(relation: TableName): PostgrestQueryBuilder; + from(relation: ViewName): PostgrestQueryBuilder; + from(relation: string): PostgrestQueryBuilder; + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn: FunctionName, args?: Function_['Args'], options?: { + head?: boolean; + count?: 'exact' | 'planned' | 'estimated'; + }): PostgrestFilterBuilder ? Function_['Returns'][number] : never : never, Function_['Returns']>; + /** + * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. + * + * @param {string} name - The name of the Realtime channel. + * @param {Object} opts - The options to pass to the Realtime channel. + * + */ + channel(name: string, opts?: RealtimeChannelOptions): RealtimeChannel; + /** + * Returns all Realtime channels. + */ + getChannels(): RealtimeChannel[]; + /** + * Unsubscribes and removes Realtime channel from Realtime client. + * + * @param {RealtimeChannel} channel - The name of the Realtime channel. + * + */ + removeChannel(channel: RealtimeChannel): Promise<'ok' | 'timed out' | 'error'>; + /** + * Unsubscribes and removes all Realtime channels from Realtime client. + */ + removeAllChannels(): Promise<('ok' | 'timed out' | 'error')[]>; + private _getAccessToken; + private _initSupabaseAuthClient; + private _initRealtimeClient; + private _listenForAuthEvents; + private _handleTokenChanged; +} +//# sourceMappingURL=SupabaseClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.d.ts.map b/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.d.ts.map new file mode 100644 index 0000000..deefd8d --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SupabaseClient.d.ts","sourceRoot":"","sources":["../../src/SupabaseClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAA;AAExD,OAAO,EACL,eAAe,EACf,sBAAsB,EACtB,qBAAqB,EACtB,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EACL,eAAe,EACf,sBAAsB,EACtB,cAAc,EAEf,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAE,aAAa,IAAI,qBAAqB,EAAE,MAAM,sBAAsB,CAAA;AAI7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AAC7D,OAAO,EAAE,KAAK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KG;IACH,aAAa,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,GAAG,WAAW,GAAG,OAAO,CAAC;IAI9E;;OAEG;IACH,iBAAiB,IAAI,OAAO,CAAC,CAAC,IAAI,GAAG,WAAW,GAAG,OAAO,CAAC,EAAE,CAAC;YAIhD,eAAe;IAM7B,OAAO,CAAC,uBAAuB;IA+B/B,OAAO,CAAC,mBAAmB;IAO3B,OAAO,CAAC,oBAAoB;IAO5B,OAAO,CAAC,mBAAmB;CAoB5B"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.js b/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.js new file mode 100644 index 0000000..d1dcac1 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.js @@ -0,0 +1,211 @@ +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 { FunctionsClient } from '@supabase/functions-js'; +import { PostgrestClient, } from '@supabase/postgrest-js'; +import { RealtimeClient, } from '@supabase/realtime-js'; +import { StorageClient as SupabaseStorageClient } from '@supabase/storage-js'; +import { DEFAULT_HEADERS } from './lib/constants'; +import { fetchWithAuth } from './lib/fetch'; +import { stripTrailingSlash, applySettingDefaults } from './lib/helpers'; +import { SupabaseAuthClient } from './lib/SupabaseAuthClient'; +const DEFAULT_GLOBAL_OPTIONS = { + headers: DEFAULT_HEADERS, +}; +const DEFAULT_DB_OPTIONS = { + schema: 'public', +}; +const DEFAULT_AUTH_OPTIONS = { + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + flowType: 'implicit', +}; +const DEFAULT_REALTIME_OPTIONS = {}; +/** + * Supabase Client. + * + * An isomorphic Javascript client for interacting with Postgres. + */ +export default class SupabaseClient { + /** + * Create a new client for use in the browser. + * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. + * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. + * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. + * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. + * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. + * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. + * @param options.realtime Options passed along to realtime-js constructor. + * @param options.global.fetch A custom fetch implementation. + * @param options.global.headers Any additional headers to send with each network request. + */ + constructor(supabaseUrl, supabaseKey, options) { + var _a, _b, _c, _d, _e, _f, _g, _h; + this.supabaseUrl = supabaseUrl; + this.supabaseKey = supabaseKey; + if (!supabaseUrl) + throw new Error('supabaseUrl is required.'); + if (!supabaseKey) + throw new Error('supabaseKey is required.'); + const _supabaseUrl = stripTrailingSlash(supabaseUrl); + this.realtimeUrl = `${_supabaseUrl}/realtime/v1`.replace(/^http/i, 'ws'); + this.authUrl = `${_supabaseUrl}/auth/v1`; + this.storageUrl = `${_supabaseUrl}/storage/v1`; + this.functionsUrl = `${_supabaseUrl}/functions/v1`; + // default storage key uses the supabase project ref as a namespace + const defaultStorageKey = `sb-${new URL(this.authUrl).hostname.split('.')[0]}-auth-token`; + const DEFAULTS = { + db: DEFAULT_DB_OPTIONS, + realtime: DEFAULT_REALTIME_OPTIONS, + auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), { storageKey: defaultStorageKey }), + global: DEFAULT_GLOBAL_OPTIONS, + }; + const settings = applySettingDefaults(options !== null && options !== void 0 ? options : {}, DEFAULTS); + this.storageKey = (_b = (_a = settings.auth) === null || _a === void 0 ? void 0 : _a.storageKey) !== null && _b !== void 0 ? _b : ''; + this.headers = (_d = (_c = settings.global) === null || _c === void 0 ? void 0 : _c.headers) !== null && _d !== void 0 ? _d : {}; + this.auth = this._initSupabaseAuthClient((_e = settings.auth) !== null && _e !== void 0 ? _e : {}, this.headers, (_f = settings.global) === null || _f === void 0 ? void 0 : _f.fetch); + this.fetch = fetchWithAuth(supabaseKey, this._getAccessToken.bind(this), (_g = settings.global) === null || _g === void 0 ? void 0 : _g.fetch); + this.realtime = this._initRealtimeClient(Object.assign({ headers: this.headers }, settings.realtime)); + this.rest = new PostgrestClient(`${_supabaseUrl}/rest/v1`, { + headers: this.headers, + schema: (_h = settings.db) === null || _h === void 0 ? void 0 : _h.schema, + fetch: this.fetch, + }); + this._listenForAuthEvents(); + } + /** + * Supabase Functions allows you to deploy and invoke edge functions. + */ + get functions() { + return new FunctionsClient(this.functionsUrl, { + headers: this.headers, + customFetch: this.fetch, + }); + } + /** + * Supabase Storage allows you to manage user-generated content, such as photos or videos. + */ + get storage() { + return new SupabaseStorageClient(this.storageUrl, this.headers, this.fetch); + } + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + return this.rest.from(relation); + } + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn, args = {}, options) { + return this.rest.rpc(fn, args, options); + } + /** + * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. + * + * @param {string} name - The name of the Realtime channel. + * @param {Object} opts - The options to pass to the Realtime channel. + * + */ + channel(name, opts = { config: {} }) { + return this.realtime.channel(name, opts); + } + /** + * Returns all Realtime channels. + */ + getChannels() { + return this.realtime.getChannels(); + } + /** + * Unsubscribes and removes Realtime channel from Realtime client. + * + * @param {RealtimeChannel} channel - The name of the Realtime channel. + * + */ + removeChannel(channel) { + return this.realtime.removeChannel(channel); + } + /** + * Unsubscribes and removes all Realtime channels from Realtime client. + */ + removeAllChannels() { + return this.realtime.removeAllChannels(); + } + _getAccessToken() { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + const { data } = yield this.auth.getSession(); + return (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : null; + }); + } + _initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, storageKey, flowType, debug, }, headers, fetch) { + const authHeaders = { + Authorization: `Bearer ${this.supabaseKey}`, + apikey: `${this.supabaseKey}`, + }; + return new SupabaseAuthClient({ + url: this.authUrl, + headers: Object.assign(Object.assign({}, authHeaders), headers), + storageKey: storageKey, + autoRefreshToken, + persistSession, + detectSessionInUrl, + storage, + flowType, + debug, + fetch, + }); + } + _initRealtimeClient(options) { + return new RealtimeClient(this.realtimeUrl, Object.assign(Object.assign({}, options), { params: Object.assign({ apikey: this.supabaseKey }, options === null || options === void 0 ? void 0 : options.params) })); + } + _listenForAuthEvents() { + let data = this.auth.onAuthStateChange((event, session) => { + this._handleTokenChanged(event, 'CLIENT', session === null || session === void 0 ? void 0 : session.access_token); + }); + return data; + } + _handleTokenChanged(event, source, token) { + if ((event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') && + this.changedAccessToken !== token) { + // Token has changed + this.realtime.setAuth(token !== null && token !== void 0 ? token : null); + this.changedAccessToken = token; + } + else if (event === 'SIGNED_OUT') { + // Token is removed + this.realtime.setAuth(this.supabaseKey); + if (source == 'STORAGE') + this.auth.signOut(); + this.changedAccessToken = undefined; + } + } +} +//# sourceMappingURL=SupabaseClient.js.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.js.map b/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.js.map new file mode 100644 index 0000000..a43524c --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/SupabaseClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SupabaseClient.js","sourceRoot":"","sources":["../../src/SupabaseClient.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAA;AAExD,OAAO,EACL,eAAe,GAGhB,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EAGL,cAAc,GAEf,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAE,aAAa,IAAI,qBAAqB,EAAE,MAAM,sBAAsB,CAAA;AAC7E,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAA;AACxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AAG7D,MAAM,sBAAsB,GAAG;IAC7B,OAAO,EAAE,eAAe;CACzB,CAAA;AAED,MAAM,kBAAkB,GAAG;IACzB,MAAM,EAAE,QAAQ;CACjB,CAAA;AAED,MAAM,oBAAoB,GAA8B;IACtD,gBAAgB,EAAE,IAAI;IACtB,cAAc,EAAE,IAAI;IACpB,kBAAkB,EAAE,IAAI;IACxB,QAAQ,EAAE,UAAU;CACrB,CAAA;AAED,MAAM,wBAAwB,GAA0B,EAAE,CAAA;AAE1D;;;;GAIG;AACH,MAAM,CAAC,OAAO,OAAO,cAAc;IA4BjC;;;;;;;;;;;OAWG;IACH,YACY,WAAmB,EACnB,WAAmB,EAC7B,OAA2C;;QAFjC,gBAAW,GAAX,WAAW,CAAQ;QACnB,gBAAW,GAAX,WAAW,CAAQ;QAG7B,IAAI,CAAC,WAAW;YAAE,MAAM,IAAI,KAAK,CAAC,0B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kCACrC,OAAO,KACV,MAAM,gBAAO,EAAE,MAAM,EAAE,IAAI,CAAC,WAAW,EAAE,EAAK,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM,KAC7D,CAAA;IACJ,CAAC;IAEO,oBAAoB;QAC1B,IAAI,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;YACxD,IAAI,CAAC,mBAAmB,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,CAAC,CAAA;QAClE,CAAC,CAAC,CAAA;QACF,OAAO,IAAI,CAAA;IACb,CAAC;IAEO,mBAAmB,CACzB,KAAsB,EACtB,MAA4B,EAC5B,KAAc;QAEd,IACE,CAAC,KAAK,KAAK,iBAAiB,IAAI,KAAK,KAAK,WAAW,CAAC;YACtD,IAAI,CAAC,kBAAkB,KAAK,KAAK,EACjC;YACA,oBAAoB;YACpB,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,IAAI,CAAC,CAAA;YAEpC,IAAI,CAAC,kBAAkB,GAAG,KAAK,CAAA;SAChC;aAAM,IAAI,KAAK,KAAK,YAAY,EAAE;YACjC,mBAAmB;YACnB,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAA;YACvC,IAAI,MAAM,IAAI,SAAS;gBAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAA;YAC5C,IAAI,CAAC,kBAAkB,GAAG,SAAS,CAAA;SACpC;IACH,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/index.d.ts b/node_modules/@supabase/supabase-js/dist/module/index.d.ts new file mode 100644 index 0000000..9b11864 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/index.d.ts @@ -0,0 +1,14 @@ +import SupabaseClient from './SupabaseClient'; +import type { GenericSchema, SupabaseClientOptions } from './lib/types'; +export * from '@supabase/gotrue-js'; +export type { User as AuthUser, Session as AuthSession } from '@supabase/gotrue-js'; +export type { PostgrestResponse, PostgrestSingleResponse, PostgrestMaybeSingleResponse, PostgrestError, } from '@supabase/postgrest-js'; +export { FunctionsHttpError, FunctionsFetchError, FunctionsRelayError, FunctionsError, } from '@supabase/functions-js'; +export * from '@supabase/realtime-js'; +export { default as SupabaseClient } from './SupabaseClient'; +export type { SupabaseClientOptions } from './lib/types'; +/** + * Creates a new Supabase Client. + */ +export declare const createClient: (supabaseUrl: string, supabaseKey: string, options?: SupabaseClientOptions | undefined) => SupabaseClient; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/index.d.ts.map b/node_modules/@supabase/supabase-js/dist/module/index.d.ts.map new file mode 100644 index 0000000..f3209c4 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAC7C,OAAO,KAAK,EAAE,aAAa,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAA;AAEvE,cAAc,qBAAqB,CAAA;AACnC,YAAY,EAAE,IAAI,IAAI,QAAQ,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,qBAAqB,CAAA;AACnF,YAAY,EACV,iBAAiB,EACjB,uBAAuB,EACvB,4BAA4B,EAC5B,cAAc,GACf,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,EACnB,cAAc,GACf,MAAM,wBAAwB,CAAA;AAC/B,cAAc,uBAAuB,CAAA;AACrC,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,kBAAkB,CAAA;AAC5D,YAAY,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAA;AAExD;;GAEG;AACH,eAAO,MAAM,YAAY,2PASV,MAAM,eACN,MAAM,0GAIpB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/index.js b/node_modules/@supabase/supabase-js/dist/module/index.js new file mode 100644 index 0000000..2979f0f --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/index.js @@ -0,0 +1,12 @@ +import SupabaseClient from './SupabaseClient'; +export * from '@supabase/gotrue-js'; +export { FunctionsHttpError, FunctionsFetchError, FunctionsRelayError, FunctionsError, } from '@supabase/functions-js'; +export * from '@supabase/realtime-js'; +export { default as SupabaseClient } from './SupabaseClient'; +/** + * Creates a new Supabase Client. + */ +export const createClient = (supabaseUrl, supabaseKey, options) => { + return new SupabaseClient(supabaseUrl, supabaseKey, options); +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/index.js.map b/node_modules/@supabase/supabase-js/dist/module/index.js.map new file mode 100644 index 0000000..567df73 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,kBAAkB,CAAA;AAG7C,cAAc,qBAAqB,CAAA;AAQnC,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,EACnB,cAAc,GACf,MAAM,wBAAwB,CAAA;AAC/B,cAAc,uBAAuB,CAAA;AACrC,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,kBAAkB,CAAA;AAG5D;;GAEG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAS1B,WAAmB,EACnB,WAAmB,EACnB,OAA2C,EACG,EAAE;IAChD,OAAO,IAAI,cAAc,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,CAAC,CAAA;AAC9D,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.d.ts b/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.d.ts new file mode 100644 index 0000000..24b89b8 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.d.ts @@ -0,0 +1,6 @@ +import { GoTrueClient } from '@supabase/gotrue-js'; +import { SupabaseAuthClientOptions } from './types'; +export declare class SupabaseAuthClient extends GoTrueClient { + constructor(options: SupabaseAuthClientOptions); +} +//# sourceMappingURL=SupabaseAuthClient.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.d.ts.map b/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.d.ts.map new file mode 100644 index 0000000..ca506a9 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"SupabaseAuthClient.d.ts","sourceRoot":"","sources":["../../../src/lib/SupabaseAuthClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAA;AAEnD,qBAAa,kBAAmB,SAAQ,YAAY;gBACtC,OAAO,EAAE,yBAAyB;CAG/C"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.js b/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.js new file mode 100644 index 0000000..82d0440 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.js @@ -0,0 +1,7 @@ +import { GoTrueClient } from '@supabase/gotrue-js'; +export class SupabaseAuthClient extends GoTrueClient { + constructor(options) { + super(options); + } +} +//# sourceMappingURL=SupabaseAuthClient.js.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.js.map b/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.js.map new file mode 100644 index 0000000..124926c --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/SupabaseAuthClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SupabaseAuthClient.js","sourceRoot":"","sources":["../../../src/lib/SupabaseAuthClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAGlD,MAAM,OAAO,kBAAmB,SAAQ,YAAY;IAClD,YAAY,OAAkC;QAC5C,KAAK,CAAC,OAAO,CAAC,CAAA;IAChB,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/constants.d.ts b/node_modules/@supabase/supabase-js/dist/module/lib/constants.d.ts new file mode 100644 index 0000000..12eb562 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/constants.d.ts @@ -0,0 +1,4 @@ +export declare const DEFAULT_HEADERS: { + 'X-Client-Info': string; +}; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/constants.d.ts.map b/node_modules/@supabase/supabase-js/dist/module/lib/constants.d.ts.map new file mode 100644 index 0000000..369da41 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,eAAe;;CAAgD,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/constants.js b/node_modules/@supabase/supabase-js/dist/module/lib/constants.js new file mode 100644 index 0000000..7fac949 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/constants.js @@ -0,0 +1,4 @@ +// constants.ts +import { version } from './version'; +export const DEFAULT_HEADERS = { 'X-Client-Info': `supabase-js/${version}` }; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/constants.js.map b/node_modules/@supabase/supabase-js/dist/module/lib/constants.js.map new file mode 100644 index 0000000..95f3e74 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAAA,eAAe;AACf,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACnC,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,eAAe,EAAE,eAAe,OAAO,EAAE,EAAE,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/fetch.d.ts b/node_modules/@supabase/supabase-js/dist/module/lib/fetch.d.ts new file mode 100644 index 0000000..a75140f --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/fetch.d.ts @@ -0,0 +1,9 @@ +declare type Fetch = typeof fetch; +export declare const resolveFetch: (customFetch?: Fetch) => Fetch; +export declare const resolveHeadersConstructor: () => { + new (init?: HeadersInit | undefined): Headers; + prototype: Headers; +}; +export declare const fetchWithAuth: (supabaseKey: string, getAccessToken: () => Promise, customFetch?: Fetch) => Fetch; +export {}; +//# sourceMappingURL=fetch.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/fetch.d.ts.map b/node_modules/@supabase/supabase-js/dist/module/lib/fetch.d.ts.map new file mode 100644 index 0000000..99da343 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/fetch.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AAEA,aAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,iBAAkB,KAAK,KAAG,KAUlD,CAAA;AAED,eAAO,MAAM,yBAAyB;;;CAMrC,CAAA;AAED,eAAO,MAAM,aAAa,gBACX,MAAM,kBACH,MAAM,QAAQ,MAAM,GAAG,IAAI,CAAC,gBAC9B,KAAK,KAClB,KAkBF,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/fetch.js b/node_modules/@supabase/supabase-js/dist/module/lib/fetch.js new file mode 100644 index 0000000..000a861 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/fetch.js @@ -0,0 +1,46 @@ +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 crossFetch, { Headers as CrossFetchHeaders } from 'cross-fetch'; +export const resolveFetch = (customFetch) => { + let _fetch; + if (customFetch) { + _fetch = customFetch; + } + else if (typeof fetch === 'undefined') { + _fetch = crossFetch; + } + else { + _fetch = fetch; + } + return (...args) => _fetch(...args); +}; +export const resolveHeadersConstructor = () => { + if (typeof Headers === 'undefined') { + return CrossFetchHeaders; + } + return Headers; +}; +export const fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => { + const fetch = resolveFetch(customFetch); + const HeadersConstructor = resolveHeadersConstructor(); + return (input, init) => __awaiter(void 0, void 0, void 0, function* () { + var _a; + const accessToken = (_a = (yield getAccessToken())) !== null && _a !== void 0 ? _a : supabaseKey; + let headers = new HeadersConstructor(init === null || init === void 0 ? void 0 : init.headers); + if (!headers.has('apikey')) { + headers.set('apikey', supabaseKey); + } + if (!headers.has('Authorization')) { + headers.set('Authorization', `Bearer ${accessToken}`); + } + return fetch(input, Object.assign(Object.assign({}, init), { headers })); + }); +}; +//# sourceMappingURL=fetch.js.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/fetch.js.map b/node_modules/@supabase/supabase-js/dist/module/lib/fetch.js.map new file mode 100644 index 0000000..2c5c6c6 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/fetch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,UAAU,EAAE,EAAE,OAAO,IAAI,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAItE,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAS,EAAE;IACzD,IAAI,MAAa,CAAA;IACjB,IAAI,WAAW,EAAE;QACf,MAAM,GAAG,WAAW,CAAA;KACrB;SAAM,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;QACvC,MAAM,GAAG,UAA8B,CAAA;KACxC;SAAM;QACL,MAAM,GAAG,KAAK,CAAA;KACf;IACD,OAAO,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,EAAE;IAC5C,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;QAClC,OAAO,iBAAiB,CAAA;KACzB;IAED,OAAO,OAAO,CAAA;AAChB,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,aAAa,GAAG,CAC3B,WAAmB,EACnB,cAA4C,EAC5C,WAAmB,EACZ,EAAE;IACT,MAAM,KAAK,GAAG,YAAY,CAAC,WAAW,CAAC,CAAA;IACvC,MAAM,kBAAkB,GAAG,yBAAyB,EAAE,CAAA;IAEtD,OAAO,CAAO,KAAK,EAAE,IAAI,EAAE,EAAE;;QAC3B,MAAM,WAAW,GAAG,MAAA,CAAC,MAAM,cAAc,EAAE,CAAC,mCAAI,WAAW,CAAA;QAC3D,IAAI,OAAO,GAAG,IAAI,kBAAkB,CAAC,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,CAAC,CAAA;QAEnD,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE;YAC1B,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAA;SACnC;QAED,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE;YACjC,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,WAAW,EAAE,CAAC,CAAA;SACtD;QAED,OAAO,KAAK,CAAC,KAAK,kCAAO,IAAI,KAAE,OAAO,IAAG,CAAA;IAC3C,CAAC,CAAA,CAAA;AACH,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/helpers.d.ts b/node_modules/@supabase/supabase-js/dist/module/lib/helpers.d.ts new file mode 100644 index 0000000..c54283a --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/helpers.d.ts @@ -0,0 +1,6 @@ +import { SupabaseClientOptions } from './types'; +export declare function uuid(): string; +export declare function stripTrailingSlash(url: string): string; +export declare const isBrowser: () => boolean; +export declare function applySettingDefaults(options: SupabaseClientOptions, defaults: SupabaseClientOptions): SupabaseClientOptions; +//# sourceMappingURL=helpers.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/helpers.d.ts.map b/node_modules/@supabase/supabase-js/dist/module/lib/helpers.d.ts.map new file mode 100644 index 0000000..2fbe2ba --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/helpers.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAA;AAE/C,wBAAgB,IAAI,WAMnB;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEtD;AAED,eAAO,MAAM,SAAS,eAAsC,CAAA;AAE5D,wBAAgB,oBAAoB,CAClC,QAAQ,GAAG,GAAG,EACd,UAAU,SAAS,MAAM,GAAG,MAAM,QAAQ,GAAG,QAAQ,SAAS,MAAM,QAAQ,GACxE,QAAQ,GACR,MAAM,GAAG,MAAM,QAAQ,EAE3B,OAAO,EAAE,qBAAqB,CAAC,UAAU,CAAC,EAC1C,QAAQ,EAAE,qBAAqB,CAAC,GAAG,CAAC,GACnC,qBAAqB,CAAC,UAAU,CAAC,CAgCnC"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/helpers.js b/node_modules/@supabase/supabase-js/dist/module/lib/helpers.js new file mode 100644 index 0000000..cf72d47 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/helpers.js @@ -0,0 +1,21 @@ +export function uuid() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +} +export function stripTrailingSlash(url) { + return url.replace(/\/$/, ''); +} +export const isBrowser = () => typeof window !== 'undefined'; +export function applySettingDefaults(options, defaults) { + const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions, } = options; + const { db: DEFAULT_DB_OPTIONS, auth: DEFAULT_AUTH_OPTIONS, realtime: DEFAULT_REALTIME_OPTIONS, global: DEFAULT_GLOBAL_OPTIONS, } = defaults; + return { + db: Object.assign(Object.assign({}, DEFAULT_DB_OPTIONS), dbOptions), + auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), authOptions), + realtime: Object.assign(Object.assign({}, DEFAULT_REALTIME_OPTIONS), realtimeOptions), + global: Object.assign(Object.assign({}, DEFAULT_GLOBAL_OPTIONS), globalOptions), + }; +} +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/helpers.js.map b/node_modules/@supabase/supabase-js/dist/module/lib/helpers.js.map new file mode 100644 index 0000000..cff0792 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AAGA,MAAM,UAAU,IAAI;IAClB,OAAO,sCAAsC,CAAC,OAAO,CAAC,OAAO,EAAE,UAAU,CAAC;QACxE,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EAC9B,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,GAAG,GAAG,CAAA;QACpC,OAAO,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAA;IACvB,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,GAAW;IAC5C,OAAO,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAA;AAC/B,CAAC;AAED,MAAM,CAAC,MAAM,SAAS,GAAG,GAAG,EAAE,CAAC,OAAO,MAAM,KAAK,WAAW,CAAA;AAE5D,MAAM,UAAU,oBAAoB,CAMlC,OAA0C,EAC1C,QAAoC;IAEpC,MAAM,EACJ,EAAE,EAAE,SAAS,EACb,IAAI,EAAE,WAAW,EACjB,QAAQ,EAAE,eAAe,EACzB,MAAM,EAAE,aAAa,GACtB,GAAG,OAAO,CAAA;IACX,MAAM,EACJ,EAAE,EAAE,kBAAkB,EACtB,IAAI,EAAE,oBAAoB,EAC1B,QAAQ,EAAE,wBAAwB,EAClC,MAAM,EAAE,sBAAsB,GAC/B,GAAG,QAAQ,CAAA;IAEZ,OAAO;QACL,EAAE,kCACG,kBAAkB,GAClB,SAAS,CACb;QACD,IAAI,kCACC,oBAAoB,GACpB,WAAW,CACf;QACD,QAAQ,kCACH,wBAAwB,GACxB,eAAe,CACnB;QACD,MAAM,kCACD,sBAAsB,GACtB,aAAa,CACjB;KACF,CAAA;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/types.d.ts b/node_modules/@supabase/supabase-js/dist/module/lib/types.d.ts new file mode 100644 index 0000000..af5481d --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/types.d.ts @@ -0,0 +1,83 @@ +import { GoTrueClient } from '@supabase/gotrue-js'; +import { RealtimeClientOptions } from '@supabase/realtime-js'; +declare type GoTrueClientOptions = ConstructorParameters[0]; +export interface SupabaseAuthClientOptions extends GoTrueClientOptions { +} +export declare type Fetch = typeof fetch; +export declare type SupabaseClientOptions = { + /** + * The Postgres schema which your tables belong to. Must be on the list of exposed schemas in Supabase. Defaults to `public`. + */ + db?: { + schema?: SchemaName; + }; + auth?: { + /** + * Automatically refreshes the token for logged-in users. Defaults to true. + */ + autoRefreshToken?: boolean; + /** + * Optional key name used for storing tokens in local storage. + */ + storageKey?: string; + /** + * Whether to persist a logged-in session to storage. Defaults to true. + */ + persistSession?: boolean; + /** + * Detect a session from the URL. Used for OAuth login callbacks. Defaults to true. + */ + detectSessionInUrl?: boolean; + /** + * A storage provider. Used to store the logged-in session. + */ + storage?: SupabaseAuthClientOptions['storage']; + /** + * OAuth flow to use - defaults to implicit flow. PKCE is recommended for mobile and server-side applications. + */ + flowType?: SupabaseAuthClientOptions['flowType']; + /** + * If debug messages for authentication client are emitted. Can be used to inspect the behavior of the library. + */ + debug?: boolean; + }; + /** + * Options passed to the realtime-js instance + */ + realtime?: RealtimeClientOptions; + global?: { + /** + * A custom `fetch` implementation. + */ + fetch?: Fetch; + /** + * Optional headers for initializing the client. + */ + headers?: Record; + }; +}; +export declare type GenericTable = { + Row: Record; + Insert: Record; + Update: Record; +}; +export declare type GenericUpdatableView = { + Row: Record; + Insert: Record; + Update: Record; +}; +export declare type GenericNonUpdatableView = { + Row: Record; +}; +export declare type GenericView = GenericUpdatableView | GenericNonUpdatableView; +export declare type GenericFunction = { + Args: Record; + Returns: unknown; +}; +export declare type GenericSchema = { + Tables: Record; + Views: Record; + Functions: Record; +}; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/types.d.ts.map b/node_modules/@supabase/supabase-js/dist/module/lib/types.d.ts.map new file mode 100644 index 0000000..3a25742 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAA;AAE7D,aAAK,mBAAmB,GAAG,qBAAqB,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,CAAA;AAExE,MAAM,WAAW,yBAA0B,SAAQ,mBAAmB;CAAG;AAEzE,oBAAY,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC,oBAAY,qBAAqB,CAAC,UAAU,IAAI;IAC9C;;OAEG;IACH,EAAE,CAAC,EAAE;QACH,MAAM,CAAC,EAAE,UAAU,CAAA;KACpB,CAAA;IAED,IAAI,CAAC,EAAE;QACL;;WAEG;QACH,gBAAgB,CAAC,EAAE,OAAO,CAAA;QAC1B;;WAEG;QACH,UAAU,CAAC,EAAE,MAAM,CAAA;QACnB;;WAEG;QACH,cAAc,CAAC,EAAE,OAAO,CAAA;QACxB;;WAEG;QACH,kBAAkB,CAAC,EAAE,OAAO,CAAA;QAC5B;;WAEG;QACH,OAAO,CAAC,EAAE,yBAAyB,CAAC,SAAS,CAAC,CAAA;QAC9C;;WAEG;QACH,QAAQ,CAAC,EAAE,yBAAyB,CAAC,UAAU,CAAC,CAAA;QAChD;;WAEG;QACH,KAAK,CAAC,EAAE,OAAO,CAAA;KAChB,CAAA;IACD;;OAEG;IACH,QAAQ,CAAC,EAAE,qBAAqB,CAAA;IAChC,MAAM,CAAC,EAAE;QACP;;WAEG;QACH,KAAK,CAAC,EAAE,KAAK,CAAA;QACb;;WAEG;QACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KACjC,CAAA;CACF,CAAA;AAED,oBAAY,YAAY,GAAG;IACzB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC5B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAChC,CAAA;AAED,oBAAY,oBAAoB,GAAG;IACjC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC5B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAChC,CAAA;AAED,oBAAY,uBAAuB,GAAG;IACpC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAC7B,CAAA;AAED,oBAAY,WAAW,GAAG,oBAAoB,GAAG,uBAAuB,CAAA;AAExE,oBAAY,eAAe,GAAG;IAC5B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC7B,OAAO,EAAE,OAAO,CAAA;CACjB,CAAA;AAED,oBAAY,aAAa,GAAG;IAC1B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAA;IACpC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAA;IAClC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAA;CAC3C,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/types.js b/node_modules/@supabase/supabase-js/dist/module/lib/types.js new file mode 100644 index 0000000..718fd38 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/types.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/types.js.map b/node_modules/@supabase/supabase-js/dist/module/lib/types.js.map new file mode 100644 index 0000000..5bb5e4d --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/version.d.ts b/node_modules/@supabase/supabase-js/dist/module/lib/version.d.ts new file mode 100644 index 0000000..f7ec3d5 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/version.d.ts @@ -0,0 +1,2 @@ +export declare const version = "2.31.0"; +//# sourceMappingURL=version.d.ts.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/version.d.ts.map b/node_modules/@supabase/supabase-js/dist/module/lib/version.d.ts.map new file mode 100644 index 0000000..7c1c990 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/version.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,oBAAoB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/version.js b/node_modules/@supabase/supabase-js/dist/module/lib/version.js new file mode 100644 index 0000000..e48dcad --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/version.js @@ -0,0 +1,2 @@ +export const version = '2.31.0'; +//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/module/lib/version.js.map b/node_modules/@supabase/supabase-js/dist/module/lib/version.js.map new file mode 100644 index 0000000..8a0d781 --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/module/lib/version.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,iBAAiB,CAAA"} \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/dist/umd/supabase.js b/node_modules/@supabase/supabase-js/dist/umd/supabase.js new file mode 100644 index 0000000..ed53d2f --- /dev/null +++ b/node_modules/@supabase/supabase-js/dist/umd/supabase.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.supabase=t():e.supabase=t()}(self,(()=>(()=>{var e,t,r={982:(e,t,r)=>{"use strict";r.r(t),r.d(t,{FunctionsClient:()=>a,FunctionsError:()=>s,FunctionsFetchError:()=>i,FunctionsHttpError:()=>o,FunctionsRelayError:()=>n});class s extends Error{constructor(e,t="FunctionsError",r){super(e),super.name=t,this.context=r}}class i extends s{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class n extends s{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class o extends s{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}class a{constructor(e,{headers:t={},customFetch:s}={}){this.url=e,this.headers=t,this.fetch=(e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>{return t=void 0,s=void 0,n=function*(){return yield(yield Promise.resolve().then(r.t.bind(r,98,23))).fetch(...e)},new((i=void 0)||(i=Promise))((function(e,r){function o(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i((function(e){e(r)}))).then(o,a)}c((n=n.apply(t,s||[])).next())}));var t,s,i,n}:fetch),(...e)=>t(...e)})(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r,s,a,c,h;return s=this,a=void 0,h=function*(){try{const{headers:s,method:a,body:c}=t;let h,l={};c&&(s&&!Object.prototype.hasOwnProperty.call(s,"Content-Type")||!s)&&("undefined"!=typeof Blob&&c instanceof Blob||c instanceof ArrayBuffer?(l["Content-Type"]="application/octet-stream",h=c):"string"==typeof c?(l["Content-Type"]="text/plain",h=c):"undefined"!=typeof FormData&&c instanceof FormData?h=c:(l["Content-Type"]="application/json",h=JSON.stringify(c)));const u=yield this.fetch(`${this.url}/${e}`,{method:a||"POST",headers:Object.assign(Object.assign(Object.assign({},l),this.headers),s),body:h}).catch((e=>{throw new i(e)})),d=u.headers.get("x-relay-error");if(d&&"true"===d)throw new n(u);if(!u.ok)throw new o(u);let f,p=(null!==(r=u.headers.get("Content-Type"))&&void 0!==r?r:"text/plain").split(";")[0].trim();return f="application/json"===p?yield u.json():"application/octet-stream"===p?yield u.blob():"multipart/form-data"===p?yield u.formData():yield u.text(),{data:f,error:null}}catch(e){return{data:null,error:e}}},new((c=void 0)||(c=Promise))((function(e,t){function r(e){try{n(h.next(e))}catch(e){t(e)}}function i(e){try{n(h.throw(e))}catch(e){t(e)}}function n(t){var s;t.done?e(t.value):(s=t.value,s instanceof c?s:new c((function(e){e(s)}))).then(r,i)}n((h=h.apply(s,a||[])).next())}))}}},765:(e,t,r)=>{"use strict";r.r(t),r.d(t,{AuthApiError:()=>P,AuthError:()=>O,AuthImplicitGrantRedirectError:()=>L,AuthInvalidCredentialsError:()=>I,AuthInvalidTokenResponseError:()=>R,AuthPKCEGrantCodeExchangeError:()=>U,AuthRetryableFetchError:()=>D,AuthSessionMissingError:()=>C,AuthUnknownError:()=>A,CustomAuthError:()=>$,GoTrueAdminApi:()=>V,GoTrueClient:()=>te,NavigatorLockAcquireTimeoutError:()=>se,isAuthApiError:()=>x,isAuthError:()=>j,isAuthRetryableFetchError:()=>N,lockInternals:()=>re,navigatorLock:()=>ie});const s=()=>"undefined"!=typeof document,i={tested:!1,writable:!1},n=()=>{if(!s())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(i.tested)return i.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),i.tested=!0,i.writable=!0}catch(e){i.tested=!0,i.writable=!1}return i.writable};function o(e){const t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach(((e,r)=>{t[r]=e}))}catch(e){}return r.searchParams.forEach(((e,r)=>{t[r]=e})),t}const a=e=>{let t;return t=e||("undefined"==typeof fetch?async(...e)=>await(await Promise.resolve().then(r.t.bind(r,98,23))).fetch(...e):fetch),(...e)=>t(...e)},c=e=>"object"==typeof e&&null!==e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json,h=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},l=async(e,t)=>{const r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return r}},u=async(e,t)=>{await e.removeItem(t)};class d{constructor(){this.promise=new d.promiseConstructor(((e,t)=>{this.resolve=e,this.reject=t}))}}function f(e){const t=e.split(".");if(3!==t.length)throw new Error("JWT is not valid: not a JWT structure");if(!/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");const r=t[1];return JSON.parse(function(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let r,s,i,n,o,a,c,h="",l=0;for(e=e.replace("-","+").replace("_","/");l>4,s=(15&o)<<4|a>>2,i=(3&a)<<6|c,h+=String.fromCharCode(r),64!=a&&0!=s&&(h+=String.fromCharCode(s)),64!=c&&0!=i&&(h+=String.fromCharCode(i));return h}(r))}async function p(e){return await new Promise((t=>{setTimeout((()=>t(null)),e)}))}function g(e){return("0"+e.toString(16)).substr(-2)}function y(){const e=new Uint32Array(56);if("undefined"==typeof crypto){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length;let r="";for(let s=0;s<56;s++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,g).join("")}async function m(e){if("undefined"==typeof crypto)return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;const t=await async function(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map((e=>String.fromCharCode(e))).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}d.promiseConstructor=Promise;const v=/__stack_guard__([a-zA-Z0-9_-]+)__/;let _,b=!1,w=!1;function S(e){var t,r;let s;_();try{throw new Error}catch(e){s=e}const i=null!==(r=null===(t=s.stack)||void 0===t?void 0:t.split("\n"))&&void 0!==r?r:[];for(let t=0;tawait t()};return Object.assign(s[r],{displayName:r}),await s[r]()}async function E(){return b||await _(),w}let k=!1;_=async()=>{b||(b=!0,await T("ENV_CHECK",(async()=>{await p(0);const e=S("ENV_CHECK");return w=e,e||k||(k=!0,console.warn("@supabase/gotrue-js: Stack guards not supported in this environment. Generally not an issue but may point to a very conservative transpilation environment (use ES2017 or above) that implements async/await with generators, or this is a JavaScript engine that does not support async/await stack traces. Safari is known to not support stack guards.")),e})))};class O extends Error{constructor(e,t){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t}}function j(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class P extends O{constructor(e,t){super(e,t),this.name="AuthApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}function x(e){return j(e)&&"AuthApiError"===e.name}class A extends O{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class $ extends O{constructor(e,t,r){super(e),this.name=t,this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class C extends ${constructor(){super("Auth session missing!","AuthSessionMissingError",400)}}class R extends ${constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500)}}class I extends ${constructor(e){super(e,"AuthInvalidCredentialsError",400)}}class L extends ${constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class U extends ${constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class D extends ${constructor(e,t){super(e,"AuthRetryableFetchError",t)}}function N(e){return j(e)&&"AuthRetryableFetchError"===e.name}const F=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),B=[502,503,504];async function M(e){if(!c(e))throw new D(F(e),0);if(B.includes(e.status))throw new D(F(e),e.status);let t;try{t=await e.json()}catch(e){throw new A(F(e),e)}throw new P(F(t),e.status||500)}async function J(e,t,r,s){var i;const n=Object.assign({},null==s?void 0:s.headers);(null==s?void 0:s.jwt)&&(n.Authorization=`Bearer ${s.jwt}`);const o=null!==(i=null==s?void 0:s.query)&&void 0!==i?i:{};(null==s?void 0:s.redirectTo)&&(o.redirect_to=s.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await async function(e,t,r,s,i,n){const o=((e,t,r,s)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),r))})(t,s,{},n);let a;try{a=await e(r,o)}catch(e){throw console.error(e),new D(F(e),0)}if(a.ok||await M(a),null==s?void 0:s.noResolveJson)return a;try{return await a.json()}catch(e){await M(e)}}(e,t,r+a,{headers:n,noResolveJson:null==s?void 0:s.noResolveJson},0,null==s?void 0:s.body);return(null==s?void 0:s.xform)?null==s?void 0:s.xform(c):{data:Object.assign({},c),error:null}}function q(e){var t;let r=null;var s;return function(e){return e.access_token&&e.refresh_token&&e.expires_in}(e)&&(r=Object.assign({},e),r.expires_at=(s=e.expires_in,Math.round(Date.now()/1e3)+s)),{data:{session:r,user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function H(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function z(e){return{data:e,error:null}}function G(e){const{action_link:t,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n}=e,o=function(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(s=Object.getOwnPropertySymbols(e);i0&&(d.forEach((e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);c[`${r}Page`]=t})),c.total=parseInt(u)),{data:Object.assign(Object.assign({},l),c),error:null}}catch(e){if(j(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){try{return await J(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:H})}catch(e){if(j(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){try{return await J(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:H})}catch(e){if(j(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){try{return await J(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:H})}catch(e){if(j(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){try{const{data:t,error:r}=await J(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(j(e))return{data:null,error:e};throw e}}async _deleteFactor(e){try{return{data:await J(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(j(e))return{data:null,error:e};throw e}}}const W="2.46.1",X={"X-Client-Info":`gotrue-js/${W}`},Y={getItem:e=>n()?globalThis.localStorage.getItem(e):null,setItem:(e,t)=>{n()&&globalThis.localStorage.setItem(e,t)},removeItem:e=>{n()&&globalThis.localStorage.removeItem(e)}};!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();const Q={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:X,flowType:"implicit",debug:!1},Z=3e4;async function ee(e,t,r){return await r()}class te{constructor(e){var t;this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.broadcastChannel=null,this.instanceID=te.nextInstanceID,te.nextInstanceID+=1,this.instanceID>0&&s()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");const r=Object.assign(Object.assign({},Q),e);if(this.logDebugMessages=r.debug,this.inMemorySession=null,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.persistSession=r.persistSession,this.storage=r.storage||Y,this.admin=new V({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=a(r.fetch),this.lock=r.lock||ee,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession&&this.storage===Y&&!n()&&console.warn("No storage option exists to persist the session, which may result in unexpected behavior when using auth.\n If you want to set persistSession to true, please provide a storage option or you may set persistSession to false to disable this warning."),s()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null===(t=this.broadcastChannel)||void 0===t||t.addEventListener("message",(async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}))}this.initialize()}_debug(...e){return this.logDebugMessages&&console.log(`GoTrueClient@${this.instanceID} (${W}) ${(new Date).toISOString()}`,...e),this}initialize(){return this.initializePromise?this.initializePromise:this._initialize()}async _initialize(){if(this.initializePromise)throw new Error("Double call of #_initialize()");return this.initializePromise=this._acquireLock(-1,(async()=>await T("_initialize",(async()=>{try{const e=!!s()&&await this._isPKCEFlow();if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){const{data:t,error:r}=await this._getSessionFromURL(e);if(r)return this._debug("#_initialize()","error detecting session from URL",r),await this._removeSession(),{error:r};const{session:s,redirectType:i}=t;return this._debug("#_initialize()","detected session in URL",s,"redirect type",i),await this._saveSession(s),setTimeout((async()=>{"recovery"===i?await this._notifyAllSubscribers("PASSWORD_RECOVERY",s):await this._notifyAllSubscribers("SIGNED_IN",s)}),0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return j(e)?{error:e}:{error:new A("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}})))),await this.initializePromise}async signUp(e){var t,r,s;try{let i;if(await this._removeSession(),"email"in e){const{email:r,password:s,options:n}=e;let o=null,a=null;if("pkce"===this.flowType){const e=y();await h(this.storage,`${this.storageKey}-code-verifier`,e),o=await m(e),a=e===o?"plain":"s256"}i=await J(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==n?void 0:n.emailRedirectTo,body:{email:r,password:s,data:null!==(t=null==n?void 0:n.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:o,code_challenge_method:a},xform:q})}else{if(!("phone"in e))throw new I("You must provide either an email or phone number and a password");{const{phone:t,password:n,options:o}=e;i=await J(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:n,data:null!==(r=null==o?void 0:o.data)&&void 0!==r?r:{},channel:null!==(s=null==o?void 0:o.channel)&&void 0!==s?s:"sms",gotrue_meta_security:{captcha_token:null==o?void 0:o.captchaToken}},xform:q})}}const{data:n,error:o}=i;if(o||!n)return{data:{user:null,session:null},error:o};const a=n.session,c=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:c,session:a},error:null}}catch(e){if(j(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithPassword(e){try{let t;if(await this._removeSession(),"email"in e){const{email:r,password:s,options:i}=e;t=await J(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:q})}else{if(!("phone"in e))throw new I("You must provide either an email or phone number and a password");{const{phone:r,password:s,options:i}=e;t=await J(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:q})}}const{data:r,error:s}=t;return s?{data:{user:null,session:null},error:s}:r&&r.session&&r.user?(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:{user:r.user,session:r.session},error:s}):{data:{user:null,session:null},error:new R}}catch(e){if(j(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOAuth(e){var t,r,s,i;return await this._removeSession(),await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(s=e.options)||void 0===s?void 0:s.queryParams,skipBrowserRedirect:null===(i=e.options)||void 0===i?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){const t=await l(this.storage,`${this.storageKey}-code-verifier`),{data:r,error:s}=await J(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:t},xform:q});return await u(this.storage,`${this.storageKey}-code-verifier`),s?{data:{user:null,session:null},error:s}:r&&r.session&&r.user?(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:r,error:s}):{data:{user:null,session:null},error:new R}}async signInWithIdToken(e){await this._removeSession();try{const{options:t,provider:r,token:s,access_token:i,nonce:n}=e,o=await J(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:n,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:q}),{data:a,error:c}=o;return c?{data:{user:null,session:null},error:c}:a&&a.session&&a.user?(a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:a,error:c}):{data:{user:null,session:null},error:new R}}catch(e){if(j(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOtp(e){var t,r,s,i,n;try{if(await this._removeSession(),"email"in e){const{email:s,options:i}=e;let n=null,o=null;if("pkce"===this.flowType){const e=y();await h(this.storage,`${this.storageKey}-code-verifier`,e),n=await m(e),o=e===n?"plain":"s256"}const{error:a}=await J(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:s,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},create_user:null===(r=null==i?void 0:i.shouldCreateUser)||void 0===r||r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:n,code_challenge_method:o},redirectTo:null==i?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:a}}if("phone"in e){const{phone:t,options:r}=e,{data:o,error:a}=await J(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(s=null==r?void 0:r.data)&&void 0!==s?s:{},create_user:null===(i=null==r?void 0:r.shouldCreateUser)||void 0===i||i,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!==(n=null==r?void 0:r.channel)&&void 0!==n?n:"sms"}});return{data:{user:null,session:null,messageId:null==o?void 0:o.message_id},error:a}}throw new I("You must provide either an email or phone number.")}catch(e){if(j(e))return{data:{user:null,session:null},error:e};throw e}}async verifyOtp(e){var t,r;try{let s,i;"email_change"!==e.type&&"phone_change"!==e.type&&await this._removeSession(),"options"in e&&(s=null===(t=e.options)||void 0===t?void 0:t.redirectTo,i=null===(r=e.options)||void 0===r?void 0:r.captchaToken);const{data:n,error:o}=await J(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:q});if(o)throw o;if(!n)throw new Error("An error occurred on token verification.");const a=n.session,c=n.user;return(null==a?void 0:a.access_token)&&(await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:c,session:a},error:null}}catch(e){if(j(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithSSO(e){var t,r,s;try{return await this._removeSession(),await J(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:null!==(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==r?r:void 0}),(null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0}),headers:this.headers,xform:z})}catch(e){if(j(e))return{data:null,error:e};throw e}}async reauthenticate(){try{return await this._useSession((async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new C;const{error:s}=await J(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:s}}))}catch(e){if(j(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{"email_change"!=e.type&&"phone_change"!=e.type&&await this._removeSession();const t=`${this.url}/resend`;if("email"in e){const{email:r,type:s,options:i}=e,{error:n}=await J(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},redirectTo:null==i?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:n}}if("phone"in e){const{phone:r,type:s,options:i}=e,{data:n,error:o}=await J(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:null==n?void 0:n.message_id},error:o}}throw new I("You must provide either an email or phone number and a type")}catch(e){if(j(e))return{data:{user:null,session:null},error:e};throw e}}async getSession(){return this._useSession((async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{return await E()?S("_acquireLock")?(this._debug("#_acquireLock","recursive call"),await t()):await this.lock(`lock:${this.storageKey}`,e,(async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{return await T("_acquireLock",(async()=>await t()))}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey)}})):(this._debug("#_acquireLock","Stack guards not supported, so exclusive locking is not performed as it can lead to deadlocks if the lock is attempted to be recursively acquired (as the recursion cannot be detected)."),await t())}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{if(S("_useSession")){this._debug("#_useSession","recursive call");const t=await this.__loadSession();return await e(t)}return await this._acquireLock(-1,(async()=>await T("_useSession",(async()=>{const t=await this.__loadSession();return await e(t)}))))}finally{this._debug("#_useSession","end")}}async __loadSession(){if(this._debug("#__loadSession()","begin"),this.logDebugMessages&&!S("_useSession")&&await E())throw new Error("Please use #_useSession()");S("_initialize")&&this._debug("#__loadSession","#_initialize recursion detected",(new Error).stack),await this.initializePromise;try{let e=null;if(this.persistSession){const t=await l(this.storage,this.storageKey);this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession()))}else e=this.inMemorySession,this._debug("#getSession()","session from memory",e);if(!e)return{data:{session:null},error:null};const t=!!e.expires_at&&e.expires_at<=Date.now()/1e3;if(this._debug("#__loadSession()",`session has${t?"":" not"} expired`,"expires_at",e.expires_at),!t)return{data:{session:e},error:null};const{session:r,error:s}=await this._callRefreshToken(e.refresh_token);return s?{data:{session:null},error:s}:{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){try{return e?await J(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:H}):await this._useSession((async e=>{var t,r;const{data:s,error:i}=e;if(i)throw i;return await J(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(r=null===(t=s.session)||void 0===t?void 0:t.access_token)&&void 0!==r?r:void 0,xform:H})}))}catch(e){if(j(e))return{data:{user:null},error:e};throw e}}async updateUser(e,t={}){try{return await this._useSession((async r=>{const{data:s,error:i}=r;if(i)throw i;if(!s.session)throw new C;const n=s.session,{data:o,error:a}=await J(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:e,jwt:n.access_token,xform:H});if(a)throw a;return n.user=o.user,await this._saveSession(n),await this._notifyAllSubscribers("USER_UPDATED",n),{data:{user:n.user},error:null}}))}catch(e){if(j(e))return{data:{user:null},error:e};throw e}}_decodeJWT(e){return f(e)}async setSession(e){try{if(!e.access_token||!e.refresh_token)throw new C;const t=Date.now()/1e3;let r=t,s=!0,i=null;const n=f(e.access_token);if(n.exp&&(r=n.exp,s=r<=t),s){const{session:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return{data:{user:null,session:null},error:r};if(!t)return{data:{user:null,session:null},error:null};i=t}else{const{data:s,error:n}=await this.getUser(e.access_token);if(n)throw n;i={access_token:e.access_token,refresh_token:e.refresh_token,user:s.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(e){if(j(e))return{data:{session:null,user:null},error:e};throw e}}async refreshSession(e){try{return await this._useSession((async t=>{var r;if(!e){const{data:s,error:i}=t;if(i)throw i;e=null!==(r=s.session)&&void 0!==r?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new C;const{session:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:s?{data:{user:s.user,session:s},error:null}:{data:{user:null,session:null},error:null}}))}catch(e){if(j(e))return{data:{user:null,session:null},error:e};throw e}}async _getSessionFromURL(e){try{if(!s())throw new L("No browser detected.");if("implicit"===this.flowType&&!this._isImplicitGrantFlow())throw new L("Not a valid implicit grant flow url.");if("pkce"==this.flowType&&!e)throw new U("Not a valid PKCE flow url.");const t=o(window.location.href);if(e){if(!t.code)throw new U("No code detected.");const{data:e,error:r}=await this.exchangeCodeForSession(t.code);if(r)throw r;const s=new URL(window.location.href);return s.searchParams.delete("code"),window.history.replaceState(window.history.state,"",s.toString()),{data:{session:e.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new L(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});const{provider_token:r,provider_refresh_token:i,access_token:n,refresh_token:a,expires_in:c,token_type:h}=t;if(!(n&&c&&a&&h))throw new L("No session defined in URL");const l=Math.round(Date.now()/1e3),u=parseInt(c),d=l+u,{data:f,error:p}=await this.getUser(n);if(p)throw p;const g={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:d,refresh_token:a,token_type:h,user:f.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:g,redirectType:t.type},error:null}}catch(e){if(j(e))return{data:{session:null,redirectType:null},error:e};throw e}}_isImplicitGrantFlow(){const e=o(window.location.href);return!(!s()||!e.access_token&&!e.error_description)}async _isPKCEFlow(){const e=o(window.location.href),t=await l(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut({scope:e}={scope:"global"}){return await this._useSession((async t=>{var r;const{data:s,error:i}=t;if(i)return{error:i};const n=null===(r=s.session)||void 0===r?void 0:r.access_token;if(n){const{error:t}=await this.admin.signOut(n,e);if(t&&(!x(t)||404!==t.status&&401!==t.status))return{error:t}}return"others"!==e&&(await this._removeSession(),await u(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}}))}onAuthStateChange(e){const t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),this._emitInitialSession(t),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession((async t=>{var r,s;try{const{data:{session:s},error:i}=t;if(i)throw i;await(null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(t){await(null===(s=this.stateChangeEmitters.get(e))||void 0===s?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}}))}async resetPasswordForEmail(e,t={}){let r=null,s=null;if("pkce"===this.flowType){const e=y();await h(this.storage,`${this.storageKey}-code-verifier`,e),r=await m(e),s=e===r?"plain":"s256"}try{return await J(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(j(e))return{data:null,error:e};throw e}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const i=Date.now();return await(r=async r=>(await p(200*r),this._debug(t,"refreshing attempt",r),await J(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:q})),s=(e,t,r)=>r&&r.error&&N(r.error)&&Date.now()+200*(e+1)-i{(async()=>{for(let i=0;i<1/0;i++)try{const t=await r(i);if(!s(i,0,t))return void e(t)}catch(e){if(!s(i))return void t(e)}})()})))}catch(e){if(this._debug(t,"error",e),j(e))return{data:{session:null,user:null},error:e};throw e}finally{this._debug(t,"end")}var r,s}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=await this._getUrlForProvider(e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),s()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;const t="#_recoverAndRefresh()";this._debug(t,"begin");try{const r=await l(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r))return this._debug(t,"session is not valid"),void(null!==r&&await this._removeSession());const s=Math.round(Date.now()/1e3),i=(null!==(e=r.expires_at)&&void 0!==e?e:1/0){try{await r.callback(e,t)}catch(e){s.push(e)}}));if(await Promise.all(i),s.length>0){for(let e=0;ethis._autoRefreshTokenTick()),Z);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e),setTimeout((async()=>{await this.initializePromise,await this._autoRefreshTokenTick()}),0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{const e=Date.now();try{return await this._useSession((async t=>{const{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const s=Math.floor((1e3*r.expires_at-e)/Z);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(r.refresh_token)}))}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!s()||!(null===window||void 0===window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null===window||void 0===window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){this._debug(`#_onVisibilityChanged(${e})`,"visibilityState",document.visibilityState),"visible"===document.visibilityState?setTimeout((async()=>{e||(await this.initializePromise,await this._recoverAndRefresh(),this._debug("#_onVisibilityChanged()","finished waiting for initialize, _recoverAndRefresh")),this.autoRefreshToken&&this._startAutoRefresh()}),0):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t){const r=[`provider=${encodeURIComponent(e)}`];if((null==t?void 0:t.redirectTo)&&r.push(`redirect_to=${encodeURIComponent(t.redirectTo)}`),(null==t?void 0:t.scopes)&&r.push(`scopes=${encodeURIComponent(t.scopes)}`),"pkce"===this.flowType){const e=y();await h(this.storage,`${this.storageKey}-code-verifier`,e);const t=await m(e),s=e===t?"plain":"s256";this._debug("PKCE","code verifier",`${e.substring(0,5)}...`,"code challenge",t,"method",s);const i=new URLSearchParams({code_challenge:`${encodeURIComponent(t)}`,code_challenge_method:`${encodeURIComponent(s)}`});r.push(i.toString())}if(null==t?void 0:t.queryParams){const e=new URLSearchParams(t.queryParams);r.push(e.toString())}return`${this.url}/authorize?${r.join("&")}`}async _unenroll(e){try{return await this._useSession((async t=>{var r;const{data:s,error:i}=t;return i?{data:null,error:i}:await J(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token})}))}catch(e){if(j(e))return{data:null,error:e};throw e}}async _enroll(e){try{return await this._useSession((async t=>{var r,s;const{data:i,error:n}=t;if(n)return{data:null,error:n};const{data:o,error:a}=await J(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:null===(r=null==i?void 0:i.session)||void 0===r?void 0:r.access_token});return a?{data:null,error:a}:((null===(s=null==o?void 0:o.totp)||void 0===s?void 0:s.qr_code)&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),{data:o,error:null})}))}catch(e){if(j(e))return{data:null,error:e};throw e}}async _verify(e){try{return await this._useSession((async t=>{var r;const{data:s,error:i}=t;if(i)return{data:null,error:i};const{data:n,error:o}=await J(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});return o?{data:null,error:o}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+n.expires_in},n)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",n),{data:n,error:o})}))}catch(e){if(j(e))return{data:null,error:e};throw e}}async _challenge(e){try{return await this._useSession((async t=>{var r;const{data:s,error:i}=t;return i?{data:null,error:i}:await J(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token})}))}catch(e){if(j(e))return{data:null,error:e};throw e}}async _challengeAndVerify(e){const{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){const{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};const r=(null==e?void 0:e.factors)||[],s=r.filter((e=>"totp"===e.factor_type&&"verified"===e.status));return{data:{all:r,totp:s},error:null}}async _getAuthenticatorAssuranceLevel(){return await this._useSession((async e=>{var t,r;const{data:{session:s},error:i}=e;if(i)return{data:null,error:i};if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const n=this._decodeJWT(s.access_token);let o=null;n.aal&&(o=n.aal);let a=o;return(null!==(r=null===(t=s.user.factors)||void 0===t?void 0:t.filter((e=>"verified"===e.status)))&&void 0!==r?r:[]).length>0&&(a="aal2"),{data:{currentLevel:o,nextLevel:a,currentAuthenticationMethods:n.amr||[]},error:null}}))}}te.nextInstanceID=0;const re={debug:!(!globalThis||!globalThis.localStorage||"true"!==globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};class se extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}async function ie(e,t,r){re.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);let s=null,i=null;const n=new Promise(((e,t)=>{s=e,i=t})),o=(async()=>{await n,re.debug&&console.log("@supabase/gotrue-js: navigatorLock: operation start");try{return await r()}finally{re.debug&&console.log("@supabase/gotrue-js: navigatorLock: operation end")}})(),a=new globalThis.AbortController;return t>0&&setTimeout((()=>{s=null,a.abort(),i&&(re.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e),i&&i(new se(`Acquiring an exclusive Navigator LockManager lock "${e}" timed out after ${t}ms`)),s=null,i=null)}),t),await globalThis.navigator.locks.request(e,{mode:"exclusive",ifAvailable:0===t,signal:a.signal},(async t=>{if(t){re.debug&&console.log("@supabase/gotrue-js: navigatorLock acquired",e);try{s&&(s(),s=null,i=null,await o)}catch(e){}finally{re.debug&&console.log("@supabase/gotrue-js: navigatorLock released",e)}}else re.debug&&console.log("@supabase/gotrue-js: navigatorLock not immediately available",e),new Error(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`).isAcquireTimeout=!0,i&&i(new se(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`)),s=null,i=null})),await o}},189:(e,t,r)=>{"use strict";r.r(t),r.d(t,{PostgrestBuilder:()=>n,PostgrestClient:()=>l,PostgrestFilterBuilder:()=>a,PostgrestQueryBuilder:()=>c,PostgrestTransformBuilder:()=>o});var s=r(98),i=r.n(s);class n{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:"undefined"==typeof fetch?this.fetch=i():this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),"GET"!==this.method&&"HEAD"!==this.method&&(this.headers["Content-Type"]="application/json");let r=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then((async e=>{var t,r,s;let i=null,n=null,o=null,a=e.status,c=e.statusText;if(e.ok){if("HEAD"!==this.method){const t=await e.text();""===t||(n="text/csv"===this.headers.Accept||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?t:JSON.parse(t))}const s=null===(t=this.headers.Prefer)||void 0===t?void 0:t.match(/count=(exact|planned|estimated)/),h=null===(r=e.headers.get("content-range"))||void 0===r?void 0:r.split("/");s&&h&&h.length>1&&(o=parseInt(h[1])),this.isMaybeSingle&&"GET"===this.method&&Array.isArray(n)&&(n.length>1?(i={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,o=null,a=406,c="Not Acceptable"):n=1===n.length?n[0]:null)}else{const t=await e.text();try{i=JSON.parse(t),Array.isArray(i)&&404===e.status&&(n=[],i=null,a=200,c="OK")}catch(r){404===e.status&&""===t?(a=204,c="No Content"):i={message:t}}if(i&&this.isMaybeSingle&&(null===(s=null==i?void 0:i.details)||void 0===s?void 0:s.includes("Results contain 0 rows"))&&(i=null,a=200,c="OK"),i&&this.shouldThrowOnError)throw i}return{error:i,data:n,count:o,status:a,statusText:c}}));return this.shouldThrowOnError||(r=r.catch((e=>{var t,r,s;return{error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:`${null!==(r=null==e?void 0:e.stack)&&void 0!==r?r:""}`,hint:"",code:`${null!==(s=null==e?void 0:e.code)&&void 0!==s?s:""}`},data:null,count:null,status:0,statusText:""}}))),r.then(e,t)}}class o extends n{select(e){let t=!1;const r=(null!=e?e:"*").split("").map((e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e))).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s}={}){const i=s?`${s}.order`:"order",n=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${n?`${n},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t}={}){const r=void 0===t?"limit":`${t}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:r}={}){const s=void 0===r?"offset":`${r}.offset`,i=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this.url.searchParams.set(i,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return"GET"===this.method?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:n="text"}={}){const o=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),a=this.headers.Accept;return this.headers.Accept=`application/vnd.pgrst.plan+${n}; for="${a}"; options=${o};`,this}rollback(){var e;return(null!==(e=this.headers.Prefer)&&void 0!==e?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}}class a extends o{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){const r=t.map((e=>"string"==typeof e&&new RegExp("[,()]").test(e)?`"${e}"`:`${e}`)).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let i="";"plain"===s?i="pl":"phrase"===s?i="ph":"websearch"===s&&(i="w");const n=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${n}.${t}`),this}match(e){return Object.entries(e).forEach((([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)})),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t}={}){const r=t?`${t}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}}class c{constructor(e,{headers:t={},schema:r,fetch:s}){this.url=e,this.headers=t,this.schema=r,this.fetch=s}select(e,{head:t=!1,count:r}={}){const s=t?"HEAD":"GET";let i=!1;const n=(null!=e?e:"*").split("").map((e=>/\s/.test(e)&&!i?"":('"'===e&&(i=!i),e))).join("");return this.url.searchParams.set("select",n),r&&(this.headers.Prefer=`count=${r}`),new a({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){const s=[];if(this.headers.Prefer&&s.push(this.headers.Prefer),t&&s.push(`count=${t}`),r||s.push("missing=default"),this.headers.Prefer=s.join(","),Array.isArray(e)){const t=e.reduce(((e,t)=>e.concat(Object.keys(t))),[]);if(t.length>0){const e=[...new Set(t)].map((e=>`"${e}"`));this.url.searchParams.set("columns",e.join(","))}}return new a({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){const n=[`resolution=${r?"ignore":"merge"}-duplicates`];if(void 0!==t&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&n.push(this.headers.Prefer),s&&n.push(`count=${s}`),i||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){const t=e.reduce(((e,t)=>e.concat(Object.keys(t))),[]);if(t.length>0){const e=[...new Set(t)].map((e=>`"${e}"`));this.url.searchParams.set("columns",e.join(","))}}return new a({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){const r=[];return this.headers.Prefer&&r.push(this.headers.Prefer),t&&r.push(`count=${t}`),this.headers.Prefer=r.join(","),new a({method:"PATCH",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){const t=[];return e&&t.push(`count=${e}`),this.headers.Prefer&&t.unshift(this.headers.Prefer),this.headers.Prefer=t.join(","),new a({method:"DELETE",url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}}const h={"X-Client-Info":"postgrest-js/1.7.0"};class l{constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=Object.assign(Object.assign({},h),t),this.schema=r,this.fetch=s}from(e){const t=new URL(`${this.url}/${e}`);return new c(t,{headers:Object.assign({},this.headers),schema:this.schema,fetch:this.fetch})}rpc(e,t={},{head:r=!1,count:s}={}){let i;const n=new URL(`${this.url}/rpc/${e}`);let o;r?(i="HEAD",Object.entries(t).forEach((([e,t])=>{n.searchParams.append(e,`${t}`)}))):(i="POST",o=t);const c=Object.assign({},this.headers);return s&&(c.Prefer=`count=${s}`),new a({method:i,url:n,headers:c,schema:this.schema,body:o,fetch:this.fetch,allowEmpty:!1})}}},73:(e,t,r)=>{"use strict";r.r(t),r.d(t,{REALTIME_LISTEN_TYPES:()=>O,REALTIME_POSTGRES_CHANGES_LISTEN_EVENT:()=>k,REALTIME_PRESENCE_LISTEN_EVENTS:()=>l,REALTIME_SUBSCRIBE_STATES:()=>j,RealtimeChannel:()=>x,RealtimeClient:()=>C,RealtimePresence:()=>g});var s=r(840);const i={"X-Client-Info":"realtime-js/2.7.3"};var n,o,a,c,h,l,u;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(n||(n={})),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(o||(o={})),function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"}(a||(a={})),function(e){e.websocket="websocket"}(c||(c={})),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(h||(h={}));class d{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout((()=>{this.tries=this.tries+1,this.callback()}),this.timerCalc(this.tries+1))}}class f{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t("string"==typeof e?JSON.parse(e):{})}_binaryDecode(e){const t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){const s=t.getUint8(1),i=t.getUint8(2);let n=this.HEADER_LENGTH+2;const o=r.decode(e.slice(n,n+s));n+=s;const a=r.decode(e.slice(n,n+i));return n+=i,{ref:null,topic:o,event:a,payload:JSON.parse(r.decode(e.slice(n,e.byteLength)))}}}class p{constructor(e,t,r={},s=1e4){this.channel=e,this.event=t,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null,this.rateLimited=!1}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,"rate limited"===this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()})&&(this.rateLimited=!0))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t(null===(r=this.receivedResp)||void 0===r?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){this.timeoutTimer||(this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref),this.channel._on(this.refEvent,{},(e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)})),this.timeoutTimer=setTimeout((()=>{this.trigger("timeout",{})}),this.timeout))}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter((t=>t.status===e)).forEach((e=>e.callback(t)))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(l||(l={}));class g{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},(e=>{const{onJoin:t,onLeave:r,onSync:s}=this.caller;this.joinRef=this.channel._joinRef(),this.state=g.syncState(this.state,e,t,r),this.pendingDiffs.forEach((e=>{this.state=g.syncDiff(this.state,e,t,r)})),this.pendingDiffs=[],s()})),this.channel._on(r.diff,{},(e=>{const{onJoin:t,onLeave:r,onSync:s}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=g.syncDiff(this.state,e,t,r),s())})),this.onJoin(((e,t,r)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:r})})),this.onLeave(((e,t,r)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:r})})),this.onSync((()=>{this.channel._trigger("presence",{event:"sync"})}))}static syncState(e,t,r,s){const i=this.cloneDeep(e),n=this.transformState(t),o={},a={};return this.map(i,((e,t)=>{n[e]||(a[e]=t)})),this.map(n,((e,t)=>{const r=i[e];if(r){const s=t.map((e=>e.presence_ref)),i=r.map((e=>e.presence_ref)),n=t.filter((e=>i.indexOf(e.presence_ref)<0)),c=r.filter((e=>s.indexOf(e.presence_ref)<0));n.length>0&&(o[e]=n),c.length>0&&(a[e]=c)}else o[e]=t})),this.syncDiff(i,{joins:o,leaves:a},r,s)}static syncDiff(e,t,r,s){const{joins:i,leaves:n}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(i,((t,s)=>{var i;const n=null!==(i=e[t])&&void 0!==i?i:[];if(e[t]=this.cloneDeep(s),n.length>0){const r=e[t].map((e=>e.presence_ref)),s=n.filter((e=>r.indexOf(e.presence_ref)<0));e[t].unshift(...s)}r(t,n,s)})),this.map(n,((t,r)=>{let i=e[t];if(!i)return;const n=r.map((e=>e.presence_ref));i=i.filter((e=>n.indexOf(e.presence_ref)<0)),e[t]=i,s(t,i,r),0===i.length&&delete e[t]})),e}static map(e,t){return Object.getOwnPropertyNames(e).map((r=>t(r,e[r])))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce(((t,r)=>{const s=e[r];return t[r]="metas"in s?s.metas.map((e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))):s,t}),{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(u||(u={}));const y=(e,t,r={})=>{var s;const i=null!==(s=r.skipTypes)&&void 0!==s?s:[];return Object.keys(t).reduce(((r,s)=>(r[s]=m(s,e,t,i),r)),{})},m=(e,t,r,s)=>{const i=t.find((t=>t.name===e)),n=null==i?void 0:i.type,o=r[e];return n&&!s.includes(n)?v(n,o):_(o)},v=(e,t)=>{if("_"===e.charAt(0)){const r=e.slice(1,e.length);return T(t,r)}switch(e){case u.bool:return b(t);case u.float4:case u.float8:case u.int2:case u.int4:case u.int8:case u.numeric:case u.oid:return w(t);case u.json:case u.jsonb:return S(t);case u.timestamp:return E(t);case u.abstime:case u.date:case u.daterange:case u.int4range:case u.int8range:case u.money:case u.reltime:case u.text:case u.time:case u.timestamptz:case u.timetz:case u.tsrange:case u.tstzrange:default:return _(t)}},_=e=>e,b=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},w=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},S=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return console.log(`JSON parse error: ${t}`),e}return e},T=(e,t)=>{if("string"!=typeof e)return e;const r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s;const i=e.slice(1,r);try{s=JSON.parse("["+i+"]")}catch(e){s=i?i.split(","):[]}return s.map((e=>v(t,e)))}return e},E=e=>"string"==typeof e?e.replace(" ","T"):e;var k,O,j,P=function(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))};!function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(k||(k={})),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes"}(O||(O={})),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(j||(j={}));class x{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=o.closed,this.joinedOnce=!1,this.pushBuffer=[],this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""}},t.config),this.timeout=this.socket.timeout,this.joinPush=new p(this,a.join,this.params,this.timeout),this.rejoinTimer=new d((()=>this._rejoinUntilConnected()),this.socket.reconnectAfterMs),this.joinPush.receive("ok",(()=>{this.state=o.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach((e=>e.send())),this.pushBuffer=[]})),this._onClose((()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=o.closed,this.socket._remove(this)})),this._onError((e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=o.errored,this.rejoinTimer.scheduleTimeout())})),this.joinPush.receive("timeout",(()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=o.errored,this.rejoinTimer.scheduleTimeout())})),this._on(a.reply,{},((e,t)=>{this._trigger(this._replyEventName(t),e)})),this.presence=new g(this)}subscribe(e,t=this.timeout){var r,s;if(this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:i,presence:n}}=this.params;this._onError((t=>e&&e("CHANNEL_ERROR",t))),this._onClose((()=>e&&e("CLOSED")));const o={},a={broadcast:i,presence:n,postgres_changes:null!==(s=null===(r=this.bindings.postgres_changes)||void 0===r?void 0:r.map((e=>e.filter)))&&void 0!==s?s:[]};this.socket.accessToken&&(o.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:a},o)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",(({postgres_changes:t})=>{var r;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),void 0!==t){const s=this.bindings.postgres_changes,i=null!==(r=null==s?void 0:s.length)&&void 0!==r?r:0,n=[];for(let r=0;r{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(t).join(", ")||"error")))})).receive("timeout",(()=>{e&&e("TIMED_OUT")}))}return this}presenceState(){return this.presence.state}track(e,t={}){return P(this,void 0,void 0,(function*(){return yield this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}))}untrack(e={}){return P(this,void 0,void 0,(function*(){return yield this.send({type:"presence",event:"untrack"},e)}))}on(e,t,r){return this._on(e,t,r)}send(e,t={}){return new Promise((r=>{var s,i,n;const o=this._push(e.type,e,t.timeout||this.timeout);o.rateLimited&&r("rate limited"),"broadcast"!==e.type||(null===(n=null===(i=null===(s=this.params)||void 0===s?void 0:s.config)||void 0===i?void 0:i.broadcast)||void 0===n?void 0:n.ack)||r("ok"),o.receive("ok",(()=>r("ok"))),o.receive("timeout",(()=>r("timed out")))}))}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=o.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(a.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise((r=>{const s=new p(this,a.leave,{},e);s.receive("ok",(()=>{t(),r("ok")})).receive("timeout",(()=>{t(),r("timed out")})).receive("error",(()=>{r("error")})),s.send(),this._canPush()||s.trigger("ok",{})}))}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new p(this,e,t,r);return this._canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,i;const n=e.toLocaleLowerCase(),{close:o,error:c,leave:h,join:l}=a;if(r&&[o,c,h,l].indexOf(n)>=0&&r!==this._joinRef())return;let u=this._onMessage(n,t,r);if(t&&!u)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(n)?null===(s=this.bindings.postgres_changes)||void 0===s||s.filter((e=>{var t,r,s;return"*"===(null===(t=e.filter)||void 0===t?void 0:t.event)||(null===(s=null===(r=e.filter)||void 0===r?void 0:r.event)||void 0===s?void 0:s.toLocaleLowerCase())===n})).map((e=>e.callback(u,r))):null===(i=this.bindings[n])||void 0===i||i.filter((e=>{var r,s,i,o,a,c;if(["broadcast","presence","postgres_changes"].includes(n)){if("id"in e){const n=e.id,o=null===(r=e.filter)||void 0===r?void 0:r.event;return n&&(null===(s=t.ids)||void 0===s?void 0:s.includes(n))&&("*"===o||(null==o?void 0:o.toLocaleLowerCase())===(null===(i=t.data)||void 0===i?void 0:i.type.toLocaleLowerCase()))}{const r=null===(a=null===(o=null==e?void 0:e.filter)||void 0===o?void 0:o.event)||void 0===a?void 0:a.toLocaleLowerCase();return"*"===r||r===(null===(c=null==t?void 0:t.event)||void 0===c?void 0:c.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===n})).map((e=>{if("object"==typeof u&&"ids"in u){const e=u.data,{schema:t,table:r,commit_timestamp:s,type:i,errors:n}=e,o={schema:t,table:r,commit_timestamp:s,eventType:i,new:{},old:{},errors:n};u=Object.assign(Object.assign({},o),this._getPayloadRecords(e))}e.callback(u,r)}))}_isClosed(){return this.state===o.closed}_isJoined(){return this.state===o.joined}_isJoining(){return this.state===o.joining}_isLeaving(){return this.state===o.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const s=e.toLocaleLowerCase(),i={type:s,filter:t,callback:r};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter((e=>{var s;return!((null===(s=e.type)||void 0===s?void 0:s.toLocaleLowerCase())===r&&x.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(a.close,{},e)}_onError(e){this._on(a.error,{},(t=>e(t)))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=o.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=y(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=y(e.columns,e.old_record)),t}}var A=function(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))};const $=()=>{};class C{constructor(e,t){var r;this.accessToken=null,this.channels=[],this.endPoint="",this.headers=i,this.params={},this.timeout=1e4,this.transport=s.w3cwebsocket,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=$,this.conn=null,this.sendBuffer=[],this.serializer=new f,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.eventsPerSecondLimitMs=100,this.inThrottle=!1,this.endPoint=`${e}/${c.websocket}`,(null==t?void 0:t.params)&&(this.params=t.params),(null==t?void 0:t.headers)&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),(null==t?void 0:t.timeout)&&(this.timeout=t.timeout),(null==t?void 0:t.logger)&&(this.logger=t.logger),(null==t?void 0:t.transport)&&(this.transport=t.transport),(null==t?void 0:t.heartbeatIntervalMs)&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);const n=null===(r=null==t?void 0:t.params)||void 0===r?void 0:r.eventsPerSecond;n&&(this.eventsPerSecondLimitMs=Math.floor(1e3/n)),this.reconnectAfterMs=(null==t?void 0:t.reconnectAfterMs)?t.reconnectAfterMs:e=>[1e3,2e3,5e3,1e4][e-1]||1e4,this.encode=(null==t?void 0:t.encode)?t.encode:(e,t)=>t(JSON.stringify(e)),this.decode=(null==t?void 0:t.decode)?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new d((()=>A(this,void 0,void 0,(function*(){this.disconnect(),this.connect()}))),this.reconnectAfterMs)}connect(){this.conn||(this.conn=new this.transport(this._endPointURL(),[],null,this.headers),this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e)))}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,null!=t?t:""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}removeChannel(e){return A(this,void 0,void 0,(function*(){const t=yield e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}))}removeAllChannels(){return A(this,void 0,void 0,(function*(){const e=yield Promise.all(this.channels.map((e=>e.unsubscribe())));return this.disconnect(),e}))}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case n.connecting:return h.Connecting;case n.open:return h.Open;case n.closing:return h.Closing;default:return h.Closed}}isConnected(){return this.connectionState()===h.Open}channel(e,t={config:{}}){this.isConnected()||this.connect();const r=new x(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){const{topic:t,event:r,payload:s,ref:i}=e;let n=()=>{this.encode(e,(e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)}))};if(this.log("push",`${t} ${r} (${i})`,s),this.isConnected())if(["broadcast","presence","postgres_changes"].includes(r)){if(this._throttle(n)())return"rate limited"}else n();else this.sendBuffer.push(n)}setAuth(e){this.accessToken=e,this.channels.forEach((t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(a.access_token,{access_token:e})}))}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find((t=>t.topic===e&&(t._isJoined()||t._isJoining())));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter((t=>t._joinRef()!==e._joinRef()))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:"1.0.0"}))}_onConnMessage(e){this.decode(e.data,(e=>{let{topic:t,event:r,payload:s,ref:i}=e;(i&&i===this.pendingHeartbeatRef||r===(null==s?void 0:s.type))&&(this.pendingHeartbeatRef=null),this.log("receive",`${s.status||""} ${t} ${r} ${i&&"("+i+")"||""}`,s),this.channels.filter((e=>e._isMember(t))).forEach((e=>e._trigger(r,s,i))),this.stateChangeCallbacks.message.forEach((t=>t(e)))}))}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval((()=>this._sendHeartbeat()),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach((e=>e()))}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach((t=>t(e)))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach((t=>t(e)))}_triggerChanError(){this.channels.forEach((e=>e._trigger(a.error)))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const r=e.match(/\?/)?"&":"?";return`${e}${r}${new URLSearchParams(t)}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach((e=>e())),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef)return this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),void(null===(e=this.conn)||void 0===e||e.close(1e3,"hearbeat timeout"));this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}_throttle(e,t=this.eventsPerSecondLimitMs){return()=>!!this.inThrottle||(e(),t>0&&(this.inThrottle=!0,setTimeout((()=>{this.inThrottle=!1}),t)),!1)}}},752:(e,t,r)=>{"use strict";r.r(t),r.d(t,{StorageApiError:()=>n,StorageClient:()=>E,StorageError:()=>s,StorageUnknownError:()=>o,isStorageError:()=>i});class s extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function i(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}class n extends s{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class o extends s{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}var a=function(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))};const c=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>a(void 0,void 0,void 0,(function*(){return yield(yield Promise.resolve().then(r.t.bind(r,98,23))).fetch(...e)})):fetch),(...e)=>t(...e)};var h=function(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))};const l=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),u=(e,t)=>h(void 0,void 0,void 0,(function*(){const s=yield a(void 0,void 0,void 0,(function*(){return"undefined"==typeof Response?(yield Promise.resolve().then(r.t.bind(r,98,23))).Response:Response}));e instanceof s?e.json().then((r=>{t(new n(l(r),e.status||500))})).catch((e=>{t(new o(l(e),e))})):t(new o(l(e),e))})),d=(e,t,r,s)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),r))};function f(e,t,r,s,i,n){return h(this,void 0,void 0,(function*(){return new Promise(((o,a)=>{e(r,d(t,s,i,n)).then((e=>{if(!e.ok)throw e;return(null==s?void 0:s.noResolveJson)?e:e.json()})).then((e=>o(e))).catch((e=>u(e,a)))}))}))}function p(e,t,r,s){return h(this,void 0,void 0,(function*(){return f(e,"GET",t,r,s)}))}function g(e,t,r,s,i){return h(this,void 0,void 0,(function*(){return f(e,"POST",t,s,i,r)}))}function y(e,t,r,s,i){return h(this,void 0,void 0,(function*(){return f(e,"DELETE",t,s,i,r)}))}var m=function(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))};const v={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},_={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class b{constructor(e,t={},r,s){this.url=e,this.headers=t,this.bucketId=r,this.fetch=c(s)}uploadOrUpdate(e,t,r,s){return m(this,void 0,void 0,(function*(){try{let i;const n=Object.assign(Object.assign({},_),s),o=Object.assign(Object.assign({},this.headers),"POST"===e&&{"x-upsert":String(n.upsert)});"undefined"!=typeof Blob&&r instanceof Blob?(i=new FormData,i.append("cacheControl",n.cacheControl),i.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(i=r,i.append("cacheControl",n.cacheControl)):(i=r,o["cache-control"]=`max-age=${n.cacheControl}`,o["content-type"]=n.contentType);const a=this._removeEmptyFolders(t),c=this._getFinalPath(a),h=yield this.fetch(`${this.url}/object/${c}`,Object.assign({method:e,body:i,headers:o},(null==n?void 0:n.duplex)?{duplex:n.duplex}:{}));return h.ok?{data:{path:a},error:null}:{data:null,error:yield h.json()}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}upload(e,t,r){return m(this,void 0,void 0,(function*(){return this.uploadOrUpdate("POST",e,t,r)}))}uploadToSignedUrl(e,t,r,s){return m(this,void 0,void 0,(function*(){const n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let e;const t=Object.assign({upsert:_.upsert},s),i=Object.assign(Object.assign({},this.headers),{"x-upsert":String(t.upsert)});"undefined"!=typeof Blob&&r instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),e.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(e=r,e.append("cacheControl",t.cacheControl)):(e=r,i["cache-control"]=`max-age=${t.cacheControl}`,i["content-type"]=t.contentType);const o=yield this.fetch(a.toString(),{method:"PUT",body:e,headers:i});return o.ok?{data:{path:n},error:null}:{data:null,error:yield o.json()}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}createSignedUploadUrl(e){return m(this,void 0,void 0,(function*(){try{let t=this._getFinalPath(e);const r=yield g(this.fetch,`${this.url}/object/upload/sign/${t}`,{},{headers:this.headers}),i=new URL(this.url+r.url),n=i.searchParams.get("token");if(!n)throw new s("No token returned by API");return{data:{signedUrl:i.toString(),path:e,token:n},error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}update(e,t,r){return m(this,void 0,void 0,(function*(){return this.uploadOrUpdate("PUT",e,t,r)}))}move(e,t){return m(this,void 0,void 0,(function*(){try{return{data:yield g(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}copy(e,t){return m(this,void 0,void 0,(function*(){try{return{data:{path:(yield g(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers})).Key},error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}createSignedUrl(e,t,r){return m(this,void 0,void 0,(function*(){try{let s=this._getFinalPath(e),i=yield g(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},(null==r?void 0:r.transform)?{transform:r.transform}:{}),{headers:this.headers});const n=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${n}`)},{data:i,error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}createSignedUrls(e,t,r){return m(this,void 0,void 0,(function*(){try{const s=yield g(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return{data:s.map((e=>Object.assign(Object.assign({},e),{signedUrl:e.signedURL?encodeURI(`${this.url}${e.signedURL}${i}`):null}))),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}download(e,t){return m(this,void 0,void 0,(function*(){const r=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",s=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),n=s?`?${s}`:"";try{const t=this._getFinalPath(e),s=yield p(this.fetch,`${this.url}/${r}/${t}${n}`,{headers:this.headers,noResolveJson:!0});return{data:yield s.blob(),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}getPublicUrl(e,t){const r=this._getFinalPath(e),s=[],i=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==i&&s.push(i);const n=void 0!==(null==t?void 0:t.transform)?"render/image":"object",o=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==o&&s.push(o);let a=s.join("&");return""!==a&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${n}/public/${r}${a}`)}}}remove(e){return m(this,void 0,void 0,(function*(){try{return{data:yield y(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}list(e,t,r){return m(this,void 0,void 0,(function*(){try{const s=Object.assign(Object.assign(Object.assign({},v),t),{prefix:e||""});return{data:yield g(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},r),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const w={"X-Client-Info":"storage-js/2.5.1"};var S=function(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))};class T{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},w),t),this.fetch=c(r)}listBuckets(){return S(this,void 0,void 0,(function*(){try{return{data:yield p(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}getBucket(e){return S(this,void 0,void 0,(function*(){try{return{data:yield p(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}createBucket(e,t={public:!1}){return S(this,void 0,void 0,(function*(){try{return{data:yield g(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}updateBucket(e,t){return S(this,void 0,void 0,(function*(){try{const r=yield function(e,t,r,s,i){return h(this,void 0,void 0,(function*(){return f(e,"PUT",t,s,undefined,r)}))}(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers});return{data:r,error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}emptyBucket(e){return S(this,void 0,void 0,(function*(){try{return{data:yield g(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}deleteBucket(e){return S(this,void 0,void 0,(function*(){try{return{data:yield y(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}}class E extends T{constructor(e,t={},r){super(e,t,r)}from(e){return new b(this.url,this.headers,e,this.fetch)}}},98:function(e,t){var r="undefined"!=typeof self?self:this,s=function(){function e(){this.fetch=!1,this.DOMException=r.DOMException}return e.prototype=r,new e}();!function(e){!function(t){var r="URLSearchParams"in e,s="Symbol"in e&&"iterator"in Symbol,i="FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),n="FormData"in e,o="ArrayBuffer"in e;if(o)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(e){return e&&a.indexOf(Object.prototype.toString.call(e))>-1};function h(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function l(e){return"string"!=typeof e&&(e=String(e)),e}function u(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return s&&(t[Symbol.iterator]=function(){return t}),t}function d(e){this.map={},e instanceof d?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function f(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function p(e){return new Promise((function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}}))}function g(e){var t=new FileReader,r=p(t);return t.readAsArrayBuffer(e),r}function y(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function m(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:i&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:n&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:r&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():o&&i&&(t=e)&&DataView.prototype.isPrototypeOf(t)?(this._bodyArrayBuffer=y(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):o&&(ArrayBuffer.prototype.isPrototypeOf(e)||c(e))?this._bodyArrayBuffer=y(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i&&(this.blob=function(){var e=f(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?f(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(g)}),this.text=function(){var e,t,r,s=f(this);if(s)return s;if(this._bodyBlob)return e=this._bodyBlob,r=p(t=new FileReader),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),s=0;s-1?s:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function b(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var r=e.split("="),s=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(s),decodeURIComponent(i))}})),t}function w(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new d(t.headers),this.url=t.url||"",this._initBody(e)}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})},m.call(_.prototype),m.call(w.prototype),w.prototype.clone=function(){return new w(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new d(this.headers),url:this.url})},w.error=function(){var e=new w(null,{status:0,statusText:""});return e.type="error",e};var S=[301,302,303,307,308];w.redirect=function(e,t){if(-1===S.indexOf(t))throw new RangeError("Invalid status code");return new w(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function T(e,r){return new Promise((function(s,n){var o=new _(e,r);if(o.signal&&o.signal.aborted)return n(new t.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function c(){a.abort()}a.onload=function(){var e,t,r={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new d,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var r=e.split(":"),s=r.shift().trim();if(s){var i=r.join(":").trim();t.append(s,i)}})),t)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var i="response"in a?a.response:a.responseText;s(new w(i,r))},a.onerror=function(){n(new TypeError("Network request failed"))},a.ontimeout=function(){n(new TypeError("Network request failed"))},a.onabort=function(){n(new t.DOMException("Aborted","AbortError"))},a.open(o.method,o.url,!0),"include"===o.credentials?a.withCredentials=!0:"omit"===o.credentials&&(a.withCredentials=!1),"responseType"in a&&i&&(a.responseType="blob"),o.headers.forEach((function(e,t){a.setRequestHeader(t,e)})),o.signal&&(o.signal.addEventListener("abort",c),a.onreadystatechange=function(){4===a.readyState&&o.signal.removeEventListener("abort",c)}),a.send(void 0===o._bodyInit?null:o._bodyInit)}))}T.polyfill=!0,e.fetch||(e.fetch=T,e.Headers=d,e.Request=_,e.Response=w),t.Headers=d,t.Request=_,t.Response=w,t.fetch=T,Object.defineProperty(t,"__esModule",{value:!0})}({})}(s),s.fetch.ponyfill=!0,delete s.fetch.polyfill;var i=s;(t=i.fetch).default=i.fetch,t.fetch=i.fetch,t.Headers=i.Headers,t.Request=i.Request,t.Response=i.Response,e.exports=t},284:e=>{var t=function(){if("object"==typeof self&&self)return self;if("object"==typeof window&&window)return window;throw new Error("Unable to resolve global `this`")};e.exports=function(){if(this)return this;if("object"==typeof globalThis&&globalThis)return globalThis;try{Object.defineProperty(Object.prototype,"__global__",{get:function(){return this},configurable:!0})}catch(e){return t()}try{return __global__||t()}finally{delete Object.prototype.__global__}}()},296:function(e,t,r){"use strict";var s=this&&this.__awaiter||function(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0});const i=r(982),n=r(189),o=r(73),a=r(752),c=r(678),h=r(716),l=r(610),u=r(283),d={headers:c.DEFAULT_HEADERS},f={schema:"public"},p={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},g={};t.default=class{constructor(e,t,r){var s,i,o,a,c,u,y,m;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");const v=(0,l.stripTrailingSlash)(e);this.realtimeUrl=`${v}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${v}/auth/v1`,this.storageUrl=`${v}/storage/v1`,this.functionsUrl=`${v}/functions/v1`;const _=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,b={db:f,realtime:g,auth:Object.assign(Object.assign({},p),{storageKey:_}),global:d},w=(0,l.applySettingDefaults)(null!=r?r:{},b);this.storageKey=null!==(i=null===(s=w.auth)||void 0===s?void 0:s.storageKey)&&void 0!==i?i:"",this.headers=null!==(a=null===(o=w.global)||void 0===o?void 0:o.headers)&&void 0!==a?a:{},this.auth=this._initSupabaseAuthClient(null!==(c=w.auth)&&void 0!==c?c:{},this.headers,null===(u=w.global)||void 0===u?void 0:u.fetch),this.fetch=(0,h.fetchWithAuth)(t,this._getAccessToken.bind(this),null===(y=w.global)||void 0===y?void 0:y.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},w.realtime)),this.rest=new n.PostgrestClient(`${v}/rest/v1`,{headers:this.headers,schema:null===(m=w.db)||void 0===m?void 0:m.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new i.FunctionsClient(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new a.StorageClient(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}rpc(e,t={},r){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return s(this,void 0,void 0,(function*(){const{data:r}=yield this.auth.getSession();return null!==(t=null===(e=r.session)||void 0===e?void 0:e.access_token)&&void 0!==t?t:null}))}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,storageKey:i,flowType:n,debug:o},a,c){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new u.SupabaseAuthClient({url:this.authUrl,headers:Object.assign(Object.assign({},h),a),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,flowType:n,debug:o,fetch:c})}_initRealtimeClient(e){return new o.RealtimeClient(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange(((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)}))}_handleTokenChanged(e,t,r){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===r?"SIGNED_OUT"===e&&(this.realtime.setAuth(this.supabaseKey),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.realtime.setAuth(null!=r?r:null),this.changedAccessToken=r)}}},341:function(e,t,r){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,i)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||s(t,e,r)},n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.createClient=t.SupabaseClient=t.FunctionsError=t.FunctionsRelayError=t.FunctionsFetchError=t.FunctionsHttpError=void 0;const o=n(r(296));i(r(765),t);var a=r(982);Object.defineProperty(t,"FunctionsHttpError",{enumerable:!0,get:function(){return a.FunctionsHttpError}}),Object.defineProperty(t,"FunctionsFetchError",{enumerable:!0,get:function(){return a.FunctionsFetchError}}),Object.defineProperty(t,"FunctionsRelayError",{enumerable:!0,get:function(){return a.FunctionsRelayError}}),Object.defineProperty(t,"FunctionsError",{enumerable:!0,get:function(){return a.FunctionsError}}),i(r(73),t);var c=r(296);Object.defineProperty(t,"SupabaseClient",{enumerable:!0,get:function(){return n(c).default}}),t.createClient=(e,t,r)=>new o.default(e,t,r)},283:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SupabaseAuthClient=void 0;const s=r(765);class i extends s.GoTrueClient{constructor(e){super(e)}}t.SupabaseAuthClient=i},678:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_HEADERS=void 0;const s=r(506);t.DEFAULT_HEADERS={"X-Client-Info":`supabase-js/${s.version}`}},716:function(e,t,r){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,i)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&s(t,e,r);return i(t,e),t},o=this&&this.__awaiter||function(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.fetchWithAuth=t.resolveHeadersConstructor=t.resolveFetch=void 0;const a=n(r(98));t.resolveFetch=e=>{let t;return t=e||("undefined"==typeof fetch?a.default:fetch),(...e)=>t(...e)},t.resolveHeadersConstructor=()=>"undefined"==typeof Headers?a.Headers:Headers,t.fetchWithAuth=(e,r,s)=>{const i=(0,t.resolveFetch)(s),n=(0,t.resolveHeadersConstructor)();return(t,s)=>o(void 0,void 0,void 0,(function*(){var o;const a=null!==(o=yield r())&&void 0!==o?o:e;let c=new n(null==s?void 0:s.headers);return c.has("apikey")||c.set("apikey",e),c.has("Authorization")||c.set("Authorization",`Bearer ${a}`),i(t,Object.assign(Object.assign({},s),{headers:c}))}))}},610:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.applySettingDefaults=t.isBrowser=t.stripTrailingSlash=t.uuid=void 0,t.uuid=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},t.stripTrailingSlash=function(e){return e.replace(/\/$/,"")},t.isBrowser=()=>"undefined"!=typeof window,t.applySettingDefaults=function(e,t){const{db:r,auth:s,realtime:i,global:n}=e,{db:o,auth:a,realtime:c,global:h}=t;return{db:Object.assign(Object.assign({},o),r),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},h),n)}}},506:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.version=void 0,t.version="2.31.0"},840:(e,t,r)=>{var s;if("object"==typeof globalThis)s=globalThis;else try{s=r(284)}catch(e){}finally{if(s||"undefined"==typeof window||(s=window),!s)throw new Error("Could not determine global this")}var i=s.WebSocket||s.MozWebSocket,n=r(387);function o(e,t){return t?new i(e,t):new i(e)}i&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach((function(e){Object.defineProperty(o,e,{get:function(){return i[e]}})})),e.exports={w3cwebsocket:i?o:null,version:n}},387:(e,t,r)=>{e.exports=r(794).version},794:e=>{"use strict";e.exports={version:"1.0.34"}}},s={};function i(e){var t=s[e];if(void 0!==t)return t.exports;var n=s[e]={exports:{}};return r[e].call(n.exports,n,n.exports,i),n.exports}return i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,i.t=function(r,s){if(1&s&&(r=this(r)),8&s)return r;if("object"==typeof r&&r){if(4&s&&r.__esModule)return r;if(16&s&&"function"==typeof r.then)return r}var n=Object.create(null);i.r(n);var o={};e=e||[null,t({}),t([]),t(t)];for(var a=2&s&&r;"object"==typeof a&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach((e=>o[e]=()=>r[e]));return o.default=()=>r,i.d(n,o),n},i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i(341)})())); \ No newline at end of file diff --git a/node_modules/@supabase/supabase-js/package.json b/node_modules/@supabase/supabase-js/package.json new file mode 100644 index 0000000..1a0663c --- /dev/null +++ b/node_modules/@supabase/supabase-js/package.json @@ -0,0 +1,71 @@ +{ + "name": "@supabase/supabase-js", + "version": "2.31.0", + "description": "Isomorphic Javascript client for Supabase", + "keywords": [ + "javascript", + "typescript", + "supabase" + ], + "homepage": "https://github.com/supabase/supabase-js", + "bugs": "https://github.com/supabase/supabase-js/issues", + "license": "MIT", + "author": "Supabase", + "files": [ + "dist", + "src" + ], + "main": "dist/main/index.js", + "module": "dist/module/index.js", + "types": "dist/module/index.d.ts", + "sideEffects": false, + "repository": "supabase/supabase-js", + "scripts": { + "clean": "rimraf dist docs/v2", + "format": "prettier --write \"{src,test}/**/*.ts\"", + "build": "run-s clean format build:*", + "build:main": "tsc -p tsconfig.json", + "build:module": "tsc -p tsconfig.module.json", + "build:umd": "webpack", + "types-generate": "dts-gen -m '@supabase/supabase-js' -s", + "test": "jest --runInBand", + "test:coverage": "jest --runInBand --coverage", + "test:db": "cd infra/db && docker-compose down && docker-compose up -d && sleep 5", + "test:watch": "jest --watch --verbose false --silent false", + "test:clean": "cd infra/db && docker-compose down", + "docs": "typedoc --entryPoints src/index.ts --out docs/v2 --includes src/**/*.ts", + "docs:json": "typedoc --entryPoints src/index.ts --includes src/**/*.ts --json docs/v2/spec.json --excludeExternals" + }, + "dependencies": { + "@supabase/functions-js": "^2.1.0", + "@supabase/gotrue-js": "^2.46.1", + "@supabase/postgrest-js": "^1.7.0", + "@supabase/realtime-js": "^2.7.3", + "@supabase/storage-js": "^2.5.1", + "cross-fetch": "^3.1.5" + }, + "devDependencies": { + "@types/jest": "^29.2.5", + "husky": "^4.3.0", + "jest": "^29.3.1", + "npm-run-all": "^4.1.5", + "prettier": "^2.5.1", + "pretty-quick": "^3.1.3", + "rimraf": "^3.0.2", + "semantic-release-plugin-update-version-in-files": "^1.1.0", + "ts-jest": "^29.0.5", + "ts-loader": "^8.0.11", + "ts-node": "^10.9.1", + "typedoc": "^0.22.16", + "typescript": "^4.5.5", + "webpack": "^5.69.1", + "webpack-cli": "^4.9.2" + }, + "husky": { + "hooks": { + "pre-commit": "pretty-quick --staged" + } + }, + "jsdelivr": "dist/umd/supabase.js", + "unpkg": "dist/umd/supabase.js" +} diff --git a/node_modules/@supabase/supabase-js/src/SupabaseClient.ts b/node_modules/@supabase/supabase-js/src/SupabaseClient.ts new file mode 100644 index 0000000..fbb3bb8 --- /dev/null +++ b/node_modules/@supabase/supabase-js/src/SupabaseClient.ts @@ -0,0 +1,312 @@ +import { FunctionsClient } from '@supabase/functions-js' +import { AuthChangeEvent } from '@supabase/gotrue-js' +import { + PostgrestClient, + PostgrestFilterBuilder, + PostgrestQueryBuilder, +} from '@supabase/postgrest-js' +import { + RealtimeChannel, + RealtimeChannelOptions, + RealtimeClient, + RealtimeClientOptions, +} from '@supabase/realtime-js' +import { StorageClient as SupabaseStorageClient } from '@supabase/storage-js' +import { DEFAULT_HEADERS } from './lib/constants' +import { fetchWithAuth } from './lib/fetch' +import { stripTrailingSlash, applySettingDefaults } from './lib/helpers' +import { SupabaseAuthClient } from './lib/SupabaseAuthClient' +import { Fetch, GenericSchema, SupabaseClientOptions, SupabaseAuthClientOptions } from './lib/types' + +const DEFAULT_GLOBAL_OPTIONS = { + headers: DEFAULT_HEADERS, +} + +const DEFAULT_DB_OPTIONS = { + schema: 'public', +} + +const DEFAULT_AUTH_OPTIONS: SupabaseAuthClientOptions = { + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + flowType: 'implicit', +} + +const DEFAULT_REALTIME_OPTIONS: RealtimeClientOptions = {} + +/** + * Supabase Client. + * + * An isomorphic Javascript client for interacting with Postgres. + */ +export default class SupabaseClient< + Database = any, + SchemaName extends string & keyof Database = 'public' extends keyof Database + ? 'public' + : string & keyof Database, + Schema extends GenericSchema = Database[SchemaName] extends GenericSchema + ? Database[SchemaName] + : any +> { + /** + * Supabase Auth allows you to create and manage user sessions for access to data that is secured by access policies. + */ + auth: SupabaseAuthClient + realtime: RealtimeClient + + protected realtimeUrl: string + protected authUrl: string + protected storageUrl: string + protected functionsUrl: string + protected rest: PostgrestClient + protected storageKey: string + protected fetch?: Fetch + protected changedAccessToken?: string + + protected headers: { + [key: string]: string + } + + /** + * Create a new client for use in the browser. + * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. + * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. + * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. + * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. + * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. + * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. + * @param options.realtime Options passed along to realtime-js constructor. + * @param options.global.fetch A custom fetch implementation. + * @param options.global.headers Any additional headers to send with each network request. + */ + constructor( + protected supabaseUrl: string, + protected supabaseKey: string, + options?: SupabaseClientOptions + ) { + if (!supabaseUrl) throw new Error('supabaseUrl is required.') + if (!supabaseKey) throw new Error('supabaseKey is required.') + + const _supabaseUrl = stripTrailingSlash(supabaseUrl) + + this.realtimeUrl = `${_supabaseUrl}/realtime/v1`.replace(/^http/i, 'ws') + this.authUrl = `${_supabaseUrl}/auth/v1` + this.storageUrl = `${_supabaseUrl}/storage/v1` + this.functionsUrl = `${_supabaseUrl}/functions/v1` + + // default storage key uses the supabase project ref as a namespace + const defaultStorageKey = `sb-${new URL(this.authUrl).hostname.split('.')[0]}-auth-token` + const DEFAULTS = { + db: DEFAULT_DB_OPTIONS, + realtime: DEFAULT_REALTIME_OPTIONS, + auth: { ...DEFAULT_AUTH_OPTIONS, storageKey: defaultStorageKey }, + global: DEFAULT_GLOBAL_OPTIONS, + } + + const settings = applySettingDefaults(options ?? {}, DEFAULTS) + + this.storageKey = settings.auth?.storageKey ?? '' + this.headers = settings.global?.headers ?? {} + + this.auth = this._initSupabaseAuthClient( + settings.auth ?? {}, + this.headers, + settings.global?.fetch + ) + this.fetch = fetchWithAuth(supabaseKey, this._getAccessToken.bind(this), settings.global?.fetch) + + this.realtime = this._initRealtimeClient({ headers: this.headers, ...settings.realtime }) + this.rest = new PostgrestClient(`${_supabaseUrl}/rest/v1`, { + headers: this.headers, + schema: settings.db?.schema, + fetch: this.fetch, + }) + + this._listenForAuthEvents() + } + + /** + * Supabase Functions allows you to deploy and invoke edge functions. + */ + get functions() { + return new FunctionsClient(this.functionsUrl, { + headers: this.headers, + customFetch: this.fetch, + }) + } + + /** + * Supabase Storage allows you to manage user-generated content, such as photos or videos. + */ + get storage() { + return new SupabaseStorageClient(this.storageUrl, this.headers, this.fetch) + } + + from< + TableName extends string & keyof Schema['Tables'], + Table extends Schema['Tables'][TableName] + >(relation: TableName): PostgrestQueryBuilder + from( + relation: ViewName + ): PostgrestQueryBuilder + from(relation: string): PostgrestQueryBuilder + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation: string): PostgrestQueryBuilder { + return this.rest.from(relation) + } + + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc< + FunctionName extends string & keyof Schema['Functions'], + Function_ extends Schema['Functions'][FunctionName] + >( + fn: FunctionName, + args: Function_['Args'] = {}, + options?: { + head?: boolean + count?: 'exact' | 'planned' | 'estimated' + } + ): PostgrestFilterBuilder< + Schema, + Function_['Returns'] extends any[] + ? Function_['Returns'][number] extends Record + ? Function_['Returns'][number] + : never + : never, + Function_['Returns'] + > { + return this.rest.rpc(fn, args, options) + } + + /** + * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. + * + * @param {string} name - The name of the Realtime channel. + * @param {Object} opts - The options to pass to the Realtime channel. + * + */ + channel(name: string, opts: RealtimeChannelOptions = { config: {} }): RealtimeChannel { + return this.realtime.channel(name, opts) + } + + /** + * Returns all Realtime channels. + */ + getChannels(): RealtimeChannel[] { + return this.realtime.getChannels() + } + + /** + * Unsubscribes and removes Realtime channel from Realtime client. + * + * @param {RealtimeChannel} channel - The name of the Realtime channel. + * + */ + removeChannel(channel: RealtimeChannel): Promise<'ok' | 'timed out' | 'error'> { + return this.realtime.removeChannel(channel) + } + + /** + * Unsubscribes and removes all Realtime channels from Realtime client. + */ + removeAllChannels(): Promise<('ok' | 'timed out' | 'error')[]> { + return this.realtime.removeAllChannels() + } + + private async _getAccessToken() { + const { data } = await this.auth.getSession() + + return data.session?.access_token ?? null + } + + private _initSupabaseAuthClient( + { + autoRefreshToken, + persistSession, + detectSessionInUrl, + storage, + storageKey, + flowType, + debug, + }: SupabaseAuthClientOptions, + headers?: Record, + fetch?: Fetch + ) { + const authHeaders = { + Authorization: `Bearer ${this.supabaseKey}`, + apikey: `${this.supabaseKey}`, + } + return new SupabaseAuthClient({ + url: this.authUrl, + headers: { ...authHeaders, ...headers }, + storageKey: storageKey, + autoRefreshToken, + persistSession, + detectSessionInUrl, + storage, + flowType, + debug, + fetch, + }) + } + + private _initRealtimeClient(options: RealtimeClientOptions) { + return new RealtimeClient(this.realtimeUrl, { + ...options, + params: { ...{ apikey: this.supabaseKey }, ...options?.params }, + }) + } + + private _listenForAuthEvents() { + let data = this.auth.onAuthStateChange((event, session) => { + this._handleTokenChanged(event, 'CLIENT', session?.access_token) + }) + return data + } + + private _handleTokenChanged( + event: AuthChangeEvent, + source: 'CLIENT' | 'STORAGE', + token?: string + ) { + if ( + (event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') && + this.changedAccessToken !== token + ) { + // Token has changed + this.realtime.setAuth(token ?? null) + + this.changedAccessToken = token + } else if (event === 'SIGNED_OUT') { + // Token is removed + this.realtime.setAuth(this.supabaseKey) + if (source == 'STORAGE') this.auth.signOut() + this.changedAccessToken = undefined + } + } +} diff --git a/node_modules/@supabase/supabase-js/src/index.ts b/node_modules/@supabase/supabase-js/src/index.ts new file mode 100644 index 0000000..c0bba47 --- /dev/null +++ b/node_modules/@supabase/supabase-js/src/index.ts @@ -0,0 +1,39 @@ +import SupabaseClient from './SupabaseClient' +import type { GenericSchema, SupabaseClientOptions } from './lib/types' + +export * from '@supabase/gotrue-js' +export type { User as AuthUser, Session as AuthSession } from '@supabase/gotrue-js' +export type { + PostgrestResponse, + PostgrestSingleResponse, + PostgrestMaybeSingleResponse, + PostgrestError, +} from '@supabase/postgrest-js' +export { + FunctionsHttpError, + FunctionsFetchError, + FunctionsRelayError, + FunctionsError, +} from '@supabase/functions-js' +export * from '@supabase/realtime-js' +export { default as SupabaseClient } from './SupabaseClient' +export type { SupabaseClientOptions } from './lib/types' + +/** + * Creates a new Supabase Client. + */ +export const createClient = < + Database = any, + SchemaName extends string & keyof Database = 'public' extends keyof Database + ? 'public' + : string & keyof Database, + Schema extends GenericSchema = Database[SchemaName] extends GenericSchema + ? Database[SchemaName] + : any +>( + supabaseUrl: string, + supabaseKey: string, + options?: SupabaseClientOptions +): SupabaseClient => { + return new SupabaseClient(supabaseUrl, supabaseKey, options) +} diff --git a/node_modules/@supabase/supabase-js/src/lib/SupabaseAuthClient.ts b/node_modules/@supabase/supabase-js/src/lib/SupabaseAuthClient.ts new file mode 100644 index 0000000..90f92c9 --- /dev/null +++ b/node_modules/@supabase/supabase-js/src/lib/SupabaseAuthClient.ts @@ -0,0 +1,8 @@ +import { GoTrueClient } from '@supabase/gotrue-js' +import { SupabaseAuthClientOptions } from './types' + +export class SupabaseAuthClient extends GoTrueClient { + constructor(options: SupabaseAuthClientOptions) { + super(options) + } +} diff --git a/node_modules/@supabase/supabase-js/src/lib/constants.ts b/node_modules/@supabase/supabase-js/src/lib/constants.ts new file mode 100644 index 0000000..2a40f2b --- /dev/null +++ b/node_modules/@supabase/supabase-js/src/lib/constants.ts @@ -0,0 +1,3 @@ +// constants.ts +import { version } from './version' +export const DEFAULT_HEADERS = { 'X-Client-Info': `supabase-js/${version}` } diff --git a/node_modules/@supabase/supabase-js/src/lib/fetch.ts b/node_modules/@supabase/supabase-js/src/lib/fetch.ts new file mode 100644 index 0000000..dfbe256 --- /dev/null +++ b/node_modules/@supabase/supabase-js/src/lib/fetch.ts @@ -0,0 +1,47 @@ +import crossFetch, { Headers as CrossFetchHeaders } from 'cross-fetch' + +type Fetch = typeof fetch + +export const resolveFetch = (customFetch?: Fetch): Fetch => { + let _fetch: Fetch + if (customFetch) { + _fetch = customFetch + } else if (typeof fetch === 'undefined') { + _fetch = crossFetch as unknown as Fetch + } else { + _fetch = fetch + } + return (...args) => _fetch(...args) +} + +export const resolveHeadersConstructor = () => { + if (typeof Headers === 'undefined') { + return CrossFetchHeaders + } + + return Headers +} + +export const fetchWithAuth = ( + supabaseKey: string, + getAccessToken: () => Promise, + customFetch?: Fetch +): Fetch => { + const fetch = resolveFetch(customFetch) + const HeadersConstructor = resolveHeadersConstructor() + + return async (input, init) => { + const accessToken = (await getAccessToken()) ?? supabaseKey + let headers = new HeadersConstructor(init?.headers) + + if (!headers.has('apikey')) { + headers.set('apikey', supabaseKey) + } + + if (!headers.has('Authorization')) { + headers.set('Authorization', `Bearer ${accessToken}`) + } + + return fetch(input, { ...init, headers }) + } +} diff --git a/node_modules/@supabase/supabase-js/src/lib/helpers.ts b/node_modules/@supabase/supabase-js/src/lib/helpers.ts new file mode 100644 index 0000000..b5243a0 --- /dev/null +++ b/node_modules/@supabase/supabase-js/src/lib/helpers.ts @@ -0,0 +1,58 @@ +// helpers.ts +import { SupabaseClientOptions } from './types' + +export function uuid() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + var r = (Math.random() * 16) | 0, + v = c == 'x' ? r : (r & 0x3) | 0x8 + return v.toString(16) + }) +} + +export function stripTrailingSlash(url: string): string { + return url.replace(/\/$/, '') +} + +export const isBrowser = () => typeof window !== 'undefined' + +export function applySettingDefaults< + Database = any, + SchemaName extends string & keyof Database = 'public' extends keyof Database + ? 'public' + : string & keyof Database +>( + options: SupabaseClientOptions, + defaults: SupabaseClientOptions +): SupabaseClientOptions { + const { + db: dbOptions, + auth: authOptions, + realtime: realtimeOptions, + global: globalOptions, + } = options + const { + db: DEFAULT_DB_OPTIONS, + auth: DEFAULT_AUTH_OPTIONS, + realtime: DEFAULT_REALTIME_OPTIONS, + global: DEFAULT_GLOBAL_OPTIONS, + } = defaults + + return { + db: { + ...DEFAULT_DB_OPTIONS, + ...dbOptions, + }, + auth: { + ...DEFAULT_AUTH_OPTIONS, + ...authOptions, + }, + realtime: { + ...DEFAULT_REALTIME_OPTIONS, + ...realtimeOptions, + }, + global: { + ...DEFAULT_GLOBAL_OPTIONS, + ...globalOptions, + }, + } +} diff --git a/node_modules/@supabase/supabase-js/src/lib/types.ts b/node_modules/@supabase/supabase-js/src/lib/types.ts new file mode 100644 index 0000000..b3e3469 --- /dev/null +++ b/node_modules/@supabase/supabase-js/src/lib/types.ts @@ -0,0 +1,91 @@ +import { GoTrueClient } from '@supabase/gotrue-js' +import { RealtimeClientOptions } from '@supabase/realtime-js' + +type GoTrueClientOptions = ConstructorParameters[0] + +export interface SupabaseAuthClientOptions extends GoTrueClientOptions {} + +export type Fetch = typeof fetch + +export type SupabaseClientOptions = { + /** + * The Postgres schema which your tables belong to. Must be on the list of exposed schemas in Supabase. Defaults to `public`. + */ + db?: { + schema?: SchemaName + } + + auth?: { + /** + * Automatically refreshes the token for logged-in users. Defaults to true. + */ + autoRefreshToken?: boolean + /** + * Optional key name used for storing tokens in local storage. + */ + storageKey?: string + /** + * Whether to persist a logged-in session to storage. Defaults to true. + */ + persistSession?: boolean + /** + * Detect a session from the URL. Used for OAuth login callbacks. Defaults to true. + */ + detectSessionInUrl?: boolean + /** + * A storage provider. Used to store the logged-in session. + */ + storage?: SupabaseAuthClientOptions['storage'] + /** + * OAuth flow to use - defaults to implicit flow. PKCE is recommended for mobile and server-side applications. + */ + flowType?: SupabaseAuthClientOptions['flowType'] + /** + * If debug messages for authentication client are emitted. Can be used to inspect the behavior of the library. + */ + debug?: boolean + } + /** + * Options passed to the realtime-js instance + */ + realtime?: RealtimeClientOptions + global?: { + /** + * A custom `fetch` implementation. + */ + fetch?: Fetch + /** + * Optional headers for initializing the client. + */ + headers?: Record + } +} + +export type GenericTable = { + Row: Record + Insert: Record + Update: Record +} + +export type GenericUpdatableView = { + Row: Record + Insert: Record + Update: Record +} + +export type GenericNonUpdatableView = { + Row: Record +} + +export type GenericView = GenericUpdatableView | GenericNonUpdatableView + +export type GenericFunction = { + Args: Record + Returns: unknown +} + +export type GenericSchema = { + Tables: Record + Views: Record + Functions: Record +} diff --git a/node_modules/@supabase/supabase-js/src/lib/version.ts b/node_modules/@supabase/supabase-js/src/lib/version.ts new file mode 100644 index 0000000..37fd0fb --- /dev/null +++ b/node_modules/@supabase/supabase-js/src/lib/version.ts @@ -0,0 +1 @@ +export const version = '2.31.0' diff --git a/node_modules/@sveltejs/kit/LICENSE b/node_modules/@sveltejs/kit/LICENSE new file mode 100644 index 0000000..22efd0c --- /dev/null +++ b/node_modules/@sveltejs/kit/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2020 [these people](https://github.com/sveltejs/kit/graphs/contributors) + +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/@sveltejs/kit/README.md b/node_modules/@sveltejs/kit/README.md new file mode 100644 index 0000000..cbf03db --- /dev/null +++ b/node_modules/@sveltejs/kit/README.md @@ -0,0 +1,18 @@ +# The fastest way to build Svelte apps + +This is the [SvelteKit](https://kit.svelte.dev) framework and CLI. + +The quickest way to get started is via the [create-svelte](https://github.com/sveltejs/kit/tree/master/packages/create-svelte) package: + +```bash +npm create svelte@latest my-app +cd my-app +npm install +npm run dev +``` + +See the [documentation](https://kit.svelte.dev/docs) to learn more. + +## Changelog + +[The Changelog for this package is available on GitHub](https://github.com/sveltejs/kit/blob/master/packages/kit/CHANGELOG.md). diff --git a/node_modules/@sveltejs/kit/package.json b/node_modules/@sveltejs/kit/package.json new file mode 100644 index 0000000..fd3b7c6 --- /dev/null +++ b/node_modules/@sveltejs/kit/package.json @@ -0,0 +1,101 @@ +{ + "name": "@sveltejs/kit", + "version": "1.22.4", + "description": "The fastest way to build Svelte apps", + "repository": { + "type": "git", + "url": "https://github.com/sveltejs/kit", + "directory": "packages/kit" + }, + "license": "MIT", + "homepage": "https://kit.svelte.dev", + "type": "module", + "dependencies": { + "@sveltejs/vite-plugin-svelte": "^2.4.1", + "@types/cookie": "^0.5.1", + "cookie": "^0.5.0", + "devalue": "^4.3.1", + "esm-env": "^1.0.0", + "kleur": "^4.1.5", + "magic-string": "^0.30.0", + "mime": "^3.0.0", + "sade": "^1.8.1", + "set-cookie-parser": "^2.6.0", + "sirv": "^2.0.2", + "undici": "~5.22.0" + }, + "devDependencies": { + "@playwright/test": "1.30.0", + "@types/connect": "^3.4.35", + "@types/marked": "^4.0.7", + "@types/mime": "^3.0.1", + "@types/node": "^16.18.6", + "@types/sade": "^1.7.4", + "@types/set-cookie-parser": "^2.4.2", + "dts-buddy": "^0.1.9", + "marked": "^4.2.3", + "rollup": "^3.7.0", + "svelte": "^4.0.5", + "svelte-preprocess": "^5.0.4", + "typescript": "^4.9.4", + "vite": "^4.4.2", + "vitest": "^0.33.0" + }, + "peerDependencies": { + "svelte": "^3.54.0 || ^4.0.0-next.0", + "vite": "^4.0.0" + }, + "bin": { + "svelte-kit": "svelte-kit.js" + }, + "files": [ + "src", + "!src/**/*.spec.js", + "!src/core/**/fixtures", + "!src/core/**/test", + "types", + "svelte-kit.js", + "postinstall.js" + ], + "exports": { + "./package.json": "./package.json", + ".": { + "types": "./types/index.d.ts", + "import": "./src/exports/index.js" + }, + "./node": { + "types": "./types/index.d.ts", + "import": "./src/exports/node/index.js" + }, + "./node/polyfills": { + "types": "./types/index.d.ts", + "import": "./src/exports/node/polyfills.js" + }, + "./hooks": { + "types": "./types/index.d.ts", + "import": "./src/exports/hooks/index.js" + }, + "./vite": { + "types": "./types/index.d.ts", + "import": "./src/exports/vite/index.js" + } + }, + "types": "types/index.d.ts", + "engines": { + "node": "^16.14 || >=18" + }, + "scripts": { + "lint": "prettier --check . --config ../../.prettierrc --ignore-path .gitignore", + "check": "tsc", + "check:all": "tsc && pnpm -r --filter=\"./**\" check", + "format": "prettier --write . --config ../../.prettierrc --ignore-path .gitignore", + "test": "pnpm test:unit && pnpm test:integration", + "test:integration": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test", + "test:cross-platform:dev": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test:cross-platform:dev", + "test:cross-platform:build": "pnpm test:unit && pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test:cross-platform:build", + "test:unit": "vitest --config kit.vitest.config.js run", + "postinstall": "node postinstall.js", + "generate:version": "node scripts/generate-version.js", + "generate:types": "node scripts/generate-dts.js" + } +} \ No newline at end of file diff --git a/node_modules/@sveltejs/kit/postinstall.js b/node_modules/@sveltejs/kit/postinstall.js new file mode 100644 index 0000000..6c21883 --- /dev/null +++ b/node_modules/@sveltejs/kit/postinstall.js @@ -0,0 +1,47 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { load_config } from './src/core/config/index.js'; +import { list_files } from './src/core/utils.js'; +import * as sync from './src/core/sync/sync.js'; + +try { + const cwd = process.env.INIT_CWD ?? process.cwd(); + process.chdir(cwd); + + if (fs.existsSync('package.json')) { + const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8')); + + const directories = []; + + if (pkg.workspaces) { + // we have to do this because of https://classic.yarnpkg.com/blog/2018/02/15/nohoist/ + const packages = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces.packages; + + for (const directory of packages) { + directories.push(...list_files(directory).map((dir) => path.resolve(cwd, dir))); + } + } else { + directories.push(cwd); + } + + for (const cwd of directories) { + process.chdir(cwd); + + if (!fs.existsSync('package.json')) continue; + if (!fs.existsSync('svelte.config.js')) continue; + + const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8')); + if (!pkg.dependencies?.['@sveltejs/kit'] && !pkg.devDependencies?.['@sveltejs/kit']) continue; + + try { + const config = await load_config(); + await sync.all(config, 'development'); + } catch (error) { + console.error('Error while trying to sync SvelteKit config'); + console.error(error); + } + } + } +} catch (error) { + console.error(error); +} diff --git a/node_modules/@sveltejs/kit/src/cli.js b/node_modules/@sveltejs/kit/src/cli.js new file mode 100644 index 0000000..9cf2cfa --- /dev/null +++ b/node_modules/@sveltejs/kit/src/cli.js @@ -0,0 +1,44 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import colors from 'kleur'; +import sade from 'sade'; +import { load_config } from './core/config/index.js'; +import { coalesce_to_error } from './utils/error.js'; + +/** @param {unknown} e */ +function handle_error(e) { + const error = coalesce_to_error(e); + + if (error.name === 'SyntaxError') throw error; + + console.error(colors.bold().red(`> ${error.message}`)); + if (error.stack) { + console.error(colors.gray(error.stack.split('\n').slice(1).join('\n'))); + } + + process.exit(1); +} + +const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf-8')); +const prog = sade('svelte-kit').version(pkg.version); + +prog + .command('sync') + .describe('Synchronise generated type definitions') + .option('--mode', 'Specify a mode for loading environment variables', 'development') + .action(async ({ mode }) => { + if (!fs.existsSync('svelte.config.js')) { + console.warn(`Missing ${path.resolve('svelte.config.js')} — skipping`); + return; + } + + try { + const config = await load_config(); + const sync = await import('./core/sync/sync.js'); + await sync.all_types(config, mode); + } catch (error) { + handle_error(error); + } + }); + +prog.parse(process.argv, { unknown: (arg) => `Unknown option: ${arg}` }); diff --git a/node_modules/@sveltejs/kit/src/constants.js b/node_modules/@sveltejs/kit/src/constants.js new file mode 100644 index 0000000..4360335 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/constants.js @@ -0,0 +1,19 @@ +/** + * A fake asset path used in `vite dev` and `vite preview`, so that we can + * serve local assets while verifying that requests are correctly prefixed + */ +export const SVELTE_KIT_ASSETS = '/_svelte_kit_assets'; + +export const GENERATED_COMMENT = '// this file is generated — do not edit it\n'; + +export const ENDPOINT_METHODS = new Set([ + 'GET', + 'POST', + 'PUT', + 'PATCH', + 'DELETE', + 'OPTIONS', + 'HEAD' +]); + +export const PAGE_METHODS = new Set(['GET', 'POST', 'HEAD']); diff --git a/node_modules/@sveltejs/kit/src/core/adapt/builder.js b/node_modules/@sveltejs/kit/src/core/adapt/builder.js new file mode 100644 index 0000000..605382e --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/adapt/builder.js @@ -0,0 +1,223 @@ +import { existsSync, statSync, createReadStream, createWriteStream } from 'node:fs'; +import { extname, join, resolve } from 'node:path'; +import { pipeline } from 'node:stream'; +import { promisify } from 'node:util'; +import zlib from 'node:zlib'; +import { copy, rimraf, mkdirp } from '../../utils/filesystem.js'; +import { generate_manifest } from '../generate_manifest/index.js'; +import { get_route_segments } from '../../utils/routing.js'; +import { get_env } from '../../exports/vite/utils.js'; +import generate_fallback from '../postbuild/fallback.js'; +import { write } from '../sync/utils.js'; +import { list_files } from '../utils.js'; + +const pipe = promisify(pipeline); +const extensions = ['.html', '.js', '.mjs', '.json', '.css', '.svg', '.xml', '.wasm']; + +/** + * Creates the Builder which is passed to adapters for building the application. + * @param {{ + * config: import('types').ValidatedConfig; + * build_data: import('types').BuildData; + * server_metadata: import('types').ServerMetadata; + * route_data: import('types').RouteData[]; + * prerendered: import('types').Prerendered; + * prerender_map: import('types').PrerenderMap; + * log: import('types').Logger; + * }} opts + * @returns {import('@sveltejs/kit').Builder} + */ +export function create_builder({ + config, + build_data, + server_metadata, + route_data, + prerendered, + prerender_map, + log +}) { + /** @type {Map} */ + const lookup = new Map(); + + /** + * Rather than exposing the internal `RouteData` type, which is subject to change, + * we expose a stable type that adapters can use to group/filter routes + */ + const routes = route_data.map((route) => { + const { config, methods, page, api } = /** @type {import('types').ServerMetadataRoute} */ ( + server_metadata.routes.get(route.id) + ); + + /** @type {import('@sveltejs/kit').RouteDefinition} */ + const facade = { + id: route.id, + api, + page, + segments: get_route_segments(route.id).map((segment) => ({ + dynamic: segment.includes('['), + rest: segment.includes('[...'), + content: segment + })), + pattern: route.pattern, + prerender: prerender_map.get(route.id) ?? false, + methods, + config + }; + + lookup.set(facade, route); + + return facade; + }); + + return { + log, + rimraf, + mkdirp, + copy, + + config, + prerendered, + routes, + + async compress(directory) { + if (!existsSync(directory)) { + return; + } + + const files = list_files(directory, (file) => extensions.includes(extname(file))).map( + (file) => resolve(directory, file) + ); + + await Promise.all( + files.flatMap((file) => [compress_file(file, 'gz'), compress_file(file, 'br')]) + ); + }, + + async createEntries(fn) { + const seen = new Set(); + + for (let i = 0; i < route_data.length; i += 1) { + const route = route_data[i]; + if (prerender_map.get(route.id) === true) continue; + const { id, filter, complete } = fn(routes[i]); + + if (seen.has(id)) continue; + seen.add(id); + + const group = [route]; + + // figure out which lower priority routes should be considered fallbacks + for (let j = i + 1; j < route_data.length; j += 1) { + if (prerender_map.get(routes[j].id) === true) continue; + if (filter(routes[j])) { + group.push(route_data[j]); + } + } + + const filtered = new Set(group); + + // heuristic: if /foo/[bar] is included, /foo/[bar].json should + // also be included, since the page likely needs the endpoint + // TODO is this still necessary, given the new way of doing things? + filtered.forEach((route) => { + if (route.page) { + const endpoint = route_data.find((candidate) => candidate.id === route.id + '.json'); + + if (endpoint) { + filtered.add(endpoint); + } + } + }); + + if (filtered.size > 0) { + await complete({ + generateManifest: ({ relativePath }) => + generate_manifest({ + build_data, + relative_path: relativePath, + routes: Array.from(filtered) + }) + }); + } + } + }, + + async generateFallback(dest) { + const manifest_path = `${config.kit.outDir}/output/server/manifest-full.js`; + const env = get_env(config.kit.env, 'production'); + + const fallback = await generate_fallback({ + manifest_path, + env: { ...env.private, ...env.public } + }); + + write(dest, fallback); + }, + + generateManifest({ relativePath, routes: subset }) { + return generate_manifest({ + build_data, + relative_path: relativePath, + routes: subset + ? subset.map((route) => /** @type {import('types').RouteData} */ (lookup.get(route))) + : route_data.filter((route) => prerender_map.get(route.id) !== true) + }); + }, + + getBuildDirectory(name) { + return `${config.kit.outDir}/${name}`; + }, + + getClientDirectory() { + return `${config.kit.outDir}/output/client`; + }, + + getServerDirectory() { + return `${config.kit.outDir}/output/server`; + }, + + getAppPath() { + return build_data.app_path; + }, + + writeClient(dest) { + const server_assets = copy( + `${config.kit.outDir}/output/server/${config.kit.appDir}/immutable/assets`, + join(dest, config.kit.appDir, 'immutable/assets') + ).map((filename) => join(config.kit.appDir, 'immutable/assets', filename)); + const client_assets = copy(`${config.kit.outDir}/output/client`, dest); + return Array.from(new Set([...server_assets, ...client_assets])); + }, + + writePrerendered(dest) { + const source = `${config.kit.outDir}/output/prerendered`; + return [...copy(`${source}/pages`, dest), ...copy(`${source}/dependencies`, dest)]; + }, + + writeServer(dest) { + return copy(`${config.kit.outDir}/output/server`, dest); + } + }; +} + +/** + * @param {string} file + * @param {'gz' | 'br'} format + */ +async function compress_file(file, format = 'gz') { + const compress = + format == 'br' + ? zlib.createBrotliCompress({ + params: { + [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT, + [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY, + [zlib.constants.BROTLI_PARAM_SIZE_HINT]: statSync(file).size + } + }) + : zlib.createGzip({ level: zlib.constants.Z_BEST_COMPRESSION }); + + const source = createReadStream(file); + const destination = createWriteStream(`${file}.${format}`); + + await pipe(source, compress, destination); +} diff --git a/node_modules/@sveltejs/kit/src/core/adapt/index.js b/node_modules/@sveltejs/kit/src/core/adapt/index.js new file mode 100644 index 0000000..b5b3d15 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/adapt/index.js @@ -0,0 +1,29 @@ +import colors from 'kleur'; +import { create_builder } from './builder.js'; + +/** + * @param {import('types').ValidatedConfig} config + * @param {import('types').BuildData} build_data + * @param {import('types').ServerMetadata} server_metadata + * @param {import('types').Prerendered} prerendered + * @param {import('types').PrerenderMap} prerender_map + * @param {import('types').Logger} log + */ +export async function adapt(config, build_data, server_metadata, prerendered, prerender_map, log) { + const { name, adapt } = config.kit.adapter; + + console.log(colors.bold().cyan(`\n> Using ${name}`)); + + const builder = create_builder({ + config, + build_data, + server_metadata, + route_data: build_data.manifest_data.routes.filter((route) => route.page || route.endpoint), + prerendered, + prerender_map, + log + }); + await adapt(builder); + + log.success('done'); +} diff --git a/node_modules/@sveltejs/kit/src/core/config/default-error.html b/node_modules/@sveltejs/kit/src/core/config/default-error.html new file mode 100644 index 0000000..12d998b --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/config/default-error.html @@ -0,0 +1,70 @@ + + + + + %sveltekit.error.message% + + + + +
+ %sveltekit.status% +
+

%sveltekit.error.message%

+
+
+ + diff --git a/node_modules/@sveltejs/kit/src/core/config/index.js b/node_modules/@sveltejs/kit/src/core/config/index.js new file mode 100644 index 0000000..a6e37d7 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/config/index.js @@ -0,0 +1,109 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import * as url from 'node:url'; +import options from './options.js'; + +/** + * Loads the template (src/app.html by default) and validates that it has the + * required content. + * @param {string} cwd + * @param {import('types').ValidatedConfig} config + */ +export function load_template(cwd, { kit }) { + const { env, files } = kit; + + const relative = path.relative(cwd, files.appTemplate); + + if (!fs.existsSync(files.appTemplate)) { + throw new Error(`${relative} does not exist`); + } + + const contents = fs.readFileSync(files.appTemplate, 'utf8'); + + const expected_tags = ['%sveltekit.head%', '%sveltekit.body%']; + expected_tags.forEach((tag) => { + if (contents.indexOf(tag) === -1) { + throw new Error(`${relative} is missing ${tag}`); + } + }); + + for (const match of contents.matchAll(/%sveltekit\.env\.([^%]+)%/g)) { + if (!match[1].startsWith(env.publicPrefix)) { + throw new Error( + `Environment variables in ${relative} must start with ${env.publicPrefix} (saw %sveltekit.env.${match[1]}%)` + ); + } + } + + return contents; +} + +/** + * Loads the error page (src/error.html by default) if it exists. + * Falls back to a generic error page content. + * @param {import('types').ValidatedConfig} config + */ +export function load_error_page(config) { + let { errorTemplate } = config.kit.files; + + // Don't do this inside resolving the config, because that would mean + // adding/removing error.html isn't detected and would require a restart. + if (!fs.existsSync(config.kit.files.errorTemplate)) { + errorTemplate = url.fileURLToPath(new URL('./default-error.html', import.meta.url)); + } + + return fs.readFileSync(errorTemplate, 'utf-8'); +} + +/** + * Loads and validates svelte.config.js + * @param {{ cwd?: string }} options + * @returns {Promise} + */ +export async function load_config({ cwd = process.cwd() } = {}) { + const config_file = path.join(cwd, 'svelte.config.js'); + + if (!fs.existsSync(config_file)) { + return process_config({}, { cwd }); + } + + const config = await import(`${url.pathToFileURL(config_file).href}?ts=${Date.now()}`); + + return process_config(config.default, { cwd }); +} + +/** + * @param {import('@sveltejs/kit').Config} config + * @returns {import('types').ValidatedConfig} + */ +function process_config(config, { cwd = process.cwd() } = {}) { + const validated = validate_config(config); + + validated.kit.outDir = path.resolve(cwd, validated.kit.outDir); + + for (const key in validated.kit.files) { + if (key === 'hooks') { + validated.kit.files.hooks.client = path.resolve(cwd, validated.kit.files.hooks.client); + validated.kit.files.hooks.server = path.resolve(cwd, validated.kit.files.hooks.server); + } else { + // @ts-expect-error + validated.kit.files[key] = path.resolve(cwd, validated.kit.files[key]); + } + } + + return validated; +} + +/** + * @param {import('@sveltejs/kit').Config} config + * @returns {import('types').ValidatedConfig} + */ +export function validate_config(config) { + if (typeof config !== 'object') { + throw new Error( + 'svelte.config.js must have a configuration object as its default export. See https://kit.svelte.dev/docs/configuration' + ); + } + + return options(config, 'config'); +} diff --git a/node_modules/@sveltejs/kit/src/core/config/options.js b/node_modules/@sveltejs/kit/src/core/config/options.js new file mode 100644 index 0000000..7d73510 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/config/options.js @@ -0,0 +1,438 @@ +import { join } from 'node:path'; + +/** @typedef {import('./types').Validator} Validator */ + +const directives = object({ + 'child-src': string_array(), + 'default-src': string_array(), + 'frame-src': string_array(), + 'worker-src': string_array(), + 'connect-src': string_array(), + 'font-src': string_array(), + 'img-src': string_array(), + 'manifest-src': string_array(), + 'media-src': string_array(), + 'object-src': string_array(), + 'prefetch-src': string_array(), + 'script-src': string_array(), + 'script-src-elem': string_array(), + 'script-src-attr': string_array(), + 'style-src': string_array(), + 'style-src-elem': string_array(), + 'style-src-attr': string_array(), + 'base-uri': string_array(), + sandbox: string_array(), + 'form-action': string_array(), + 'frame-ancestors': string_array(), + 'navigate-to': string_array(), + 'report-uri': string_array(), + 'report-to': string_array(), + 'require-trusted-types-for': string_array(), + 'trusted-types': string_array(), + 'upgrade-insecure-requests': boolean(false), + 'require-sri-for': string_array(), + 'block-all-mixed-content': boolean(false), + 'plugin-types': string_array(), + referrer: string_array() +}); + +/** @type {Validator} */ +const options = object( + { + extensions: validate(['.svelte'], (input, keypath) => { + if (!Array.isArray(input) || !input.every((page) => typeof page === 'string')) { + throw new Error(`${keypath} must be an array of strings`); + } + + input.forEach((extension) => { + if (extension[0] !== '.') { + throw new Error(`Each member of ${keypath} must start with '.' — saw '${extension}'`); + } + + if (!/^(\.[a-z0-9]+)+$/i.test(extension)) { + throw new Error(`File extensions must be alphanumeric — saw '${extension}'`); + } + }); + + return input; + }), + + kit: object({ + adapter: validate(null, (input, keypath) => { + if (typeof input !== 'object' || !input.adapt) { + let message = `${keypath} should be an object with an "adapt" method`; + + if (Array.isArray(input) || typeof input === 'string') { + // for the early adapter adopters + message += ', rather than the name of an adapter'; + } + + throw new Error(`${message}. See https://kit.svelte.dev/docs/adapters`); + } + + return input; + }), + + alias: validate({}, (input, keypath) => { + if (typeof input !== 'object') { + throw new Error(`${keypath} should be an object`); + } + + for (const key in input) { + assert_string(input[key], `${keypath}.${key}`); + } + + return input; + }), + + appDir: validate('_app', (input, keypath) => { + assert_string(input, keypath); + + if (input) { + if (input.startsWith('/') || input.endsWith('/')) { + throw new Error( + "config.kit.appDir cannot start or end with '/'. See https://kit.svelte.dev/docs/configuration" + ); + } + } else { + throw new Error(`${keypath} cannot be empty`); + } + + return input; + }), + + csp: object({ + mode: list(['auto', 'hash', 'nonce']), + directives, + reportOnly: directives + }), + + csrf: object({ + checkOrigin: boolean(true) + }), + + dangerZone: object({ + // TODO 2.0: Remove this + trackServerFetches: boolean(false) + }), + + embedded: boolean(false), + + env: object({ + dir: string(process.cwd()), + publicPrefix: string('PUBLIC_'), + privatePrefix: string('') + }), + + files: object({ + assets: string('static'), + hooks: object({ + client: string(join('src', 'hooks.client')), + server: string(join('src', 'hooks.server')) + }), + lib: string(join('src', 'lib')), + params: string(join('src', 'params')), + routes: string(join('src', 'routes')), + serviceWorker: string(join('src', 'service-worker')), + appTemplate: string(join('src', 'app.html')), + errorTemplate: string(join('src', 'error.html')) + }), + + inlineStyleThreshold: number(0), + + moduleExtensions: string_array(['.js', '.ts']), + + outDir: string('.svelte-kit'), + + output: object({ + preloadStrategy: list(['modulepreload', 'preload-js', 'preload-mjs'], 'modulepreload') + }), + + paths: object({ + base: validate('', (input, keypath) => { + assert_string(input, keypath); + + if (input !== '' && (input.endsWith('/') || !input.startsWith('/'))) { + throw new Error( + `${keypath} option must either be the empty string or a root-relative path that starts but doesn't end with '/'. See https://kit.svelte.dev/docs/configuration#paths` + ); + } + + return input; + }), + assets: validate('', (input, keypath) => { + assert_string(input, keypath); + + if (input) { + if (!/^[a-z]+:\/\//.test(input)) { + throw new Error( + `${keypath} option must be an absolute path, if specified. See https://kit.svelte.dev/docs/configuration#paths` + ); + } + + if (input.endsWith('/')) { + throw new Error( + `${keypath} option must not end with '/'. See https://kit.svelte.dev/docs/configuration#paths` + ); + } + } + + return input; + }), + relative: validate(undefined, (input, keypath) => { + if (typeof input !== 'boolean') { + throw new Error(`${keypath} option must be a boolean or undefined`); + } + + return input; + }) + }), + + prerender: object({ + concurrency: number(1), + crawl: boolean(true), + entries: validate(['*'], (input, keypath) => { + if (!Array.isArray(input) || !input.every((page) => typeof page === 'string')) { + throw new Error(`${keypath} must be an array of strings`); + } + + input.forEach((page) => { + if (page !== '*' && page[0] !== '/') { + throw new Error( + `Each member of ${keypath} must be either '*' or an absolute path beginning with '/' — saw '${page}'` + ); + } + }); + + return input; + }), + + handleHttpError: validate( + (/** @type {any} */ { message }) => { + throw new Error( + message + + '\nTo suppress or handle this error, implement `handleHttpError` in https://kit.svelte.dev/docs/configuration#prerender' + ); + }, + (input, keypath) => { + if (typeof input === 'function') return input; + if (['fail', 'warn', 'ignore'].includes(input)) return input; + throw new Error(`${keypath} should be "fail", "warn", "ignore" or a custom function`); + } + ), + + handleMissingId: validate( + (/** @type {any} */ { message }) => { + throw new Error( + message + + '\nTo suppress or handle this error, implement `handleMissingId` in https://kit.svelte.dev/docs/configuration#prerender' + ); + }, + (input, keypath) => { + if (typeof input === 'function') return input; + if (['fail', 'warn', 'ignore'].includes(input)) return input; + throw new Error(`${keypath} should be "fail", "warn", "ignore" or a custom function`); + } + ), + + handleEntryGeneratorMismatch: validate( + (/** @type {any} */ { message }) => { + throw new Error( + message + + '\nTo suppress or handle this error, implement `handleEntryGeneratorMismatch` in https://kit.svelte.dev/docs/configuration#prerender' + ); + }, + (input, keypath) => { + if (typeof input === 'function') return input; + if (['fail', 'warn', 'ignore'].includes(input)) return input; + throw new Error(`${keypath} should be "fail", "warn", "ignore" or a custom function`); + } + ), + + origin: validate('http://sveltekit-prerender', (input, keypath) => { + assert_string(input, keypath); + + let origin; + + try { + origin = new URL(input).origin; + } catch (e) { + throw new Error(`${keypath} must be a valid origin`); + } + + if (input !== origin) { + throw new Error(`${keypath} must be a valid origin (${origin} rather than ${input})`); + } + + return origin; + }) + }), + + serviceWorker: object({ + register: boolean(true), + files: fun((filename) => !/\.DS_Store/.test(filename)) + }), + + typescript: object({ + config: fun((config) => config) + }), + + version: object({ + name: string(Date.now().toString()), + pollInterval: number(0) + }) + }) + }, + true +); + +/** + * @param {Record} children + * @param {boolean} [allow_unknown] + * @returns {Validator} + */ +function object(children, allow_unknown = false) { + return (input, keypath) => { + /** @type {Record} */ + const output = {}; + + if ((input && typeof input !== 'object') || Array.isArray(input)) { + throw new Error(`${keypath} should be an object`); + } + + for (const key in input) { + if (!(key in children)) { + if (allow_unknown) { + output[key] = input[key]; + } else { + let message = `Unexpected option ${keypath}.${key}`; + + // special case + if (keypath === 'config.kit' && key in options) { + message += ` (did you mean config.${key}?)`; + } + + throw new Error(message); + } + } + } + + for (const key in children) { + const validator = children[key]; + output[key] = validator(input && input[key], `${keypath}.${key}`); + } + + return output; + }; +} + +/** + * @param {any} fallback + * @param {(value: any, keypath: string) => any} fn + * @returns {Validator} + */ +function validate(fallback, fn) { + return (input, keypath) => { + return input === undefined ? fallback : fn(input, keypath); + }; +} + +/** + * @param {string | null} fallback + * @param {boolean} allow_empty + * @returns {Validator} + */ +function string(fallback, allow_empty = true) { + return validate(fallback, (input, keypath) => { + assert_string(input, keypath); + + if (!allow_empty && input === '') { + throw new Error(`${keypath} cannot be empty`); + } + + return input; + }); +} + +/** + * @param {string[] | undefined} [fallback] + * @returns {Validator} + */ +function string_array(fallback) { + return validate(fallback, (input, keypath) => { + if (!Array.isArray(input) || input.some((value) => typeof value !== 'string')) { + throw new Error(`${keypath} must be an array of strings, if specified`); + } + + return input; + }); +} + +/** + * @param {number} fallback + * @returns {Validator} + */ +function number(fallback) { + return validate(fallback, (input, keypath) => { + if (typeof input !== 'number') { + throw new Error(`${keypath} should be a number, if specified`); + } + return input; + }); +} + +/** + * @param {boolean} fallback + * @returns {Validator} + */ +function boolean(fallback) { + return validate(fallback, (input, keypath) => { + if (typeof input !== 'boolean') { + throw new Error(`${keypath} should be true or false, if specified`); + } + return input; + }); +} + +/** + * @param {string[]} options + * @returns {Validator} + */ +function list(options, fallback = options[0]) { + return validate(fallback, (input, keypath) => { + if (!options.includes(input)) { + // prettier-ignore + const msg = options.length > 2 + ? `${keypath} should be one of ${options.slice(0, -1).map(input => `"${input}"`).join(', ')} or "${options[options.length - 1]}"` + : `${keypath} should be either "${options[0]}" or "${options[1]}"`; + + throw new Error(msg); + } + return input; + }); +} + +/** + * @param {(...args: any) => any} fallback + * @returns {Validator} + */ +function fun(fallback) { + return validate(fallback, (input, keypath) => { + if (typeof input !== 'function') { + throw new Error(`${keypath} should be a function, if specified`); + } + return input; + }); +} + +/** + * @param {string} input + * @param {string} keypath + */ +function assert_string(input, keypath) { + if (typeof input !== 'string') { + throw new Error(`${keypath} should be a string, if specified`); + } +} + +export default options; diff --git a/node_modules/@sveltejs/kit/src/core/config/types.d.ts b/node_modules/@sveltejs/kit/src/core/config/types.d.ts new file mode 100644 index 0000000..00d005c --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/config/types.d.ts @@ -0,0 +1 @@ +export type Validator = (input: T, keypath: string) => T; diff --git a/node_modules/@sveltejs/kit/src/core/env.js b/node_modules/@sveltejs/kit/src/core/env.js new file mode 100644 index 0000000..455eb0f --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/env.js @@ -0,0 +1,152 @@ +import { GENERATED_COMMENT } from '../constants.js'; +import { dedent } from './sync/utils.js'; +import { runtime_base } from './utils.js'; + +/** + * @typedef {'public' | 'private'} EnvType + */ + +/** + * @param {string} id + * @param {Record} env + * @returns {string} + */ +export function create_static_module(id, env) { + /** @type {string[]} */ + const declarations = []; + + for (const key in env) { + if (!valid_identifier.test(key) || reserved.has(key)) { + continue; + } + + const comment = `/** @type {import('${id}').${key}} */`; + const declaration = `export const ${key} = ${JSON.stringify(env[key])};`; + + declarations.push(`${comment}\n${declaration}`); + } + + return GENERATED_COMMENT + declarations.join('\n\n'); +} + +/** + * @param {EnvType} type + * @param {Record | undefined} dev_values If in a development mode, values to pre-populate the module with. + */ +export function create_dynamic_module(type, dev_values) { + if (dev_values) { + const keys = Object.entries(dev_values).map( + ([k, v]) => `${JSON.stringify(k)}: ${JSON.stringify(v)}` + ); + return `export const env = {\n${keys.join(',\n')}\n}`; + } + return `export { ${type}_env as env } from '${runtime_base}/shared-server.js';`; +} + +/** + * @param {EnvType} id + * @param {import('types').Env} env + * @returns {string} + */ +export function create_static_types(id, env) { + const declarations = Object.keys(env[id]) + .filter((k) => valid_identifier.test(k)) + .map((k) => `export const ${k}: string;`); + + return dedent` + declare module '$env/static/${id}' { + ${declarations.join('\n')} + } + `; +} + +/** + * @param {EnvType} id + * @param {import('types').Env} env + * @param {{ + * public_prefix: string; + * private_prefix: string; + * }} prefixes + * @returns {string} + */ +export function create_dynamic_types(id, env, { public_prefix, private_prefix }) { + const properties = Object.keys(env[id]) + .filter((k) => valid_identifier.test(k)) + .map((k) => `${k}: string;`); + + const public_prefixed = `[key: \`${public_prefix}\${string}\`]`; + const private_prefixed = `[key: \`${private_prefix}\${string}\`]`; + + if (id === 'private') { + if (public_prefix) { + properties.push(`${public_prefixed}: undefined;`); + } + properties.push(`${private_prefixed}: string | undefined;`); + } else { + if (private_prefix) { + properties.push(`${private_prefixed}: undefined;`); + } + properties.push(`${public_prefixed}: string | undefined;`); + } + + return dedent` + declare module '$env/dynamic/${id}' { + export const env: { + ${properties.join('\n')} + } + } + `; +} + +export const reserved = new Set([ + 'do', + 'if', + 'in', + 'for', + 'let', + 'new', + 'try', + 'var', + 'case', + 'else', + 'enum', + 'eval', + 'null', + 'this', + 'true', + 'void', + 'with', + 'await', + 'break', + 'catch', + 'class', + 'const', + 'false', + 'super', + 'throw', + 'while', + 'yield', + 'delete', + 'export', + 'import', + 'public', + 'return', + 'static', + 'switch', + 'typeof', + 'default', + 'extends', + 'finally', + 'package', + 'private', + 'continue', + 'debugger', + 'function', + 'arguments', + 'interface', + 'protected', + 'implements', + 'instanceof' +]); + +export const valid_identifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/; diff --git a/node_modules/@sveltejs/kit/src/core/generate_manifest/index.js b/node_modules/@sveltejs/kit/src/core/generate_manifest/index.js new file mode 100644 index 0000000..272d79e --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/generate_manifest/index.js @@ -0,0 +1,122 @@ +import { s } from '../../utils/misc.js'; +import { get_mime_lookup } from '../utils.js'; +import { resolve_symlinks } from '../../exports/vite/build/utils.js'; +import { compact } from '../../utils/array.js'; +import { join_relative } from '../../utils/filesystem.js'; +import { dedent } from '../sync/utils.js'; + +/** + * Generates the data used to write the server-side manifest.js file. This data is used in the Vite + * build process, to power routing, etc. + * @param {{ + * build_data: import('types').BuildData; + * relative_path: string; + * routes: import('types').RouteData[]; + * }} opts + */ +export function generate_manifest({ build_data, relative_path, routes }) { + /** + * @type {Map} The new index of each node in the filtered nodes array + */ + const reindexed = new Map(); + /** + * All nodes actually used in the routes definition (prerendered routes are omitted). + * Root layout/error is always included as they are needed for 404 and root errors. + * @type {Set} + */ + const used_nodes = new Set([0, 1]); + + for (const route of routes) { + if (route.page) { + for (const i of route.page.layouts) used_nodes.add(i); + for (const i of route.page.errors) used_nodes.add(i); + used_nodes.add(route.page.leaf); + } + } + + const node_paths = compact( + build_data.manifest_data.nodes.map((_, i) => { + if (used_nodes.has(i)) { + reindexed.set(i, reindexed.size); + return join_relative(relative_path, `/nodes/${i}.js`); + } + }) + ); + + /** @type {(path: string) => string} */ + const loader = (path) => `__memo(() => import('${path}'))`; + + const assets = build_data.manifest_data.assets.map((asset) => asset.file); + if (build_data.service_worker) { + assets.push(build_data.service_worker); + } + + const matchers = new Set(); + + /** @param {Array} indexes */ + function get_nodes(indexes) { + const string = indexes.map((n) => reindexed.get(n) ?? '').join(','); + + // since JavaScript ignores trailing commas, we need to insert a dummy + // comma so that the array has the correct length if the last item + // is undefined + return `[${string},]`; + } + + // prettier-ignore + // String representation of + /** @template {import('@sveltejs/kit').SSRManifest} T */ + const manifest_expr = dedent` + { + appDir: ${s(build_data.app_dir)}, + appPath: ${s(build_data.app_path)}, + assets: new Set(${s(assets)}), + mimeTypes: ${s(get_mime_lookup(build_data.manifest_data))}, + _: { + client: ${s(build_data.client)}, + nodes: [ + ${(node_paths).map(loader).join(',\n')} + ], + routes: [ + ${routes.map(route => { + if (!route.page && !route.endpoint) return; + + route.params.forEach(param => { + if (param.matcher) matchers.add(param.matcher); + }); + + return dedent` + { + id: ${s(route.id)}, + pattern: ${route.pattern}, + params: ${s(route.params)}, + page: ${route.page ? `{ layouts: ${get_nodes(route.page.layouts)}, errors: ${get_nodes(route.page.errors)}, leaf: ${reindexed.get(route.page.leaf)} }` : 'null'}, + endpoint: ${route.endpoint ? loader(join_relative(relative_path, resolve_symlinks(build_data.server_manifest, route.endpoint.file).chunk.file)) : 'null'} + } + `; + }).filter(Boolean).join(',\n')} + ], + matchers: async () => { + ${Array.from( + matchers, + type => `const { match: ${type} } = await import ('${(join_relative(relative_path, `/entries/matchers/${type}.js`))}')` + ).join('\n')} + return { ${Array.from(matchers).join(', ')} }; + } + } + } + `; + + // Memoize the loaders to prevent Node from doing unnecessary work + // on every dynamic import call + return dedent` + (() => { + function __memo(fn) { + let value; + return () => value ??= (value = fn()); + } + + return ${manifest_expr} + })() + `; +} diff --git a/node_modules/@sveltejs/kit/src/core/postbuild/analyse.js b/node_modules/@sveltejs/kit/src/core/postbuild/analyse.js new file mode 100644 index 0000000..a78924d --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/postbuild/analyse.js @@ -0,0 +1,172 @@ +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { get_option } from '../../utils/options.js'; +import { + validate_layout_exports, + validate_layout_server_exports, + validate_page_exports, + validate_page_server_exports, + validate_server_exports +} from '../../utils/exports.js'; +import { load_config } from '../config/index.js'; +import { forked } from '../../utils/fork.js'; +import { should_polyfill } from '../../utils/platform.js'; +import { installPolyfills } from '../../exports/node/polyfills.js'; +import { resolvePath } from '../../exports/index.js'; +import { ENDPOINT_METHODS } from '../../constants.js'; +import { filter_private_env, filter_public_env } from '../../utils/env.js'; + +export default forked(import.meta.url, analyse); + +/** + * @param {{ + * manifest_path: string; + * env: Record + * }} opts + */ +async function analyse({ manifest_path, env }) { + /** @type {import('@sveltejs/kit').SSRManifest} */ + const manifest = (await import(pathToFileURL(manifest_path).href)).manifest; + + /** @type {import('types').ValidatedKitConfig} */ + const config = (await load_config()).kit; + + const server_root = join(config.outDir, 'output'); + + /** @type {import('types').ServerInternalModule} */ + const internal = await import(pathToFileURL(`${server_root}/server/internal.js`).href); + + if (should_polyfill) { + installPolyfills(); + } + + // configure `import { building } from '$app/environment'` — + // essential we do this before analysing the code + internal.set_building(true); + + // set env, in case it's used in initialisation + const { publicPrefix: public_prefix, privatePrefix: private_prefix } = config.env; + internal.set_private_env(filter_private_env(env, { public_prefix, private_prefix })); + internal.set_public_env(filter_public_env(env, { public_prefix, private_prefix })); + + /** @type {import('types').ServerMetadata} */ + const metadata = { + nodes: [], + routes: new Map() + }; + + // analyse nodes + for (const loader of manifest._.nodes) { + const node = await loader(); + + metadata.nodes[node.index] = { + has_server_load: node.server?.load !== undefined + }; + } + + // analyse routes + for (const route of manifest._.routes) { + /** @type {Array<'GET' | 'POST'>} */ + const page_methods = []; + + /** @type {import('types').HttpMethod[]} */ + const api_methods = []; + + /** @type {import('types').PrerenderOption | undefined} */ + let prerender = undefined; + /** @type {any} */ + let config = undefined; + /** @type {import('types').PrerenderEntryGenerator | undefined} */ + let entries = undefined; + + if (route.endpoint) { + const mod = await route.endpoint(); + if (mod.prerender !== undefined) { + validate_server_exports(mod, route.id); + + if (mod.prerender && (mod.POST || mod.PATCH || mod.PUT || mod.DELETE)) { + throw new Error( + `Cannot prerender a +server file with POST, PATCH, PUT, or DELETE (${route.id})` + ); + } + + prerender = mod.prerender; + } + + Object.values(mod).forEach((/** @type {import('types').HttpMethod} */ method) => { + if (mod[method] && ENDPOINT_METHODS.has(method)) { + api_methods.push(method); + } + }); + + config = mod.config; + entries = mod.entries; + } + + if (route.page) { + const nodes = await Promise.all( + [...route.page.layouts, route.page.leaf].map((n) => { + if (n !== undefined) return manifest._.nodes[n](); + }) + ); + + const layouts = nodes.slice(0, -1); + const page = nodes.at(-1); + + for (const layout of layouts) { + if (layout) { + validate_layout_server_exports(layout.server, layout.server_id); + validate_layout_exports(layout.universal, layout.universal_id); + } + } + + if (page) { + page_methods.push('GET'); + if (page.server?.actions) page_methods.push('POST'); + + validate_page_server_exports(page.server, page.server_id); + validate_page_exports(page.universal, page.universal_id); + } + + prerender = get_option(nodes, 'prerender') ?? false; + + config = get_config(nodes); + entries ??= get_option(nodes, 'entries'); + } + + metadata.routes.set(route.id, { + config, + methods: Array.from(new Set([...page_methods, ...api_methods])), + page: { + methods: page_methods + }, + api: { + methods: api_methods + }, + prerender, + entries: + entries && (await entries()).map((entry_object) => resolvePath(route.id, entry_object)) + }); + } + + return metadata; +} + +/** + * Do a shallow merge (first level) of the config object + * @param {Array} nodes + */ +function get_config(nodes) { + let current = {}; + for (const node of nodes) { + const config = node?.universal?.config ?? node?.server?.config; + if (config) { + current = { + ...current, + ...config + }; + } + } + + return Object.keys(current).length ? current : undefined; +} diff --git a/node_modules/@sveltejs/kit/src/core/postbuild/crawl.js b/node_modules/@sveltejs/kit/src/core/postbuild/crawl.js new file mode 100644 index 0000000..caffef5 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/postbuild/crawl.js @@ -0,0 +1,243 @@ +import { resolve } from '../../utils/url.js'; +import { decode } from './entities.js'; + +const DOCTYPE = 'DOCTYPE'; +const CDATA_OPEN = '[CDATA['; +const CDATA_CLOSE = ']]>'; +const COMMENT_OPEN = '--'; +const COMMENT_CLOSE = '-->'; + +const TAG_OPEN = /[a-zA-Z]/; +const TAG_CHAR = /[a-zA-Z0-9]/; +const ATTRIBUTE_NAME = /[^\t\n\f />"'=]/; + +const WHITESPACE = /[\s\n\r]/; + +const CRAWLABLE_META_NAME_ATTRS = new Set([ + 'og:url', + 'og:image', + 'og:image:url', + 'og:image:secure_url', + 'og:video', + 'og:video:url', + 'og:video:secure_url', + 'og:audio', + 'og:audio:url', + 'og:audio:secure_url', + 'twitter:image' +]); + +/** + * @param {string} html + * @param {string} base + */ +export function crawl(html, base) { + /** @type {string[]} */ + const ids = []; + + /** @type {string[]} */ + const hrefs = []; + + let i = 0; + main: while (i < html.length) { + const char = html[i]; + + if (char === '<') { + if (html[i + 1] === '!') { + i += 2; + + if (html.slice(i, i + DOCTYPE.length).toUpperCase() === DOCTYPE) { + i += DOCTYPE.length; + while (i < html.length) { + if (html[i++] === '>') { + continue main; + } + } + } + + // skip cdata + if (html.slice(i, i + CDATA_OPEN.length) === CDATA_OPEN) { + i += CDATA_OPEN.length; + while (i < html.length) { + if (html.slice(i, i + CDATA_CLOSE.length) === CDATA_CLOSE) { + i += CDATA_CLOSE.length; + continue main; + } + + i += 1; + } + } + + // skip comments + if (html.slice(i, i + COMMENT_OPEN.length) === COMMENT_OPEN) { + i += COMMENT_OPEN.length; + while (i < html.length) { + if (html.slice(i, i + COMMENT_CLOSE.length) === COMMENT_CLOSE) { + i += COMMENT_CLOSE.length; + continue main; + } + + i += 1; + } + } + } + + // parse opening tags + const start = ++i; + if (TAG_OPEN.test(html[start])) { + while (i < html.length) { + if (!TAG_CHAR.test(html[i])) { + break; + } + + i += 1; + } + + const tag = html.slice(start, i).toUpperCase(); + + /** @type {Record} */ + const attributes = {}; + + if (tag === 'SCRIPT' || tag === 'STYLE') { + while (i < html.length) { + if ( + html[i] === '<' && + html[i + 1] === '/' && + html.slice(i + 2, i + 2 + tag.length).toUpperCase() === tag + ) { + continue main; + } + + i += 1; + } + } + + while (i < html.length) { + const start = i; + + const char = html[start]; + if (char === '>') break; + + if (ATTRIBUTE_NAME.test(char)) { + i += 1; + + while (i < html.length) { + if (!ATTRIBUTE_NAME.test(html[i])) { + break; + } + + i += 1; + } + + const name = html.slice(start, i).toLowerCase(); + + while (WHITESPACE.test(html[i])) i += 1; + + if (html[i] === '=') { + i += 1; + while (WHITESPACE.test(html[i])) i += 1; + + let value; + + if (html[i] === "'" || html[i] === '"') { + const quote = html[i++]; + + const start = i; + let escaped = false; + + while (i < html.length) { + if (escaped) { + escaped = false; + } else { + const char = html[i]; + + if (html[i] === quote) { + break; + } + + if (char === '\\') { + escaped = true; + } + } + + i += 1; + } + + value = html.slice(start, i); + } else { + const start = i; + while (html[i] !== '>' && !WHITESPACE.test(html[i])) i += 1; + value = html.slice(start, i); + + i -= 1; + } + + value = decode(value); + attributes[name] = value; + } else { + i -= 1; + } + } + + i += 1; + } + + const { href, id, name, property, rel, src, srcset, content } = attributes; + + if (href) { + if (tag === 'BASE') { + base = resolve(base, href); + } else if (!rel || !/\bexternal\b/i.test(rel)) { + hrefs.push(resolve(base, href)); + } + } + + if (id) { + ids.push(id); + } + + if (name && tag === 'A') { + ids.push(name); + } + + if (src) { + hrefs.push(resolve(base, src)); + } + + if (srcset) { + let value = srcset; + const candidates = []; + let insideURL = true; + value = value.trim(); + for (let i = 0; i < value.length; i++) { + if (value[i] === ',' && (!insideURL || (insideURL && WHITESPACE.test(value[i + 1])))) { + candidates.push(value.slice(0, i)); + value = value.substring(i + 1).trim(); + i = 0; + insideURL = true; + } else if (WHITESPACE.test(value[i])) { + insideURL = false; + } + } + candidates.push(value); + for (const candidate of candidates) { + const src = candidate.split(WHITESPACE)[0]; + if (src) hrefs.push(resolve(base, src)); + } + } + + if (tag === 'META' && content) { + const attr = name ?? property; + + if (attr && CRAWLABLE_META_NAME_ATTRS.has(attr)) { + hrefs.push(resolve(base, content)); + } + } + } + } + + i += 1; + } + + return { ids, hrefs }; +} diff --git a/node_modules/@sveltejs/kit/src/core/postbuild/entities.js b/node_modules/@sveltejs/kit/src/core/postbuild/entities.js new file mode 100644 index 0000000..91888a9 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/postbuild/entities.js @@ -0,0 +1,2252 @@ +/** + * A list of all named HTML entities, from https://html.spec.whatwg.org/multipage/named-characters.html + * @type {Record} + */ +const entities = { + AElig: 'Æ', + 'AElig;': 'Æ', + AMP: '&', + 'AMP;': '&', + Aacute: 'Á', + 'Aacute;': 'Á', + 'Abreve;': 'Ă', + Acirc: 'Â', + 'Acirc;': 'Â', + 'Acy;': 'А', + 'Afr;': '𝔄', + Agrave: 'À', + 'Agrave;': 'À', + 'Alpha;': 'Α', + 'Amacr;': 'Ā', + 'And;': '⩓', + 'Aogon;': 'Ą', + 'Aopf;': '𝔸', + 'ApplyFunction;': '⁡', + Aring: 'Å', + 'Aring;': 'Å', + 'Ascr;': '𝒜', + 'Assign;': '≔', + Atilde: 'Ã', + 'Atilde;': 'Ã', + Auml: 'Ä', + 'Auml;': 'Ä', + 'Backslash;': '∖', + 'Barv;': '⫧', + 'Barwed;': '⌆', + 'Bcy;': 'Б', + 'Because;': '∵', + 'Bernoullis;': 'ℬ', + 'Beta;': 'Β', + 'Bfr;': '𝔅', + 'Bopf;': '𝔹', + 'Breve;': '˘', + 'Bscr;': 'ℬ', + 'Bumpeq;': '≎', + 'CHcy;': 'Ч', + COPY: '©', + 'COPY;': '©', + 'Cacute;': 'Ć', + 'Cap;': '⋒', + 'CapitalDifferentialD;': 'ⅅ', + 'Cayleys;': 'ℭ', + 'Ccaron;': 'Č', + Ccedil: 'Ç', + 'Ccedil;': 'Ç', + 'Ccirc;': 'Ĉ', + 'Cconint;': '∰', + 'Cdot;': 'Ċ', + 'Cedilla;': '¸', + 'CenterDot;': '·', + 'Cfr;': 'ℭ', + 'Chi;': 'Χ', + 'CircleDot;': '⊙', + 'CircleMinus;': '⊖', + 'CirclePlus;': '⊕', + 'CircleTimes;': '⊗', + 'ClockwiseContourIntegral;': '∲', + 'CloseCurlyDoubleQuote;': '”', + 'CloseCurlyQuote;': '’', + 'Colon;': '∷', + 'Colone;': '⩴', + 'Congruent;': '≡', + 'Conint;': '∯', + 'ContourIntegral;': '∮', + 'Copf;': 'ℂ', + 'Coproduct;': '∐', + 'CounterClockwiseContourIntegral;': '∳', + 'Cross;': '⨯', + 'Cscr;': '𝒞', + 'Cup;': '⋓', + 'CupCap;': '≍', + 'DD;': 'ⅅ', + 'DDotrahd;': '⤑', + 'DJcy;': 'Ђ', + 'DScy;': 'Ѕ', + 'DZcy;': 'Џ', + 'Dagger;': '‡', + 'Darr;': '↡', + 'Dashv;': '⫤', + 'Dcaron;': 'Ď', + 'Dcy;': 'Д', + 'Del;': '∇', + 'Delta;': 'Δ', + 'Dfr;': '𝔇', + 'DiacriticalAcute;': '´', + 'DiacriticalDot;': '˙', + 'DiacriticalDoubleAcute;': '˝', + 'DiacriticalGrave;': '`', + 'DiacriticalTilde;': '˜', + 'Diamond;': '⋄', + 'DifferentialD;': 'ⅆ', + 'Dopf;': '𝔻', + 'Dot;': '¨', + 'DotDot;': '⃜', + 'DotEqual;': '≐', + 'DoubleContourIntegral;': '∯', + 'DoubleDot;': '¨', + 'DoubleDownArrow;': '⇓', + 'DoubleLeftArrow;': '⇐', + 'DoubleLeftRightArrow;': '⇔', + 'DoubleLeftTee;': '⫤', + 'DoubleLongLeftArrow;': '⟸', + 'DoubleLongLeftRightArrow;': '⟺', + 'DoubleLongRightArrow;': '⟹', + 'DoubleRightArrow;': '⇒', + 'DoubleRightTee;': '⊨', + 'DoubleUpArrow;': '⇑', + 'DoubleUpDownArrow;': '⇕', + 'DoubleVerticalBar;': '∥', + 'DownArrow;': '↓', + 'DownArrowBar;': '⤓', + 'DownArrowUpArrow;': '⇵', + 'DownBreve;': '̑', + 'DownLeftRightVector;': '⥐', + 'DownLeftTeeVector;': '⥞', + 'DownLeftVector;': '↽', + 'DownLeftVectorBar;': '⥖', + 'DownRightTeeVector;': '⥟', + 'DownRightVector;': '⇁', + 'DownRightVectorBar;': '⥗', + 'DownTee;': '⊤', + 'DownTeeArrow;': '↧', + 'Downarrow;': '⇓', + 'Dscr;': '𝒟', + 'Dstrok;': 'Đ', + 'ENG;': 'Ŋ', + ETH: 'Ð', + 'ETH;': 'Ð', + Eacute: 'É', + 'Eacute;': 'É', + 'Ecaron;': 'Ě', + Ecirc: 'Ê', + 'Ecirc;': 'Ê', + 'Ecy;': 'Э', + 'Edot;': 'Ė', + 'Efr;': '𝔈', + Egrave: 'È', + 'Egrave;': 'È', + 'Element;': '∈', + 'Emacr;': 'Ē', + 'EmptySmallSquare;': '◻', + 'EmptyVerySmallSquare;': '▫', + 'Eogon;': 'Ę', + 'Eopf;': '𝔼', + 'Epsilon;': 'Ε', + 'Equal;': '⩵', + 'EqualTilde;': '≂', + 'Equilibrium;': '⇌', + 'Escr;': 'ℰ', + 'Esim;': '⩳', + 'Eta;': 'Η', + Euml: 'Ë', + 'Euml;': 'Ë', + 'Exists;': '∃', + 'ExponentialE;': 'ⅇ', + 'Fcy;': 'Ф', + 'Ffr;': '𝔉', + 'FilledSmallSquare;': '◼', + 'FilledVerySmallSquare;': '▪', + 'Fopf;': '𝔽', + 'ForAll;': '∀', + 'Fouriertrf;': 'ℱ', + 'Fscr;': 'ℱ', + 'GJcy;': 'Ѓ', + GT: '>', + 'GT;': '>', + 'Gamma;': 'Γ', + 'Gammad;': 'Ϝ', + 'Gbreve;': 'Ğ', + 'Gcedil;': 'Ģ', + 'Gcirc;': 'Ĝ', + 'Gcy;': 'Г', + 'Gdot;': 'Ġ', + 'Gfr;': '𝔊', + 'Gg;': '⋙', + 'Gopf;': '𝔾', + 'GreaterEqual;': '≥', + 'GreaterEqualLess;': '⋛', + 'GreaterFullEqual;': '≧', + 'GreaterGreater;': '⪢', + 'GreaterLess;': '≷', + 'GreaterSlantEqual;': '⩾', + 'GreaterTilde;': '≳', + 'Gscr;': '𝒢', + 'Gt;': '≫', + 'HARDcy;': 'Ъ', + 'Hacek;': 'ˇ', + 'Hat;': '^', + 'Hcirc;': 'Ĥ', + 'Hfr;': 'ℌ', + 'HilbertSpace;': 'ℋ', + 'Hopf;': 'ℍ', + 'HorizontalLine;': '─', + 'Hscr;': 'ℋ', + 'Hstrok;': 'Ħ', + 'HumpDownHump;': '≎', + 'HumpEqual;': '≏', + 'IEcy;': 'Е', + 'IJlig;': 'IJ', + 'IOcy;': 'Ё', + Iacute: 'Í', + 'Iacute;': 'Í', + Icirc: 'Î', + 'Icirc;': 'Î', + 'Icy;': 'И', + 'Idot;': 'İ', + 'Ifr;': 'ℑ', + Igrave: 'Ì', + 'Igrave;': 'Ì', + 'Im;': 'ℑ', + 'Imacr;': 'Ī', + 'ImaginaryI;': 'ⅈ', + 'Implies;': '⇒', + 'Int;': '∬', + 'Integral;': '∫', + 'Intersection;': '⋂', + 'InvisibleComma;': '⁣', + 'InvisibleTimes;': '⁢', + 'Iogon;': 'Į', + 'Iopf;': '𝕀', + 'Iota;': 'Ι', + 'Iscr;': 'ℐ', + 'Itilde;': 'Ĩ', + 'Iukcy;': 'І', + Iuml: 'Ï', + 'Iuml;': 'Ï', + 'Jcirc;': 'Ĵ', + 'Jcy;': 'Й', + 'Jfr;': '𝔍', + 'Jopf;': '𝕁', + 'Jscr;': '𝒥', + 'Jsercy;': 'Ј', + 'Jukcy;': 'Є', + 'KHcy;': 'Х', + 'KJcy;': 'Ќ', + 'Kappa;': 'Κ', + 'Kcedil;': 'Ķ', + 'Kcy;': 'К', + 'Kfr;': '𝔎', + 'Kopf;': '𝕂', + 'Kscr;': '𝒦', + 'LJcy;': 'Љ', + LT: '<', + 'LT;': '<', + 'Lacute;': 'Ĺ', + 'Lambda;': 'Λ', + 'Lang;': '⟪', + 'Laplacetrf;': 'ℒ', + 'Larr;': '↞', + 'Lcaron;': 'Ľ', + 'Lcedil;': 'Ļ', + 'Lcy;': 'Л', + 'LeftAngleBracket;': '⟨', + 'LeftArrow;': '←', + 'LeftArrowBar;': '⇤', + 'LeftArrowRightArrow;': '⇆', + 'LeftCeiling;': '⌈', + 'LeftDoubleBracket;': '⟦', + 'LeftDownTeeVector;': '⥡', + 'LeftDownVector;': '⇃', + 'LeftDownVectorBar;': '⥙', + 'LeftFloor;': '⌊', + 'LeftRightArrow;': '↔', + 'LeftRightVector;': '⥎', + 'LeftTee;': '⊣', + 'LeftTeeArrow;': '↤', + 'LeftTeeVector;': '⥚', + 'LeftTriangle;': '⊲', + 'LeftTriangleBar;': '⧏', + 'LeftTriangleEqual;': '⊴', + 'LeftUpDownVector;': '⥑', + 'LeftUpTeeVector;': '⥠', + 'LeftUpVector;': '↿', + 'LeftUpVectorBar;': '⥘', + 'LeftVector;': '↼', + 'LeftVectorBar;': '⥒', + 'Leftarrow;': '⇐', + 'Leftrightarrow;': '⇔', + 'LessEqualGreater;': '⋚', + 'LessFullEqual;': '≦', + 'LessGreater;': '≶', + 'LessLess;': '⪡', + 'LessSlantEqual;': '⩽', + 'LessTilde;': '≲', + 'Lfr;': '𝔏', + 'Ll;': '⋘', + 'Lleftarrow;': '⇚', + 'Lmidot;': 'Ŀ', + 'LongLeftArrow;': '⟵', + 'LongLeftRightArrow;': '⟷', + 'LongRightArrow;': '⟶', + 'Longleftarrow;': '⟸', + 'Longleftrightarrow;': '⟺', + 'Longrightarrow;': '⟹', + 'Lopf;': '𝕃', + 'LowerLeftArrow;': '↙', + 'LowerRightArrow;': '↘', + 'Lscr;': 'ℒ', + 'Lsh;': '↰', + 'Lstrok;': 'Ł', + 'Lt;': '≪', + 'Map;': '⤅', + 'Mcy;': 'М', + 'MediumSpace;': ' ', + 'Mellintrf;': 'ℳ', + 'Mfr;': '𝔐', + 'MinusPlus;': '∓', + 'Mopf;': '𝕄', + 'Mscr;': 'ℳ', + 'Mu;': 'Μ', + 'NJcy;': 'Њ', + 'Nacute;': 'Ń', + 'Ncaron;': 'Ň', + 'Ncedil;': 'Ņ', + 'Ncy;': 'Н', + 'NegativeMediumSpace;': '​', + 'NegativeThickSpace;': '​', + 'NegativeThinSpace;': '​', + 'NegativeVeryThinSpace;': '​', + 'NestedGreaterGreater;': '≫', + 'NestedLessLess;': '≪', + 'NewLine;': '\n', + 'Nfr;': '𝔑', + 'NoBreak;': '⁠', + 'NonBreakingSpace;': ' ', + 'Nopf;': 'ℕ', + 'Not;': '⫬', + 'NotCongruent;': '≢', + 'NotCupCap;': '≭', + 'NotDoubleVerticalBar;': '∦', + 'NotElement;': '∉', + 'NotEqual;': '≠', + 'NotEqualTilde;': '≂̸', + 'NotExists;': '∄', + 'NotGreater;': '≯', + 'NotGreaterEqual;': '≱', + 'NotGreaterFullEqual;': '≧̸', + 'NotGreaterGreater;': '≫̸', + 'NotGreaterLess;': '≹', + 'NotGreaterSlantEqual;': '⩾̸', + 'NotGreaterTilde;': '≵', + 'NotHumpDownHump;': '≎̸', + 'NotHumpEqual;': '≏̸', + 'NotLeftTriangle;': '⋪', + 'NotLeftTriangleBar;': '⧏̸', + 'NotLeftTriangleEqual;': '⋬', + 'NotLess;': '≮', + 'NotLessEqual;': '≰', + 'NotLessGreater;': '≸', + 'NotLessLess;': '≪̸', + 'NotLessSlantEqual;': '⩽̸', + 'NotLessTilde;': '≴', + 'NotNestedGreaterGreater;': '⪢̸', + 'NotNestedLessLess;': '⪡̸', + 'NotPrecedes;': '⊀', + 'NotPrecedesEqual;': '⪯̸', + 'NotPrecedesSlantEqual;': '⋠', + 'NotReverseElement;': '∌', + 'NotRightTriangle;': '⋫', + 'NotRightTriangleBar;': '⧐̸', + 'NotRightTriangleEqual;': '⋭', + 'NotSquareSubset;': '⊏̸', + 'NotSquareSubsetEqual;': '⋢', + 'NotSquareSuperset;': '⊐̸', + 'NotSquareSupersetEqual;': '⋣', + 'NotSubset;': '⊂⃒', + 'NotSubsetEqual;': '⊈', + 'NotSucceeds;': '⊁', + 'NotSucceedsEqual;': '⪰̸', + 'NotSucceedsSlantEqual;': '⋡', + 'NotSucceedsTilde;': '≿̸', + 'NotSuperset;': '⊃⃒', + 'NotSupersetEqual;': '⊉', + 'NotTilde;': '≁', + 'NotTildeEqual;': '≄', + 'NotTildeFullEqual;': '≇', + 'NotTildeTilde;': '≉', + 'NotVerticalBar;': '∤', + 'Nscr;': '𝒩', + Ntilde: 'Ñ', + 'Ntilde;': 'Ñ', + 'Nu;': 'Ν', + 'OElig;': 'Œ', + Oacute: 'Ó', + 'Oacute;': 'Ó', + Ocirc: 'Ô', + 'Ocirc;': 'Ô', + 'Ocy;': 'О', + 'Odblac;': 'Ő', + 'Ofr;': '𝔒', + Ograve: 'Ò', + 'Ograve;': 'Ò', + 'Omacr;': 'Ō', + 'Omega;': 'Ω', + 'Omicron;': 'Ο', + 'Oopf;': '𝕆', + 'OpenCurlyDoubleQuote;': '“', + 'OpenCurlyQuote;': '‘', + 'Or;': '⩔', + 'Oscr;': '𝒪', + Oslash: 'Ø', + 'Oslash;': 'Ø', + Otilde: 'Õ', + 'Otilde;': 'Õ', + 'Otimes;': '⨷', + Ouml: 'Ö', + 'Ouml;': 'Ö', + 'OverBar;': '‾', + 'OverBrace;': '⏞', + 'OverBracket;': '⎴', + 'OverParenthesis;': '⏜', + 'PartialD;': '∂', + 'Pcy;': 'П', + 'Pfr;': '𝔓', + 'Phi;': 'Φ', + 'Pi;': 'Π', + 'PlusMinus;': '±', + 'Poincareplane;': 'ℌ', + 'Popf;': 'ℙ', + 'Pr;': '⪻', + 'Precedes;': '≺', + 'PrecedesEqual;': '⪯', + 'PrecedesSlantEqual;': '≼', + 'PrecedesTilde;': '≾', + 'Prime;': '″', + 'Product;': '∏', + 'Proportion;': '∷', + 'Proportional;': '∝', + 'Pscr;': '𝒫', + 'Psi;': 'Ψ', + QUOT: '"', + 'QUOT;': '"', + 'Qfr;': '𝔔', + 'Qopf;': 'ℚ', + 'Qscr;': '𝒬', + 'RBarr;': '⤐', + REG: '®', + 'REG;': '®', + 'Racute;': 'Ŕ', + 'Rang;': '⟫', + 'Rarr;': '↠', + 'Rarrtl;': '⤖', + 'Rcaron;': 'Ř', + 'Rcedil;': 'Ŗ', + 'Rcy;': 'Р', + 'Re;': 'ℜ', + 'ReverseElement;': '∋', + 'ReverseEquilibrium;': '⇋', + 'ReverseUpEquilibrium;': '⥯', + 'Rfr;': 'ℜ', + 'Rho;': 'Ρ', + 'RightAngleBracket;': '⟩', + 'RightArrow;': '→', + 'RightArrowBar;': '⇥', + 'RightArrowLeftArrow;': '⇄', + 'RightCeiling;': '⌉', + 'RightDoubleBracket;': '⟧', + 'RightDownTeeVector;': '⥝', + 'RightDownVector;': '⇂', + 'RightDownVectorBar;': '⥕', + 'RightFloor;': '⌋', + 'RightTee;': '⊢', + 'RightTeeArrow;': '↦', + 'RightTeeVector;': '⥛', + 'RightTriangle;': '⊳', + 'RightTriangleBar;': '⧐', + 'RightTriangleEqual;': '⊵', + 'RightUpDownVector;': '⥏', + 'RightUpTeeVector;': '⥜', + 'RightUpVector;': '↾', + 'RightUpVectorBar;': '⥔', + 'RightVector;': '⇀', + 'RightVectorBar;': '⥓', + 'Rightarrow;': '⇒', + 'Ropf;': 'ℝ', + 'RoundImplies;': '⥰', + 'Rrightarrow;': '⇛', + 'Rscr;': 'ℛ', + 'Rsh;': '↱', + 'RuleDelayed;': '⧴', + 'SHCHcy;': 'Щ', + 'SHcy;': 'Ш', + 'SOFTcy;': 'Ь', + 'Sacute;': 'Ś', + 'Sc;': '⪼', + 'Scaron;': 'Š', + 'Scedil;': 'Ş', + 'Scirc;': 'Ŝ', + 'Scy;': 'С', + 'Sfr;': '𝔖', + 'ShortDownArrow;': '↓', + 'ShortLeftArrow;': '←', + 'ShortRightArrow;': '→', + 'ShortUpArrow;': '↑', + 'Sigma;': 'Σ', + 'SmallCircle;': '∘', + 'Sopf;': '𝕊', + 'Sqrt;': '√', + 'Square;': '□', + 'SquareIntersection;': '⊓', + 'SquareSubset;': '⊏', + 'SquareSubsetEqual;': '⊑', + 'SquareSuperset;': '⊐', + 'SquareSupersetEqual;': '⊒', + 'SquareUnion;': '⊔', + 'Sscr;': '𝒮', + 'Star;': '⋆', + 'Sub;': '⋐', + 'Subset;': '⋐', + 'SubsetEqual;': '⊆', + 'Succeeds;': '≻', + 'SucceedsEqual;': '⪰', + 'SucceedsSlantEqual;': '≽', + 'SucceedsTilde;': '≿', + 'SuchThat;': '∋', + 'Sum;': '∑', + 'Sup;': '⋑', + 'Superset;': '⊃', + 'SupersetEqual;': '⊇', + 'Supset;': '⋑', + THORN: 'Þ', + 'THORN;': 'Þ', + 'TRADE;': '™', + 'TSHcy;': 'Ћ', + 'TScy;': 'Ц', + 'Tab;': '\t', + 'Tau;': 'Τ', + 'Tcaron;': 'Ť', + 'Tcedil;': 'Ţ', + 'Tcy;': 'Т', + 'Tfr;': '𝔗', + 'Therefore;': '∴', + 'Theta;': 'Θ', + 'ThickSpace;': '  ', + 'ThinSpace;': ' ', + 'Tilde;': '∼', + 'TildeEqual;': '≃', + 'TildeFullEqual;': '≅', + 'TildeTilde;': '≈', + 'Topf;': '𝕋', + 'TripleDot;': '⃛', + 'Tscr;': '𝒯', + 'Tstrok;': 'Ŧ', + Uacute: 'Ú', + 'Uacute;': 'Ú', + 'Uarr;': '↟', + 'Uarrocir;': '⥉', + 'Ubrcy;': 'Ў', + 'Ubreve;': 'Ŭ', + Ucirc: 'Û', + 'Ucirc;': 'Û', + 'Ucy;': 'У', + 'Udblac;': 'Ű', + 'Ufr;': '𝔘', + Ugrave: 'Ù', + 'Ugrave;': 'Ù', + 'Umacr;': 'Ū', + 'UnderBar;': '_', + 'UnderBrace;': '⏟', + 'UnderBracket;': '⎵', + 'UnderParenthesis;': '⏝', + 'Union;': '⋃', + 'UnionPlus;': '⊎', + 'Uogon;': 'Ų', + 'Uopf;': '𝕌', + 'UpArrow;': '↑', + 'UpArrowBar;': '⤒', + 'UpArrowDownArrow;': '⇅', + 'UpDownArrow;': '↕', + 'UpEquilibrium;': '⥮', + 'UpTee;': '⊥', + 'UpTeeArrow;': '↥', + 'Uparrow;': '⇑', + 'Updownarrow;': '⇕', + 'UpperLeftArrow;': '↖', + 'UpperRightArrow;': '↗', + 'Upsi;': 'ϒ', + 'Upsilon;': 'Υ', + 'Uring;': 'Ů', + 'Uscr;': '𝒰', + 'Utilde;': 'Ũ', + Uuml: 'Ü', + 'Uuml;': 'Ü', + 'VDash;': '⊫', + 'Vbar;': '⫫', + 'Vcy;': 'В', + 'Vdash;': '⊩', + 'Vdashl;': '⫦', + 'Vee;': '⋁', + 'Verbar;': '‖', + 'Vert;': '‖', + 'VerticalBar;': '∣', + 'VerticalLine;': '|', + 'VerticalSeparator;': '❘', + 'VerticalTilde;': '≀', + 'VeryThinSpace;': ' ', + 'Vfr;': '𝔙', + 'Vopf;': '𝕍', + 'Vscr;': '𝒱', + 'Vvdash;': '⊪', + 'Wcirc;': 'Ŵ', + 'Wedge;': '⋀', + 'Wfr;': '𝔚', + 'Wopf;': '𝕎', + 'Wscr;': '𝒲', + 'Xfr;': '𝔛', + 'Xi;': 'Ξ', + 'Xopf;': '𝕏', + 'Xscr;': '𝒳', + 'YAcy;': 'Я', + 'YIcy;': 'Ї', + 'YUcy;': 'Ю', + Yacute: 'Ý', + 'Yacute;': 'Ý', + 'Ycirc;': 'Ŷ', + 'Ycy;': 'Ы', + 'Yfr;': '𝔜', + 'Yopf;': '𝕐', + 'Yscr;': '𝒴', + 'Yuml;': 'Ÿ', + 'ZHcy;': 'Ж', + 'Zacute;': 'Ź', + 'Zcaron;': 'Ž', + 'Zcy;': 'З', + 'Zdot;': 'Ż', + 'ZeroWidthSpace;': '​', + 'Zeta;': 'Ζ', + 'Zfr;': 'ℨ', + 'Zopf;': 'ℤ', + 'Zscr;': '𝒵', + aacute: 'á', + 'aacute;': 'á', + 'abreve;': 'ă', + 'ac;': '∾', + 'acE;': '∾̳', + 'acd;': '∿', + acirc: 'â', + 'acirc;': 'â', + acute: '´', + 'acute;': '´', + 'acy;': 'а', + aelig: 'æ', + 'aelig;': 'æ', + 'af;': '⁡', + 'afr;': '𝔞', + agrave: 'à', + 'agrave;': 'à', + 'alefsym;': 'ℵ', + 'aleph;': 'ℵ', + 'alpha;': 'α', + 'amacr;': 'ā', + 'amalg;': '⨿', + amp: '&', + 'amp;': '&', + 'and;': '∧', + 'andand;': '⩕', + 'andd;': '⩜', + 'andslope;': '⩘', + 'andv;': '⩚', + 'ang;': '∠', + 'ange;': '⦤', + 'angle;': '∠', + 'angmsd;': '∡', + 'angmsdaa;': '⦨', + 'angmsdab;': '⦩', + 'angmsdac;': '⦪', + 'angmsdad;': '⦫', + 'angmsdae;': '⦬', + 'angmsdaf;': '⦭', + 'angmsdag;': '⦮', + 'angmsdah;': '⦯', + 'angrt;': '∟', + 'angrtvb;': '⊾', + 'angrtvbd;': '⦝', + 'angsph;': '∢', + 'angst;': 'Å', + 'angzarr;': '⍼', + 'aogon;': 'ą', + 'aopf;': '𝕒', + 'ap;': '≈', + 'apE;': '⩰', + 'apacir;': '⩯', + 'ape;': '≊', + 'apid;': '≋', + 'apos;': "'", + 'approx;': '≈', + 'approxeq;': '≊', + aring: 'å', + 'aring;': 'å', + 'ascr;': '𝒶', + 'ast;': '*', + 'asymp;': '≈', + 'asympeq;': '≍', + atilde: 'ã', + 'atilde;': 'ã', + auml: 'ä', + 'auml;': 'ä', + 'awconint;': '∳', + 'awint;': '⨑', + 'bNot;': '⫭', + 'backcong;': '≌', + 'backepsilon;': '϶', + 'backprime;': '‵', + 'backsim;': '∽', + 'backsimeq;': '⋍', + 'barvee;': '⊽', + 'barwed;': '⌅', + 'barwedge;': '⌅', + 'bbrk;': '⎵', + 'bbrktbrk;': '⎶', + 'bcong;': '≌', + 'bcy;': 'б', + 'bdquo;': '„', + 'becaus;': '∵', + 'because;': '∵', + 'bemptyv;': '⦰', + 'bepsi;': '϶', + 'bernou;': 'ℬ', + 'beta;': 'β', + 'beth;': 'ℶ', + 'between;': '≬', + 'bfr;': '𝔟', + 'bigcap;': '⋂', + 'bigcirc;': '◯', + 'bigcup;': '⋃', + 'bigodot;': '⨀', + 'bigoplus;': '⨁', + 'bigotimes;': '⨂', + 'bigsqcup;': '⨆', + 'bigstar;': '★', + 'bigtriangledown;': '▽', + 'bigtriangleup;': '△', + 'biguplus;': '⨄', + 'bigvee;': '⋁', + 'bigwedge;': '⋀', + 'bkarow;': '⤍', + 'blacklozenge;': '⧫', + 'blacksquare;': '▪', + 'blacktriangle;': '▴', + 'blacktriangledown;': '▾', + 'blacktriangleleft;': '◂', + 'blacktriangleright;': '▸', + 'blank;': '␣', + 'blk12;': '▒', + 'blk14;': '░', + 'blk34;': '▓', + 'block;': '█', + 'bne;': '=⃥', + 'bnequiv;': '≡⃥', + 'bnot;': '⌐', + 'bopf;': '𝕓', + 'bot;': '⊥', + 'bottom;': '⊥', + 'bowtie;': '⋈', + 'boxDL;': '╗', + 'boxDR;': '╔', + 'boxDl;': '╖', + 'boxDr;': '╓', + 'boxH;': '═', + 'boxHD;': '╦', + 'boxHU;': '╩', + 'boxHd;': '╤', + 'boxHu;': '╧', + 'boxUL;': '╝', + 'boxUR;': '╚', + 'boxUl;': '╜', + 'boxUr;': '╙', + 'boxV;': '║', + 'boxVH;': '╬', + 'boxVL;': '╣', + 'boxVR;': '╠', + 'boxVh;': '╫', + 'boxVl;': '╢', + 'boxVr;': '╟', + 'boxbox;': '⧉', + 'boxdL;': '╕', + 'boxdR;': '╒', + 'boxdl;': '┐', + 'boxdr;': '┌', + 'boxh;': '─', + 'boxhD;': '╥', + 'boxhU;': '╨', + 'boxhd;': '┬', + 'boxhu;': '┴', + 'boxminus;': '⊟', + 'boxplus;': '⊞', + 'boxtimes;': '⊠', + 'boxuL;': '╛', + 'boxuR;': '╘', + 'boxul;': '┘', + 'boxur;': '└', + 'boxv;': '│', + 'boxvH;': '╪', + 'boxvL;': '╡', + 'boxvR;': '╞', + 'boxvh;': '┼', + 'boxvl;': '┤', + 'boxvr;': '├', + 'bprime;': '‵', + 'breve;': '˘', + brvbar: '¦', + 'brvbar;': '¦', + 'bscr;': '𝒷', + 'bsemi;': '⁏', + 'bsim;': '∽', + 'bsime;': '⋍', + 'bsol;': '\\', + 'bsolb;': '⧅', + 'bsolhsub;': '⟈', + 'bull;': '•', + 'bullet;': '•', + 'bump;': '≎', + 'bumpE;': '⪮', + 'bumpe;': '≏', + 'bumpeq;': '≏', + 'cacute;': 'ć', + 'cap;': '∩', + 'capand;': '⩄', + 'capbrcup;': '⩉', + 'capcap;': '⩋', + 'capcup;': '⩇', + 'capdot;': '⩀', + 'caps;': '∩︀', + 'caret;': '⁁', + 'caron;': 'ˇ', + 'ccaps;': '⩍', + 'ccaron;': 'č', + ccedil: 'ç', + 'ccedil;': 'ç', + 'ccirc;': 'ĉ', + 'ccups;': '⩌', + 'ccupssm;': '⩐', + 'cdot;': 'ċ', + cedil: '¸', + 'cedil;': '¸', + 'cemptyv;': '⦲', + cent: '¢', + 'cent;': '¢', + 'centerdot;': '·', + 'cfr;': '𝔠', + 'chcy;': 'ч', + 'check;': '✓', + 'checkmark;': '✓', + 'chi;': 'χ', + 'cir;': '○', + 'cirE;': '⧃', + 'circ;': 'ˆ', + 'circeq;': '≗', + 'circlearrowleft;': '↺', + 'circlearrowright;': '↻', + 'circledR;': '®', + 'circledS;': 'Ⓢ', + 'circledast;': '⊛', + 'circledcirc;': '⊚', + 'circleddash;': '⊝', + 'cire;': '≗', + 'cirfnint;': '⨐', + 'cirmid;': '⫯', + 'cirscir;': '⧂', + 'clubs;': '♣', + 'clubsuit;': '♣', + 'colon;': ':', + 'colone;': '≔', + 'coloneq;': '≔', + 'comma;': ',', + 'commat;': '@', + 'comp;': '∁', + 'compfn;': '∘', + 'complement;': '∁', + 'complexes;': 'ℂ', + 'cong;': '≅', + 'congdot;': '⩭', + 'conint;': '∮', + 'copf;': '𝕔', + 'coprod;': '∐', + copy: '©', + 'copy;': '©', + 'copysr;': '℗', + 'crarr;': '↵', + 'cross;': '✗', + 'cscr;': '𝒸', + 'csub;': '⫏', + 'csube;': '⫑', + 'csup;': '⫐', + 'csupe;': '⫒', + 'ctdot;': '⋯', + 'cudarrl;': '⤸', + 'cudarrr;': '⤵', + 'cuepr;': '⋞', + 'cuesc;': '⋟', + 'cularr;': '↶', + 'cularrp;': '⤽', + 'cup;': '∪', + 'cupbrcap;': '⩈', + 'cupcap;': '⩆', + 'cupcup;': '⩊', + 'cupdot;': '⊍', + 'cupor;': '⩅', + 'cups;': '∪︀', + 'curarr;': '↷', + 'curarrm;': '⤼', + 'curlyeqprec;': '⋞', + 'curlyeqsucc;': '⋟', + 'curlyvee;': '⋎', + 'curlywedge;': '⋏', + curren: '¤', + 'curren;': '¤', + 'curvearrowleft;': '↶', + 'curvearrowright;': '↷', + 'cuvee;': '⋎', + 'cuwed;': '⋏', + 'cwconint;': '∲', + 'cwint;': '∱', + 'cylcty;': '⌭', + 'dArr;': '⇓', + 'dHar;': '⥥', + 'dagger;': '†', + 'daleth;': 'ℸ', + 'darr;': '↓', + 'dash;': '‐', + 'dashv;': '⊣', + 'dbkarow;': '⤏', + 'dblac;': '˝', + 'dcaron;': 'ď', + 'dcy;': 'д', + 'dd;': 'ⅆ', + 'ddagger;': '‡', + 'ddarr;': '⇊', + 'ddotseq;': '⩷', + deg: '°', + 'deg;': '°', + 'delta;': 'δ', + 'demptyv;': '⦱', + 'dfisht;': '⥿', + 'dfr;': '𝔡', + 'dharl;': '⇃', + 'dharr;': '⇂', + 'diam;': '⋄', + 'diamond;': '⋄', + 'diamondsuit;': '♦', + 'diams;': '♦', + 'die;': '¨', + 'digamma;': 'ϝ', + 'disin;': '⋲', + 'div;': '÷', + divide: '÷', + 'divide;': '÷', + 'divideontimes;': '⋇', + 'divonx;': '⋇', + 'djcy;': 'ђ', + 'dlcorn;': '⌞', + 'dlcrop;': '⌍', + 'dollar;': '$', + 'dopf;': '𝕕', + 'dot;': '˙', + 'doteq;': '≐', + 'doteqdot;': '≑', + 'dotminus;': '∸', + 'dotplus;': '∔', + 'dotsquare;': '⊡', + 'doublebarwedge;': '⌆', + 'downarrow;': '↓', + 'downdownarrows;': '⇊', + 'downharpoonleft;': '⇃', + 'downharpoonright;': '⇂', + 'drbkarow;': '⤐', + 'drcorn;': '⌟', + 'drcrop;': '⌌', + 'dscr;': '𝒹', + 'dscy;': 'ѕ', + 'dsol;': '⧶', + 'dstrok;': 'đ', + 'dtdot;': '⋱', + 'dtri;': '▿', + 'dtrif;': '▾', + 'duarr;': '⇵', + 'duhar;': '⥯', + 'dwangle;': '⦦', + 'dzcy;': 'џ', + 'dzigrarr;': '⟿', + 'eDDot;': '⩷', + 'eDot;': '≑', + eacute: 'é', + 'eacute;': 'é', + 'easter;': '⩮', + 'ecaron;': 'ě', + 'ecir;': '≖', + ecirc: 'ê', + 'ecirc;': 'ê', + 'ecolon;': '≕', + 'ecy;': 'э', + 'edot;': 'ė', + 'ee;': 'ⅇ', + 'efDot;': '≒', + 'efr;': '𝔢', + 'eg;': '⪚', + egrave: 'è', + 'egrave;': 'è', + 'egs;': '⪖', + 'egsdot;': '⪘', + 'el;': '⪙', + 'elinters;': '⏧', + 'ell;': 'ℓ', + 'els;': '⪕', + 'elsdot;': '⪗', + 'emacr;': 'ē', + 'empty;': '∅', + 'emptyset;': '∅', + 'emptyv;': '∅', + 'emsp13;': ' ', + 'emsp14;': ' ', + 'emsp;': ' ', + 'eng;': 'ŋ', + 'ensp;': ' ', + 'eogon;': 'ę', + 'eopf;': '𝕖', + 'epar;': '⋕', + 'eparsl;': '⧣', + 'eplus;': '⩱', + 'epsi;': 'ε', + 'epsilon;': 'ε', + 'epsiv;': 'ϵ', + 'eqcirc;': '≖', + 'eqcolon;': '≕', + 'eqsim;': '≂', + 'eqslantgtr;': '⪖', + 'eqslantless;': '⪕', + 'equals;': '=', + 'equest;': '≟', + 'equiv;': '≡', + 'equivDD;': '⩸', + 'eqvparsl;': '⧥', + 'erDot;': '≓', + 'erarr;': '⥱', + 'escr;': 'ℯ', + 'esdot;': '≐', + 'esim;': '≂', + 'eta;': 'η', + eth: 'ð', + 'eth;': 'ð', + euml: 'ë', + 'euml;': 'ë', + 'euro;': '€', + 'excl;': '!', + 'exist;': '∃', + 'expectation;': 'ℰ', + 'exponentiale;': 'ⅇ', + 'fallingdotseq;': '≒', + 'fcy;': 'ф', + 'female;': '♀', + 'ffilig;': 'ffi', + 'fflig;': 'ff', + 'ffllig;': 'ffl', + 'ffr;': '𝔣', + 'filig;': 'fi', + 'fjlig;': 'fj', + 'flat;': '♭', + 'fllig;': 'fl', + 'fltns;': '▱', + 'fnof;': 'ƒ', + 'fopf;': '𝕗', + 'forall;': '∀', + 'fork;': '⋔', + 'forkv;': '⫙', + 'fpartint;': '⨍', + frac12: '½', + 'frac12;': '½', + 'frac13;': '⅓', + frac14: '¼', + 'frac14;': '¼', + 'frac15;': '⅕', + 'frac16;': '⅙', + 'frac18;': '⅛', + 'frac23;': '⅔', + 'frac25;': '⅖', + frac34: '¾', + 'frac34;': '¾', + 'frac35;': '⅗', + 'frac38;': '⅜', + 'frac45;': '⅘', + 'frac56;': '⅚', + 'frac58;': '⅝', + 'frac78;': '⅞', + 'frasl;': '⁄', + 'frown;': '⌢', + 'fscr;': '𝒻', + 'gE;': '≧', + 'gEl;': '⪌', + 'gacute;': 'ǵ', + 'gamma;': 'γ', + 'gammad;': 'ϝ', + 'gap;': '⪆', + 'gbreve;': 'ğ', + 'gcirc;': 'ĝ', + 'gcy;': 'г', + 'gdot;': 'ġ', + 'ge;': '≥', + 'gel;': '⋛', + 'geq;': '≥', + 'geqq;': '≧', + 'geqslant;': '⩾', + 'ges;': '⩾', + 'gescc;': '⪩', + 'gesdot;': '⪀', + 'gesdoto;': '⪂', + 'gesdotol;': '⪄', + 'gesl;': '⋛︀', + 'gesles;': '⪔', + 'gfr;': '𝔤', + 'gg;': '≫', + 'ggg;': '⋙', + 'gimel;': 'ℷ', + 'gjcy;': 'ѓ', + 'gl;': '≷', + 'glE;': '⪒', + 'gla;': '⪥', + 'glj;': '⪤', + 'gnE;': '≩', + 'gnap;': '⪊', + 'gnapprox;': '⪊', + 'gne;': '⪈', + 'gneq;': '⪈', + 'gneqq;': '≩', + 'gnsim;': '⋧', + 'gopf;': '𝕘', + 'grave;': '`', + 'gscr;': 'ℊ', + 'gsim;': '≳', + 'gsime;': '⪎', + 'gsiml;': '⪐', + gt: '>', + 'gt;': '>', + 'gtcc;': '⪧', + 'gtcir;': '⩺', + 'gtdot;': '⋗', + 'gtlPar;': '⦕', + 'gtquest;': '⩼', + 'gtrapprox;': '⪆', + 'gtrarr;': '⥸', + 'gtrdot;': '⋗', + 'gtreqless;': '⋛', + 'gtreqqless;': '⪌', + 'gtrless;': '≷', + 'gtrsim;': '≳', + 'gvertneqq;': '≩︀', + 'gvnE;': '≩︀', + 'hArr;': '⇔', + 'hairsp;': ' ', + 'half;': '½', + 'hamilt;': 'ℋ', + 'hardcy;': 'ъ', + 'harr;': '↔', + 'harrcir;': '⥈', + 'harrw;': '↭', + 'hbar;': 'ℏ', + 'hcirc;': 'ĥ', + 'hearts;': '♥', + 'heartsuit;': '♥', + 'hellip;': '…', + 'hercon;': '⊹', + 'hfr;': '𝔥', + 'hksearow;': '⤥', + 'hkswarow;': '⤦', + 'hoarr;': '⇿', + 'homtht;': '∻', + 'hookleftarrow;': '↩', + 'hookrightarrow;': '↪', + 'hopf;': '𝕙', + 'horbar;': '―', + 'hscr;': '𝒽', + 'hslash;': 'ℏ', + 'hstrok;': 'ħ', + 'hybull;': '⁃', + 'hyphen;': '‐', + iacute: 'í', + 'iacute;': 'í', + 'ic;': '⁣', + icirc: 'î', + 'icirc;': 'î', + 'icy;': 'и', + 'iecy;': 'е', + iexcl: '¡', + 'iexcl;': '¡', + 'iff;': '⇔', + 'ifr;': '𝔦', + igrave: 'ì', + 'igrave;': 'ì', + 'ii;': 'ⅈ', + 'iiiint;': '⨌', + 'iiint;': '∭', + 'iinfin;': '⧜', + 'iiota;': '℩', + 'ijlig;': 'ij', + 'imacr;': 'ī', + 'image;': 'ℑ', + 'imagline;': 'ℐ', + 'imagpart;': 'ℑ', + 'imath;': 'ı', + 'imof;': '⊷', + 'imped;': 'Ƶ', + 'in;': '∈', + 'incare;': '℅', + 'infin;': '∞', + 'infintie;': '⧝', + 'inodot;': 'ı', + 'int;': '∫', + 'intcal;': '⊺', + 'integers;': 'ℤ', + 'intercal;': '⊺', + 'intlarhk;': '⨗', + 'intprod;': '⨼', + 'iocy;': 'ё', + 'iogon;': 'į', + 'iopf;': '𝕚', + 'iota;': 'ι', + 'iprod;': '⨼', + iquest: '¿', + 'iquest;': '¿', + 'iscr;': '𝒾', + 'isin;': '∈', + 'isinE;': '⋹', + 'isindot;': '⋵', + 'isins;': '⋴', + 'isinsv;': '⋳', + 'isinv;': '∈', + 'it;': '⁢', + 'itilde;': 'ĩ', + 'iukcy;': 'і', + iuml: 'ï', + 'iuml;': 'ï', + 'jcirc;': 'ĵ', + 'jcy;': 'й', + 'jfr;': '𝔧', + 'jmath;': 'ȷ', + 'jopf;': '𝕛', + 'jscr;': '𝒿', + 'jsercy;': 'ј', + 'jukcy;': 'є', + 'kappa;': 'κ', + 'kappav;': 'ϰ', + 'kcedil;': 'ķ', + 'kcy;': 'к', + 'kfr;': '𝔨', + 'kgreen;': 'ĸ', + 'khcy;': 'х', + 'kjcy;': 'ќ', + 'kopf;': '𝕜', + 'kscr;': '𝓀', + 'lAarr;': '⇚', + 'lArr;': '⇐', + 'lAtail;': '⤛', + 'lBarr;': '⤎', + 'lE;': '≦', + 'lEg;': '⪋', + 'lHar;': '⥢', + 'lacute;': 'ĺ', + 'laemptyv;': '⦴', + 'lagran;': 'ℒ', + 'lambda;': 'λ', + 'lang;': '⟨', + 'langd;': '⦑', + 'langle;': '⟨', + 'lap;': '⪅', + laquo: '«', + 'laquo;': '«', + 'larr;': '←', + 'larrb;': '⇤', + 'larrbfs;': '⤟', + 'larrfs;': '⤝', + 'larrhk;': '↩', + 'larrlp;': '↫', + 'larrpl;': '⤹', + 'larrsim;': '⥳', + 'larrtl;': '↢', + 'lat;': '⪫', + 'latail;': '⤙', + 'late;': '⪭', + 'lates;': '⪭︀', + 'lbarr;': '⤌', + 'lbbrk;': '❲', + 'lbrace;': '{', + 'lbrack;': '[', + 'lbrke;': '⦋', + 'lbrksld;': '⦏', + 'lbrkslu;': '⦍', + 'lcaron;': 'ľ', + 'lcedil;': 'ļ', + 'lceil;': '⌈', + 'lcub;': '{', + 'lcy;': 'л', + 'ldca;': '⤶', + 'ldquo;': '“', + 'ldquor;': '„', + 'ldrdhar;': '⥧', + 'ldrushar;': '⥋', + 'ldsh;': '↲', + 'le;': '≤', + 'leftarrow;': '←', + 'leftarrowtail;': '↢', + 'leftharpoondown;': '↽', + 'leftharpoonup;': '↼', + 'leftleftarrows;': '⇇', + 'leftrightarrow;': '↔', + 'leftrightarrows;': '⇆', + 'leftrightharpoons;': '⇋', + 'leftrightsquigarrow;': '↭', + 'leftthreetimes;': '⋋', + 'leg;': '⋚', + 'leq;': '≤', + 'leqq;': '≦', + 'leqslant;': '⩽', + 'les;': '⩽', + 'lescc;': '⪨', + 'lesdot;': '⩿', + 'lesdoto;': '⪁', + 'lesdotor;': '⪃', + 'lesg;': '⋚︀', + 'lesges;': '⪓', + 'lessapprox;': '⪅', + 'lessdot;': '⋖', + 'lesseqgtr;': '⋚', + 'lesseqqgtr;': '⪋', + 'lessgtr;': '≶', + 'lesssim;': '≲', + 'lfisht;': '⥼', + 'lfloor;': '⌊', + 'lfr;': '𝔩', + 'lg;': '≶', + 'lgE;': '⪑', + 'lhard;': '↽', + 'lharu;': '↼', + 'lharul;': '⥪', + 'lhblk;': '▄', + 'ljcy;': 'љ', + 'll;': '≪', + 'llarr;': '⇇', + 'llcorner;': '⌞', + 'llhard;': '⥫', + 'lltri;': '◺', + 'lmidot;': 'ŀ', + 'lmoust;': '⎰', + 'lmoustache;': '⎰', + 'lnE;': '≨', + 'lnap;': '⪉', + 'lnapprox;': '⪉', + 'lne;': '⪇', + 'lneq;': '⪇', + 'lneqq;': '≨', + 'lnsim;': '⋦', + 'loang;': '⟬', + 'loarr;': '⇽', + 'lobrk;': '⟦', + 'longleftarrow;': '⟵', + 'longleftrightarrow;': '⟷', + 'longmapsto;': '⟼', + 'longrightarrow;': '⟶', + 'looparrowleft;': '↫', + 'looparrowright;': '↬', + 'lopar;': '⦅', + 'lopf;': '𝕝', + 'loplus;': '⨭', + 'lotimes;': '⨴', + 'lowast;': '∗', + 'lowbar;': '_', + 'loz;': '◊', + 'lozenge;': '◊', + 'lozf;': '⧫', + 'lpar;': '(', + 'lparlt;': '⦓', + 'lrarr;': '⇆', + 'lrcorner;': '⌟', + 'lrhar;': '⇋', + 'lrhard;': '⥭', + 'lrm;': '‎', + 'lrtri;': '⊿', + 'lsaquo;': '‹', + 'lscr;': '𝓁', + 'lsh;': '↰', + 'lsim;': '≲', + 'lsime;': '⪍', + 'lsimg;': '⪏', + 'lsqb;': '[', + 'lsquo;': '‘', + 'lsquor;': '‚', + 'lstrok;': 'ł', + lt: '<', + 'lt;': '<', + 'ltcc;': '⪦', + 'ltcir;': '⩹', + 'ltdot;': '⋖', + 'lthree;': '⋋', + 'ltimes;': '⋉', + 'ltlarr;': '⥶', + 'ltquest;': '⩻', + 'ltrPar;': '⦖', + 'ltri;': '◃', + 'ltrie;': '⊴', + 'ltrif;': '◂', + 'lurdshar;': '⥊', + 'luruhar;': '⥦', + 'lvertneqq;': '≨︀', + 'lvnE;': '≨︀', + 'mDDot;': '∺', + macr: '¯', + 'macr;': '¯', + 'male;': '♂', + 'malt;': '✠', + 'maltese;': '✠', + 'map;': '↦', + 'mapsto;': '↦', + 'mapstodown;': '↧', + 'mapstoleft;': '↤', + 'mapstoup;': '↥', + 'marker;': '▮', + 'mcomma;': '⨩', + 'mcy;': 'м', + 'mdash;': '—', + 'measuredangle;': '∡', + 'mfr;': '𝔪', + 'mho;': '℧', + micro: 'µ', + 'micro;': 'µ', + 'mid;': '∣', + 'midast;': '*', + 'midcir;': '⫰', + middot: '·', + 'middot;': '·', + 'minus;': '−', + 'minusb;': '⊟', + 'minusd;': '∸', + 'minusdu;': '⨪', + 'mlcp;': '⫛', + 'mldr;': '…', + 'mnplus;': '∓', + 'models;': '⊧', + 'mopf;': '𝕞', + 'mp;': '∓', + 'mscr;': '𝓂', + 'mstpos;': '∾', + 'mu;': 'μ', + 'multimap;': '⊸', + 'mumap;': '⊸', + 'nGg;': '⋙̸', + 'nGt;': '≫⃒', + 'nGtv;': '≫̸', + 'nLeftarrow;': '⇍', + 'nLeftrightarrow;': '⇎', + 'nLl;': '⋘̸', + 'nLt;': '≪⃒', + 'nLtv;': '≪̸', + 'nRightarrow;': '⇏', + 'nVDash;': '⊯', + 'nVdash;': '⊮', + 'nabla;': '∇', + 'nacute;': 'ń', + 'nang;': '∠⃒', + 'nap;': '≉', + 'napE;': '⩰̸', + 'napid;': '≋̸', + 'napos;': 'ʼn', + 'napprox;': '≉', + 'natur;': '♮', + 'natural;': '♮', + 'naturals;': 'ℕ', + nbsp: ' ', + 'nbsp;': ' ', + 'nbump;': '≎̸', + 'nbumpe;': '≏̸', + 'ncap;': '⩃', + 'ncaron;': 'ň', + 'ncedil;': 'ņ', + 'ncong;': '≇', + 'ncongdot;': '⩭̸', + 'ncup;': '⩂', + 'ncy;': 'н', + 'ndash;': '–', + 'ne;': '≠', + 'neArr;': '⇗', + 'nearhk;': '⤤', + 'nearr;': '↗', + 'nearrow;': '↗', + 'nedot;': '≐̸', + 'nequiv;': '≢', + 'nesear;': '⤨', + 'nesim;': '≂̸', + 'nexist;': '∄', + 'nexists;': '∄', + 'nfr;': '𝔫', + 'ngE;': '≧̸', + 'nge;': '≱', + 'ngeq;': '≱', + 'ngeqq;': '≧̸', + 'ngeqslant;': '⩾̸', + 'nges;': '⩾̸', + 'ngsim;': '≵', + 'ngt;': '≯', + 'ngtr;': '≯', + 'nhArr;': '⇎', + 'nharr;': '↮', + 'nhpar;': '⫲', + 'ni;': '∋', + 'nis;': '⋼', + 'nisd;': '⋺', + 'niv;': '∋', + 'njcy;': 'њ', + 'nlArr;': '⇍', + 'nlE;': '≦̸', + 'nlarr;': '↚', + 'nldr;': '‥', + 'nle;': '≰', + 'nleftarrow;': '↚', + 'nleftrightarrow;': '↮', + 'nleq;': '≰', + 'nleqq;': '≦̸', + 'nleqslant;': '⩽̸', + 'nles;': '⩽̸', + 'nless;': '≮', + 'nlsim;': '≴', + 'nlt;': '≮', + 'nltri;': '⋪', + 'nltrie;': '⋬', + 'nmid;': '∤', + 'nopf;': '𝕟', + not: '¬', + 'not;': '¬', + 'notin;': '∉', + 'notinE;': '⋹̸', + 'notindot;': '⋵̸', + 'notinva;': '∉', + 'notinvb;': '⋷', + 'notinvc;': '⋶', + 'notni;': '∌', + 'notniva;': '∌', + 'notnivb;': '⋾', + 'notnivc;': '⋽', + 'npar;': '∦', + 'nparallel;': '∦', + 'nparsl;': '⫽⃥', + 'npart;': '∂̸', + 'npolint;': '⨔', + 'npr;': '⊀', + 'nprcue;': '⋠', + 'npre;': '⪯̸', + 'nprec;': '⊀', + 'npreceq;': '⪯̸', + 'nrArr;': '⇏', + 'nrarr;': '↛', + 'nrarrc;': '⤳̸', + 'nrarrw;': '↝̸', + 'nrightarrow;': '↛', + 'nrtri;': '⋫', + 'nrtrie;': '⋭', + 'nsc;': '⊁', + 'nsccue;': '⋡', + 'nsce;': '⪰̸', + 'nscr;': '𝓃', + 'nshortmid;': '∤', + 'nshortparallel;': '∦', + 'nsim;': '≁', + 'nsime;': '≄', + 'nsimeq;': '≄', + 'nsmid;': '∤', + 'nspar;': '∦', + 'nsqsube;': '⋢', + 'nsqsupe;': '⋣', + 'nsub;': '⊄', + 'nsubE;': '⫅̸', + 'nsube;': '⊈', + 'nsubset;': '⊂⃒', + 'nsubseteq;': '⊈', + 'nsubseteqq;': '⫅̸', + 'nsucc;': '⊁', + 'nsucceq;': '⪰̸', + 'nsup;': '⊅', + 'nsupE;': '⫆̸', + 'nsupe;': '⊉', + 'nsupset;': '⊃⃒', + 'nsupseteq;': '⊉', + 'nsupseteqq;': '⫆̸', + 'ntgl;': '≹', + ntilde: 'ñ', + 'ntilde;': 'ñ', + 'ntlg;': '≸', + 'ntriangleleft;': '⋪', + 'ntrianglelefteq;': '⋬', + 'ntriangleright;': '⋫', + 'ntrianglerighteq;': '⋭', + 'nu;': 'ν', + 'num;': '#', + 'numero;': '№', + 'numsp;': ' ', + 'nvDash;': '⊭', + 'nvHarr;': '⤄', + 'nvap;': '≍⃒', + 'nvdash;': '⊬', + 'nvge;': '≥⃒', + 'nvgt;': '>⃒', + 'nvinfin;': '⧞', + 'nvlArr;': '⤂', + 'nvle;': '≤⃒', + 'nvlt;': '<⃒', + 'nvltrie;': '⊴⃒', + 'nvrArr;': '⤃', + 'nvrtrie;': '⊵⃒', + 'nvsim;': '∼⃒', + 'nwArr;': '⇖', + 'nwarhk;': '⤣', + 'nwarr;': '↖', + 'nwarrow;': '↖', + 'nwnear;': '⤧', + 'oS;': 'Ⓢ', + oacute: 'ó', + 'oacute;': 'ó', + 'oast;': '⊛', + 'ocir;': '⊚', + ocirc: 'ô', + 'ocirc;': 'ô', + 'ocy;': 'о', + 'odash;': '⊝', + 'odblac;': 'ő', + 'odiv;': '⨸', + 'odot;': '⊙', + 'odsold;': '⦼', + 'oelig;': 'œ', + 'ofcir;': '⦿', + 'ofr;': '𝔬', + 'ogon;': '˛', + ograve: 'ò', + 'ograve;': 'ò', + 'ogt;': '⧁', + 'ohbar;': '⦵', + 'ohm;': 'Ω', + 'oint;': '∮', + 'olarr;': '↺', + 'olcir;': '⦾', + 'olcross;': '⦻', + 'oline;': '‾', + 'olt;': '⧀', + 'omacr;': 'ō', + 'omega;': 'ω', + 'omicron;': 'ο', + 'omid;': '⦶', + 'ominus;': '⊖', + 'oopf;': '𝕠', + 'opar;': '⦷', + 'operp;': '⦹', + 'oplus;': '⊕', + 'or;': '∨', + 'orarr;': '↻', + 'ord;': '⩝', + 'order;': 'ℴ', + 'orderof;': 'ℴ', + ordf: 'ª', + 'ordf;': 'ª', + ordm: 'º', + 'ordm;': 'º', + 'origof;': '⊶', + 'oror;': '⩖', + 'orslope;': '⩗', + 'orv;': '⩛', + 'oscr;': 'ℴ', + oslash: 'ø', + 'oslash;': 'ø', + 'osol;': '⊘', + otilde: 'õ', + 'otilde;': 'õ', + 'otimes;': '⊗', + 'otimesas;': '⨶', + ouml: 'ö', + 'ouml;': 'ö', + 'ovbar;': '⌽', + 'par;': '∥', + para: '¶', + 'para;': '¶', + 'parallel;': '∥', + 'parsim;': '⫳', + 'parsl;': '⫽', + 'part;': '∂', + 'pcy;': 'п', + 'percnt;': '%', + 'period;': '.', + 'permil;': '‰', + 'perp;': '⊥', + 'pertenk;': '‱', + 'pfr;': '𝔭', + 'phi;': 'φ', + 'phiv;': 'ϕ', + 'phmmat;': 'ℳ', + 'phone;': '☎', + 'pi;': 'π', + 'pitchfork;': '⋔', + 'piv;': 'ϖ', + 'planck;': 'ℏ', + 'planckh;': 'ℎ', + 'plankv;': 'ℏ', + 'plus;': '+', + 'plusacir;': '⨣', + 'plusb;': '⊞', + 'pluscir;': '⨢', + 'plusdo;': '∔', + 'plusdu;': '⨥', + 'pluse;': '⩲', + plusmn: '±', + 'plusmn;': '±', + 'plussim;': '⨦', + 'plustwo;': '⨧', + 'pm;': '±', + 'pointint;': '⨕', + 'popf;': '𝕡', + pound: '£', + 'pound;': '£', + 'pr;': '≺', + 'prE;': '⪳', + 'prap;': '⪷', + 'prcue;': '≼', + 'pre;': '⪯', + 'prec;': '≺', + 'precapprox;': '⪷', + 'preccurlyeq;': '≼', + 'preceq;': '⪯', + 'precnapprox;': '⪹', + 'precneqq;': '⪵', + 'precnsim;': '⋨', + 'precsim;': '≾', + 'prime;': '′', + 'primes;': 'ℙ', + 'prnE;': '⪵', + 'prnap;': '⪹', + 'prnsim;': '⋨', + 'prod;': '∏', + 'profalar;': '⌮', + 'profline;': '⌒', + 'profsurf;': '⌓', + 'prop;': '∝', + 'propto;': '∝', + 'prsim;': '≾', + 'prurel;': '⊰', + 'pscr;': '𝓅', + 'psi;': 'ψ', + 'puncsp;': ' ', + 'qfr;': '𝔮', + 'qint;': '⨌', + 'qopf;': '𝕢', + 'qprime;': '⁗', + 'qscr;': '𝓆', + 'quaternions;': 'ℍ', + 'quatint;': '⨖', + 'quest;': '?', + 'questeq;': '≟', + quot: '"', + 'quot;': '"', + 'rAarr;': '⇛', + 'rArr;': '⇒', + 'rAtail;': '⤜', + 'rBarr;': '⤏', + 'rHar;': '⥤', + 'race;': '∽̱', + 'racute;': 'ŕ', + 'radic;': '√', + 'raemptyv;': '⦳', + 'rang;': '⟩', + 'rangd;': '⦒', + 'range;': '⦥', + 'rangle;': '⟩', + raquo: '»', + 'raquo;': '»', + 'rarr;': '→', + 'rarrap;': '⥵', + 'rarrb;': '⇥', + 'rarrbfs;': '⤠', + 'rarrc;': '⤳', + 'rarrfs;': '⤞', + 'rarrhk;': '↪', + 'rarrlp;': '↬', + 'rarrpl;': '⥅', + 'rarrsim;': '⥴', + 'rarrtl;': '↣', + 'rarrw;': '↝', + 'ratail;': '⤚', + 'ratio;': '∶', + 'rationals;': 'ℚ', + 'rbarr;': '⤍', + 'rbbrk;': '❳', + 'rbrace;': '}', + 'rbrack;': ']', + 'rbrke;': '⦌', + 'rbrksld;': '⦎', + 'rbrkslu;': '⦐', + 'rcaron;': 'ř', + 'rcedil;': 'ŗ', + 'rceil;': '⌉', + 'rcub;': '}', + 'rcy;': 'р', + 'rdca;': '⤷', + 'rdldhar;': '⥩', + 'rdquo;': '”', + 'rdquor;': '”', + 'rdsh;': '↳', + 'real;': 'ℜ', + 'realine;': 'ℛ', + 'realpart;': 'ℜ', + 'reals;': 'ℝ', + 'rect;': '▭', + reg: '®', + 'reg;': '®', + 'rfisht;': '⥽', + 'rfloor;': '⌋', + 'rfr;': '𝔯', + 'rhard;': '⇁', + 'rharu;': '⇀', + 'rharul;': '⥬', + 'rho;': 'ρ', + 'rhov;': 'ϱ', + 'rightarrow;': '→', + 'rightarrowtail;': '↣', + 'rightharpoondown;': '⇁', + 'rightharpoonup;': '⇀', + 'rightleftarrows;': '⇄', + 'rightleftharpoons;': '⇌', + 'rightrightarrows;': '⇉', + 'rightsquigarrow;': '↝', + 'rightthreetimes;': '⋌', + 'ring;': '˚', + 'risingdotseq;': '≓', + 'rlarr;': '⇄', + 'rlhar;': '⇌', + 'rlm;': '‏', + 'rmoust;': '⎱', + 'rmoustache;': '⎱', + 'rnmid;': '⫮', + 'roang;': '⟭', + 'roarr;': '⇾', + 'robrk;': '⟧', + 'ropar;': '⦆', + 'ropf;': '𝕣', + 'roplus;': '⨮', + 'rotimes;': '⨵', + 'rpar;': ')', + 'rpargt;': '⦔', + 'rppolint;': '⨒', + 'rrarr;': '⇉', + 'rsaquo;': '›', + 'rscr;': '𝓇', + 'rsh;': '↱', + 'rsqb;': ']', + 'rsquo;': '’', + 'rsquor;': '’', + 'rthree;': '⋌', + 'rtimes;': '⋊', + 'rtri;': '▹', + 'rtrie;': '⊵', + 'rtrif;': '▸', + 'rtriltri;': '⧎', + 'ruluhar;': '⥨', + 'rx;': '℞', + 'sacute;': 'ś', + 'sbquo;': '‚', + 'sc;': '≻', + 'scE;': '⪴', + 'scap;': '⪸', + 'scaron;': 'š', + 'sccue;': '≽', + 'sce;': '⪰', + 'scedil;': 'ş', + 'scirc;': 'ŝ', + 'scnE;': '⪶', + 'scnap;': '⪺', + 'scnsim;': '⋩', + 'scpolint;': '⨓', + 'scsim;': '≿', + 'scy;': 'с', + 'sdot;': '⋅', + 'sdotb;': '⊡', + 'sdote;': '⩦', + 'seArr;': '⇘', + 'searhk;': '⤥', + 'searr;': '↘', + 'searrow;': '↘', + sect: '§', + 'sect;': '§', + 'semi;': ';', + 'seswar;': '⤩', + 'setminus;': '∖', + 'setmn;': '∖', + 'sext;': '✶', + 'sfr;': '𝔰', + 'sfrown;': '⌢', + 'sharp;': '♯', + 'shchcy;': 'щ', + 'shcy;': 'ш', + 'shortmid;': '∣', + 'shortparallel;': '∥', + shy: '­', + 'shy;': '­', + 'sigma;': 'σ', + 'sigmaf;': 'ς', + 'sigmav;': 'ς', + 'sim;': '∼', + 'simdot;': '⩪', + 'sime;': '≃', + 'simeq;': '≃', + 'simg;': '⪞', + 'simgE;': '⪠', + 'siml;': '⪝', + 'simlE;': '⪟', + 'simne;': '≆', + 'simplus;': '⨤', + 'simrarr;': '⥲', + 'slarr;': '←', + 'smallsetminus;': '∖', + 'smashp;': '⨳', + 'smeparsl;': '⧤', + 'smid;': '∣', + 'smile;': '⌣', + 'smt;': '⪪', + 'smte;': '⪬', + 'smtes;': '⪬︀', + 'softcy;': 'ь', + 'sol;': '/', + 'solb;': '⧄', + 'solbar;': '⌿', + 'sopf;': '𝕤', + 'spades;': '♠', + 'spadesuit;': '♠', + 'spar;': '∥', + 'sqcap;': '⊓', + 'sqcaps;': '⊓︀', + 'sqcup;': '⊔', + 'sqcups;': '⊔︀', + 'sqsub;': '⊏', + 'sqsube;': '⊑', + 'sqsubset;': '⊏', + 'sqsubseteq;': '⊑', + 'sqsup;': '⊐', + 'sqsupe;': '⊒', + 'sqsupset;': '⊐', + 'sqsupseteq;': '⊒', + 'squ;': '□', + 'square;': '□', + 'squarf;': '▪', + 'squf;': '▪', + 'srarr;': '→', + 'sscr;': '𝓈', + 'ssetmn;': '∖', + 'ssmile;': '⌣', + 'sstarf;': '⋆', + 'star;': '☆', + 'starf;': '★', + 'straightepsilon;': 'ϵ', + 'straightphi;': 'ϕ', + 'strns;': '¯', + 'sub;': '⊂', + 'subE;': '⫅', + 'subdot;': '⪽', + 'sube;': '⊆', + 'subedot;': '⫃', + 'submult;': '⫁', + 'subnE;': '⫋', + 'subne;': '⊊', + 'subplus;': '⪿', + 'subrarr;': '⥹', + 'subset;': '⊂', + 'subseteq;': '⊆', + 'subseteqq;': '⫅', + 'subsetneq;': '⊊', + 'subsetneqq;': '⫋', + 'subsim;': '⫇', + 'subsub;': '⫕', + 'subsup;': '⫓', + 'succ;': '≻', + 'succapprox;': '⪸', + 'succcurlyeq;': '≽', + 'succeq;': '⪰', + 'succnapprox;': '⪺', + 'succneqq;': '⪶', + 'succnsim;': '⋩', + 'succsim;': '≿', + 'sum;': '∑', + 'sung;': '♪', + sup1: '¹', + 'sup1;': '¹', + sup2: '²', + 'sup2;': '²', + sup3: '³', + 'sup3;': '³', + 'sup;': '⊃', + 'supE;': '⫆', + 'supdot;': '⪾', + 'supdsub;': '⫘', + 'supe;': '⊇', + 'supedot;': '⫄', + 'suphsol;': '⟉', + 'suphsub;': '⫗', + 'suplarr;': '⥻', + 'supmult;': '⫂', + 'supnE;': '⫌', + 'supne;': '⊋', + 'supplus;': '⫀', + 'supset;': '⊃', + 'supseteq;': '⊇', + 'supseteqq;': '⫆', + 'supsetneq;': '⊋', + 'supsetneqq;': '⫌', + 'supsim;': '⫈', + 'supsub;': '⫔', + 'supsup;': '⫖', + 'swArr;': '⇙', + 'swarhk;': '⤦', + 'swarr;': '↙', + 'swarrow;': '↙', + 'swnwar;': '⤪', + szlig: 'ß', + 'szlig;': 'ß', + 'target;': '⌖', + 'tau;': 'τ', + 'tbrk;': '⎴', + 'tcaron;': 'ť', + 'tcedil;': 'ţ', + 'tcy;': 'т', + 'tdot;': '⃛', + 'telrec;': '⌕', + 'tfr;': '𝔱', + 'there4;': '∴', + 'therefore;': '∴', + 'theta;': 'θ', + 'thetasym;': 'ϑ', + 'thetav;': 'ϑ', + 'thickapprox;': '≈', + 'thicksim;': '∼', + 'thinsp;': ' ', + 'thkap;': '≈', + 'thksim;': '∼', + thorn: 'þ', + 'thorn;': 'þ', + 'tilde;': '˜', + times: '×', + 'times;': '×', + 'timesb;': '⊠', + 'timesbar;': '⨱', + 'timesd;': '⨰', + 'tint;': '∭', + 'toea;': '⤨', + 'top;': '⊤', + 'topbot;': '⌶', + 'topcir;': '⫱', + 'topf;': '𝕥', + 'topfork;': '⫚', + 'tosa;': '⤩', + 'tprime;': '‴', + 'trade;': '™', + 'triangle;': '▵', + 'triangledown;': '▿', + 'triangleleft;': '◃', + 'trianglelefteq;': '⊴', + 'triangleq;': '≜', + 'triangleright;': '▹', + 'trianglerighteq;': '⊵', + 'tridot;': '◬', + 'trie;': '≜', + 'triminus;': '⨺', + 'triplus;': '⨹', + 'trisb;': '⧍', + 'tritime;': '⨻', + 'trpezium;': '⏢', + 'tscr;': '𝓉', + 'tscy;': 'ц', + 'tshcy;': 'ћ', + 'tstrok;': 'ŧ', + 'twixt;': '≬', + 'twoheadleftarrow;': '↞', + 'twoheadrightarrow;': '↠', + 'uArr;': '⇑', + 'uHar;': '⥣', + uacute: 'ú', + 'uacute;': 'ú', + 'uarr;': '↑', + 'ubrcy;': 'ў', + 'ubreve;': 'ŭ', + ucirc: 'û', + 'ucirc;': 'û', + 'ucy;': 'у', + 'udarr;': '⇅', + 'udblac;': 'ű', + 'udhar;': '⥮', + 'ufisht;': '⥾', + 'ufr;': '𝔲', + ugrave: 'ù', + 'ugrave;': 'ù', + 'uharl;': '↿', + 'uharr;': '↾', + 'uhblk;': '▀', + 'ulcorn;': '⌜', + 'ulcorner;': '⌜', + 'ulcrop;': '⌏', + 'ultri;': '◸', + 'umacr;': 'ū', + uml: '¨', + 'uml;': '¨', + 'uogon;': 'ų', + 'uopf;': '𝕦', + 'uparrow;': '↑', + 'updownarrow;': '↕', + 'upharpoonleft;': '↿', + 'upharpoonright;': '↾', + 'uplus;': '⊎', + 'upsi;': 'υ', + 'upsih;': 'ϒ', + 'upsilon;': 'υ', + 'upuparrows;': '⇈', + 'urcorn;': '⌝', + 'urcorner;': '⌝', + 'urcrop;': '⌎', + 'uring;': 'ů', + 'urtri;': '◹', + 'uscr;': '𝓊', + 'utdot;': '⋰', + 'utilde;': 'ũ', + 'utri;': '▵', + 'utrif;': '▴', + 'uuarr;': '⇈', + uuml: 'ü', + 'uuml;': 'ü', + 'uwangle;': '⦧', + 'vArr;': '⇕', + 'vBar;': '⫨', + 'vBarv;': '⫩', + 'vDash;': '⊨', + 'vangrt;': '⦜', + 'varepsilon;': 'ϵ', + 'varkappa;': 'ϰ', + 'varnothing;': '∅', + 'varphi;': 'ϕ', + 'varpi;': 'ϖ', + 'varpropto;': '∝', + 'varr;': '↕', + 'varrho;': 'ϱ', + 'varsigma;': 'ς', + 'varsubsetneq;': '⊊︀', + 'varsubsetneqq;': '⫋︀', + 'varsupsetneq;': '⊋︀', + 'varsupsetneqq;': '⫌︀', + 'vartheta;': 'ϑ', + 'vartriangleleft;': '⊲', + 'vartriangleright;': '⊳', + 'vcy;': 'в', + 'vdash;': '⊢', + 'vee;': '∨', + 'veebar;': '⊻', + 'veeeq;': '≚', + 'vellip;': '⋮', + 'verbar;': '|', + 'vert;': '|', + 'vfr;': '𝔳', + 'vltri;': '⊲', + 'vnsub;': '⊂⃒', + 'vnsup;': '⊃⃒', + 'vopf;': '𝕧', + 'vprop;': '∝', + 'vrtri;': '⊳', + 'vscr;': '𝓋', + 'vsubnE;': '⫋︀', + 'vsubne;': '⊊︀', + 'vsupnE;': '⫌︀', + 'vsupne;': '⊋︀', + 'vzigzag;': '⦚', + 'wcirc;': 'ŵ', + 'wedbar;': '⩟', + 'wedge;': '∧', + 'wedgeq;': '≙', + 'weierp;': '℘', + 'wfr;': '𝔴', + 'wopf;': '𝕨', + 'wp;': '℘', + 'wr;': '≀', + 'wreath;': '≀', + 'wscr;': '𝓌', + 'xcap;': '⋂', + 'xcirc;': '◯', + 'xcup;': '⋃', + 'xdtri;': '▽', + 'xfr;': '𝔵', + 'xhArr;': '⟺', + 'xharr;': '⟷', + 'xi;': 'ξ', + 'xlArr;': '⟸', + 'xlarr;': '⟵', + 'xmap;': '⟼', + 'xnis;': '⋻', + 'xodot;': '⨀', + 'xopf;': '𝕩', + 'xoplus;': '⨁', + 'xotime;': '⨂', + 'xrArr;': '⟹', + 'xrarr;': '⟶', + 'xscr;': '𝓍', + 'xsqcup;': '⨆', + 'xuplus;': '⨄', + 'xutri;': '△', + 'xvee;': '⋁', + 'xwedge;': '⋀', + yacute: 'ý', + 'yacute;': 'ý', + 'yacy;': 'я', + 'ycirc;': 'ŷ', + 'ycy;': 'ы', + yen: '¥', + 'yen;': '¥', + 'yfr;': '𝔶', + 'yicy;': 'ї', + 'yopf;': '𝕪', + 'yscr;': '𝓎', + 'yucy;': 'ю', + yuml: 'ÿ', + 'yuml;': 'ÿ', + 'zacute;': 'ź', + 'zcaron;': 'ž', + 'zcy;': 'з', + 'zdot;': 'ż', + 'zeetrf;': 'ℨ', + 'zeta;': 'ζ', + 'zfr;': '𝔷', + 'zhcy;': 'ж', + 'zigrarr;': '⇝', + 'zopf;': '𝕫', + 'zscr;': '𝓏', + 'zwj;': '‍', + 'zwnj;': '‌' +}; + +const numeric = /&#(x)?([0-9a-f]+);/i; +const named = new RegExp( + `&(${Object.keys(entities) + .sort((a, b) => b.length - a.length) + .join('|')})`, + 'g' +); + +/** @param {string} str */ +export function decode(str) { + return str + .replace(numeric, (_match, hex, code) => String.fromCharCode(hex ? parseInt(code, 16) : +code)) + .replace(named, (_match, entity) => entities[entity]); +} diff --git a/node_modules/@sveltejs/kit/src/core/postbuild/fallback.js b/node_modules/@sveltejs/kit/src/core/postbuild/fallback.js new file mode 100644 index 0000000..40d6a9a --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/postbuild/fallback.js @@ -0,0 +1,54 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { installPolyfills } from '../../exports/node/polyfills.js'; +import { load_config } from '../config/index.js'; +import { forked } from '../../utils/fork.js'; + +export default forked(import.meta.url, generate_fallback); + +/** + * @param {{ + * manifest_path: string; + * env: Record + * }} opts + */ +async function generate_fallback({ manifest_path, env }) { + /** @type {import('types').ValidatedKitConfig} */ + const config = (await load_config()).kit; + + installPolyfills(); + + const server_root = join(config.outDir, 'output'); + + /** @type {import('types').ServerInternalModule} */ + const { set_building } = await import(pathToFileURL(`${server_root}/server/internal.js`).href); + + /** @type {import('types').ServerModule} */ + const { Server } = await import(pathToFileURL(`${server_root}/server/index.js`).href); + + /** @type {import('@sveltejs/kit').SSRManifest} */ + const manifest = (await import(pathToFileURL(manifest_path).href)).manifest; + + set_building(true); + + const server = new Server(manifest); + await server.init({ env }); + + const response = await server.respond(new Request(config.prerender.origin + '/[fallback]'), { + getClientAddress: () => { + throw new Error('Cannot read clientAddress during prerendering'); + }, + prerendering: { + fallback: true, + dependencies: new Map() + }, + read: (file) => readFileSync(join(config.files.assets, file)) + }); + + if (response.ok) { + return await response.text(); + } + + throw new Error(`Could not create a fallback page — failed with status ${response.status}`); +} diff --git a/node_modules/@sveltejs/kit/src/core/postbuild/prerender.js b/node_modules/@sveltejs/kit/src/core/postbuild/prerender.js new file mode 100644 index 0000000..e64b7f8 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/postbuild/prerender.js @@ -0,0 +1,483 @@ +import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { installPolyfills } from '../../exports/node/polyfills.js'; +import { mkdirp, posixify, walk } from '../../utils/filesystem.js'; +import { should_polyfill } from '../../utils/platform.js'; +import { decode_uri, is_root_relative, resolve } from '../../utils/url.js'; +import { escape_html_attr } from '../../utils/escape.js'; +import { logger } from '../utils.js'; +import { load_config } from '../config/index.js'; +import { get_route_segments } from '../../utils/routing.js'; +import { queue } from './queue.js'; +import { crawl } from './crawl.js'; +import { forked } from '../../utils/fork.js'; +import * as devalue from 'devalue'; + +export default forked(import.meta.url, prerender); + +/** + * @param {{ + * out: string; + * manifest_path: string; + * metadata: import('types').ServerMetadata; + * verbose: boolean; + * env: Record + * }} opts + */ +async function prerender({ out, manifest_path, metadata, verbose, env }) { + /** @type {import('@sveltejs/kit').SSRManifest} */ + const manifest = (await import(pathToFileURL(manifest_path).href)).manifest; + + /** @type {import('types').ServerInternalModule} */ + const internal = await import(pathToFileURL(`${out}/server/internal.js`).href); + + /** @type {import('types').ServerModule} */ + const { Server } = await import(pathToFileURL(`${out}/server/index.js`).href); + + // configure `import { building } from '$app/environment'` — + // essential we do this before analysing the code + internal.set_building(true); + + /** + * @template {{message: string}} T + * @template {Omit} K + * @param {import('types').Logger} log + * @param {'fail' | 'warn' | 'ignore' | ((details: T) => void)} input + * @param {(details: K) => string} format + * @returns {(details: K) => void} + */ + function normalise_error_handler(log, input, format) { + switch (input) { + case 'fail': + return (details) => { + throw new Error(format(details)); + }; + case 'warn': + return (details) => { + log.error(format(details)); + }; + case 'ignore': + return () => {}; + default: + // @ts-expect-error TS thinks T might be of a different kind, but it's not + return (details) => input({ ...details, message: format(details) }); + } + } + + const OK = 2; + const REDIRECT = 3; + + /** @type {import('types').Prerendered} */ + const prerendered = { + pages: new Map(), + assets: new Map(), + redirects: new Map(), + paths: [] + }; + + /** @type {import('types').PrerenderMap} */ + const prerender_map = new Map(); + + for (const [id, { prerender }] of metadata.routes) { + if (prerender !== undefined) { + prerender_map.set(id, prerender); + } + } + + /** @type {Set} */ + const prerendered_routes = new Set(); + + /** @type {import('types').ValidatedKitConfig} */ + const config = (await load_config()).kit; + + /** @type {import('types').Logger} */ + const log = logger({ verbose }); + + if (should_polyfill) { + installPolyfills(); + } + + /** @type {Map} */ + const saved = new Map(); + + const server = new Server(manifest); + await server.init({ env }); + + const handle_http_error = normalise_error_handler( + log, + config.prerender.handleHttpError, + ({ status, path, referrer, referenceType }) => { + const message = + status === 404 && !path.startsWith(config.paths.base) + ? `${path} does not begin with \`base\`, which is configured in \`paths.base\` and can be imported from \`$app/paths\` - see https://kit.svelte.dev/docs/configuration#paths for more info` + : path; + + return `${status} ${message}${referrer ? ` (${referenceType} from ${referrer})` : ''}`; + } + ); + + const handle_missing_id = normalise_error_handler( + log, + config.prerender.handleMissingId, + ({ path, id, referrers }) => { + return ( + `The following pages contain links to ${path}#${id}, but no element with id="${id}" exists on ${path} - see the \`handleMissingId\` option in https://kit.svelte.dev/docs/configuration#prerender for more info:` + + referrers.map((l) => `\n - ${l}`).join('') + ); + } + ); + + const handle_entry_generator_mismatch = normalise_error_handler( + log, + config.prerender.handleEntryGeneratorMismatch, + ({ generatedFromId, entry, matchedId }) => { + return `The entries export from ${generatedFromId} generated entry ${entry}, which was matched by ${matchedId} - see the \`handleEntryGeneratorMismatch\` option in https://kit.svelte.dev/docs/configuration#prerender for more info.`; + } + ); + + const q = queue(config.prerender.concurrency); + + /** + * @param {string} path + * @param {boolean} is_html + */ + function output_filename(path, is_html) { + const file = path.slice(config.paths.base.length + 1) || 'index.html'; + + if (is_html && !file.endsWith('.html')) { + return file + (file.endsWith('/') ? 'index.html' : '.html'); + } + + return file; + } + + const files = new Set(walk(`${out}/client`).map(posixify)); + + const immutable = `${config.appDir}/immutable`; + if (existsSync(`${out}/server/${immutable}`)) { + for (const file of walk(`${out}/server/${immutable}`)) { + files.add(posixify(`${config.appDir}/immutable/${file}`)); + } + } + const seen = new Set(); + const written = new Set(); + + /** @type {Map>} */ + const expected_hashlinks = new Map(); + + /** @type {Map} */ + const actual_hashlinks = new Map(); + + /** + * @param {string | null} referrer + * @param {string} decoded + * @param {string} [encoded] + * @param {string} [generated_from_id] + */ + function enqueue(referrer, decoded, encoded, generated_from_id) { + if (seen.has(decoded)) return; + seen.add(decoded); + + const file = decoded.slice(config.paths.base.length + 1); + if (files.has(file)) return; + + return q.add(() => visit(decoded, encoded || encodeURI(decoded), referrer, generated_from_id)); + } + + /** + * @param {string} decoded + * @param {string} encoded + * @param {string?} referrer + * @param {string} [generated_from_id] + */ + async function visit(decoded, encoded, referrer, generated_from_id) { + if (!decoded.startsWith(config.paths.base)) { + handle_http_error({ status: 404, path: decoded, referrer, referenceType: 'linked' }); + return; + } + + /** @type {Map} */ + const dependencies = new Map(); + + const response = await server.respond(new Request(config.prerender.origin + encoded), { + getClientAddress() { + throw new Error('Cannot read clientAddress during prerendering'); + }, + prerendering: { + dependencies + }, + read: (file) => { + // stuff we just wrote + const filepath = saved.get(file); + if (filepath) return readFileSync(filepath); + + // stuff in `static` + return readFileSync(join(config.files.assets, file)); + } + }); + + const encoded_id = response.headers.get('x-sveltekit-routeid'); + const decoded_id = encoded_id && decode_uri(encoded_id); + if ( + decoded_id !== null && + generated_from_id !== undefined && + decoded_id !== generated_from_id + ) { + handle_entry_generator_mismatch({ + generatedFromId: generated_from_id, + entry: decoded, + matchedId: decoded_id + }); + } + + const body = Buffer.from(await response.arrayBuffer()); + + save('pages', response, body, decoded, encoded, referrer, 'linked'); + + for (const [dependency_path, result] of dependencies) { + // this seems circuitous, but using new URL allows us to not care + // whether dependency_path is encoded or not + const encoded_dependency_path = new URL(dependency_path, 'http://localhost').pathname; + const decoded_dependency_path = decode_uri(encoded_dependency_path); + + const headers = Object.fromEntries(result.response.headers); + + const prerender = headers['x-sveltekit-prerender']; + if (prerender) { + const encoded_route_id = headers['x-sveltekit-routeid']; + if (encoded_route_id != null) { + const route_id = decode_uri(encoded_route_id); + const existing_value = prerender_map.get(route_id); + if (existing_value !== 'auto') { + prerender_map.set(route_id, prerender === 'true' ? true : 'auto'); + } + } + } + + const body = result.body ?? new Uint8Array(await result.response.arrayBuffer()); + + save( + 'dependencies', + result.response, + body, + decoded_dependency_path, + encoded_dependency_path, + decoded, + 'fetched' + ); + } + + // avoid triggering `filterSerializeResponseHeaders` guard + const headers = Object.fromEntries(response.headers); + + if (config.prerender.crawl && headers['content-type'] === 'text/html') { + const { ids, hrefs } = crawl(body.toString(), decoded); + + actual_hashlinks.set(decoded, ids); + + for (const href of hrefs) { + if (!is_root_relative(href)) continue; + + const { pathname, search, hash } = new URL(href, 'http://localhost'); + + if (search) { + // TODO warn that query strings have no effect on statically-exported pages + } + + if (hash) { + const key = decode_uri(pathname + hash); + + if (!expected_hashlinks.has(key)) { + expected_hashlinks.set(key, new Set()); + } + + /** @type {Set} */ (expected_hashlinks.get(key)).add(decoded); + } + + enqueue(decoded, decode_uri(pathname), pathname); + } + } + } + + /** + * @param {'pages' | 'dependencies'} category + * @param {Response} response + * @param {string | Uint8Array} body + * @param {string} decoded + * @param {string} encoded + * @param {string | null} referrer + * @param {'linked' | 'fetched'} referenceType + */ + function save(category, response, body, decoded, encoded, referrer, referenceType) { + const response_type = Math.floor(response.status / 100); + const headers = Object.fromEntries(response.headers); + + const type = headers['content-type']; + const is_html = response_type === REDIRECT || type === 'text/html'; + + const file = output_filename(decoded, is_html); + const dest = `${config.outDir}/output/prerendered/${category}/${file}`; + + if (written.has(file)) return; + + const encoded_route_id = response.headers.get('x-sveltekit-routeid'); + const route_id = encoded_route_id != null ? decode_uri(encoded_route_id) : null; + if (route_id !== null) prerendered_routes.add(route_id); + + if (response_type === REDIRECT) { + const location = headers['location']; + + if (location) { + const resolved = resolve(encoded, location); + if (is_root_relative(resolved)) { + enqueue(decoded, decode_uri(resolved), resolved); + } + + if (!headers['x-sveltekit-normalize']) { + mkdirp(dirname(dest)); + + log.warn(`${response.status} ${decoded} -> ${location}`); + + writeFileSync( + dest, + `` + ); + + written.add(file); + + if (!prerendered.redirects.has(decoded)) { + prerendered.redirects.set(decoded, { + status: response.status, + location: resolved + }); + + prerendered.paths.push(decoded); + } + } + } else { + log.warn(`location header missing on redirect received from ${decoded}`); + } + + return; + } + + if (response.status === 200) { + if (existsSync(dest) && statSync(dest).isDirectory()) { + throw new Error( + `Cannot save ${decoded} as it is already a directory. See https://kit.svelte.dev/docs/page-options#prerender-route-conflicts for more information` + ); + } + + const dir = dirname(dest); + + if (existsSync(dir) && !statSync(dir).isDirectory()) { + const parent = decoded.split('/').slice(0, -1).join('/'); + throw new Error( + `Cannot save ${decoded} as ${parent} is already a file. See https://kit.svelte.dev/docs/page-options#prerender-route-conflicts for more information` + ); + } + + mkdirp(dir); + + log.info(`${response.status} ${decoded}`); + writeFileSync(dest, body); + written.add(file); + + if (is_html) { + prerendered.pages.set(decoded, { + file + }); + } else { + prerendered.assets.set(decoded, { + type + }); + } + + prerendered.paths.push(decoded); + } else if (response_type !== OK) { + handle_http_error({ status: response.status, path: decoded, referrer, referenceType }); + } + + manifest.assets.add(file); + saved.set(file, dest); + } + + /** @type {Array<{ id: string, entries: Array}>} */ + const route_level_entries = []; + for (const [id, { entries }] of metadata.routes.entries()) { + if (entries) { + route_level_entries.push({ id, entries }); + } + } + + if ( + config.prerender.entries.length > 1 || + config.prerender.entries[0] !== '*' || + route_level_entries.length > 0 || + prerender_map.size > 0 + ) { + // Only log if we're actually going to do something to not confuse users + log.info('Prerendering'); + } + + for (const entry of config.prerender.entries) { + if (entry === '*') { + for (const [id, prerender] of prerender_map) { + if (prerender) { + if (id.includes('[')) continue; + const path = `/${get_route_segments(id).join('/')}`; + enqueue(null, config.paths.base + path); + } + } + } else { + enqueue(null, config.paths.base + entry); + } + } + + for (const { id, entries } of route_level_entries) { + for (const entry of entries) { + enqueue(null, config.paths.base + entry, undefined, id); + } + } + + await q.done(); + + // handle invalid fragment links + for (const [key, referrers] of expected_hashlinks) { + const index = key.indexOf('#'); + const path = key.slice(0, index); + const id = key.slice(index + 1); + + const hashlinks = actual_hashlinks.get(path); + // ignore fragment links to pages that were not prerendered + if (!hashlinks) continue; + + if (!hashlinks.includes(id)) { + handle_missing_id({ id, path, referrers: Array.from(referrers) }); + } + } + + /** @type {string[]} */ + const not_prerendered = []; + + for (const [route_id, prerender] of prerender_map) { + if (prerender === true && !prerendered_routes.has(route_id)) { + not_prerendered.push(route_id); + } + } + + if (not_prerendered.length > 0) { + throw new Error( + `The following routes were marked as prerenderable, but were not prerendered because they were not found while crawling your app:\n${not_prerendered.map( + (id) => ` - ${id}` + )}\n\nSee https://kit.svelte.dev/docs/page-options#prerender-troubleshooting for info on how to solve this` + ); + } + + return { prerendered, prerender_map }; +} diff --git a/node_modules/@sveltejs/kit/src/core/postbuild/queue.js b/node_modules/@sveltejs/kit/src/core/postbuild/queue.js new file mode 100644 index 0000000..79a2e9b --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/postbuild/queue.js @@ -0,0 +1,80 @@ +/** + * @typedef {{ + * fn: () => Promise, + * fulfil: (value: any) => void, + * reject: (error: Error) => void + * }} Task + */ + +/** @param {number} concurrency */ +export function queue(concurrency) { + /** @type {Task[]} */ + const tasks = []; + + let current = 0; + + /** @type {(value?: any) => void} */ + let fulfil; + + /** @type {(error: Error) => void} */ + let reject; + + let closed = false; + + const done = new Promise((f, r) => { + fulfil = f; + reject = r; + }); + + done.catch(() => { + // this is necessary in case a catch handler is never added + // to the done promise by the user + }); + + function dequeue() { + if (current < concurrency) { + const task = tasks.shift(); + + if (task) { + current += 1; + const promise = Promise.resolve(task.fn()); + + promise + .then(task.fulfil, (err) => { + task.reject(err); + reject(err); + }) + .then(() => { + current -= 1; + dequeue(); + }); + } else if (current === 0) { + closed = true; + fulfil(); + } + } + } + + return { + /** @param {() => any} fn */ + add: (fn) => { + if (closed) throw new Error('Cannot add tasks to a queue that has ended'); + + const promise = new Promise((fulfil, reject) => { + tasks.push({ fn, fulfil, reject }); + }); + + dequeue(); + return promise; + }, + + done: () => { + if (current === 0) { + closed = true; + fulfil(); + } + + return done; + } + }; +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/conflict.js b/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/conflict.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/index.js b/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/index.js new file mode 100644 index 0000000..06426da --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/index.js @@ -0,0 +1,546 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import mime from 'mime'; +import { list_files, runtime_directory } from '../../utils.js'; +import { posixify } from '../../../utils/filesystem.js'; +import { parse_route_id } from '../../../utils/routing.js'; +import { sort_routes } from './sort.js'; + +/** + * Generates the manifest data used for the client-side manifest and types generation. + * @param {{ + * config: import('types').ValidatedConfig; + * fallback?: string; + * cwd?: string; + * }} opts + * @returns {import('types').ManifestData} + */ +export default function create_manifest_data({ + config, + fallback = `${runtime_directory}/components`, + cwd = process.cwd() +}) { + const assets = create_assets(config); + const matchers = create_matchers(config, cwd); + const { nodes, routes } = create_routes_and_nodes(cwd, config, fallback); + + for (const route of routes) { + for (const param of route.params) { + if (param.matcher && !matchers[param.matcher]) { + throw new Error(`No matcher found for parameter '${param.matcher}' in route ${route.id}`); + } + } + } + + return { + assets, + matchers, + nodes, + routes + }; +} + +/** + * @param {import('types').ValidatedConfig} config + */ +export function create_assets(config) { + return list_files(config.kit.files.assets).map((file) => ({ + file, + size: fs.statSync(path.resolve(config.kit.files.assets, file)).size, + type: mime.getType(file) + })); +} + +/** + * @param {import('types').ValidatedConfig} config + * @param {string} cwd + */ +function create_matchers(config, cwd) { + const params_base = path.relative(cwd, config.kit.files.params); + + /** @type {Record} */ + const matchers = {}; + if (fs.existsSync(config.kit.files.params)) { + for (const file of fs.readdirSync(config.kit.files.params)) { + const ext = path.extname(file); + if (!config.kit.moduleExtensions.includes(ext)) continue; + const type = file.slice(0, -ext.length); + + if (/^\w+$/.test(type)) { + const matcher_file = path.join(params_base, file); + + // Disallow same matcher with different extensions + if (matchers[type]) { + throw new Error(`Duplicate matchers: ${matcher_file} and ${matchers[type]}`); + } else { + matchers[type] = matcher_file; + } + } else { + // Allow for matcher test collocation + if (type.endsWith('.test') || type.endsWith('.spec')) continue; + + throw new Error( + `Matcher names can only have underscores and alphanumeric characters — "${file}" is invalid` + ); + } + } + } + + return matchers; +} + +/** + * @param {import('types').ValidatedConfig} config + * @param {string} cwd + * @param {string} fallback + */ +function create_routes_and_nodes(cwd, config, fallback) { + /** @type {import('types').RouteData[]} */ + const routes = []; + + const routes_base = posixify(path.relative(cwd, config.kit.files.routes)); + + const valid_extensions = [...config.extensions, ...config.kit.moduleExtensions]; + + /** @type {import('types').PageNode[]} */ + const nodes = []; + + if (fs.existsSync(config.kit.files.routes)) { + /** + * @param {number} depth + * @param {string} id + * @param {string} segment + * @param {import('types').RouteData | null} parent + */ + const walk = (depth, id, segment, parent) => { + const unescaped = id.replace(/\[([ux])\+([^\]]+)\]/gi, (match, type, code) => { + if (match !== match.toLowerCase()) { + throw new Error(`Character escape sequence in ${id} must be lowercase`); + } + + if (!/[0-9a-f]+/.test(code)) { + throw new Error(`Invalid character escape sequence in ${id}`); + } + + if (type === 'x') { + if (code.length !== 2) { + throw new Error(`Hexadecimal escape sequence in ${id} must be two characters`); + } + + return String.fromCharCode(parseInt(code, 16)); + } else { + if (code.length < 4 || code.length > 6) { + throw new Error( + `Unicode escape sequence in ${id} must be between four and six characters` + ); + } + + return String.fromCharCode(parseInt(code, 16)); + } + }); + + if (/\]\[/.test(unescaped)) { + throw new Error(`Invalid route ${id} — parameters must be separated`); + } + + if (count_occurrences('[', id) !== count_occurrences(']', id)) { + throw new Error(`Invalid route ${id} — brackets are unbalanced`); + } + + if (/#/.test(segment)) { + // Vite will barf on files with # in them + throw new Error(`Route ${id} should be renamed to ${id.replace(/#/g, '[x+23]')}`); + } + + if (/\[\.\.\.\w+\]\/\[\[/.test(id)) { + throw new Error( + `Invalid route ${id} — an [[optional]] route segment cannot follow a [...rest] route segment` + ); + } + + if (/\[\[\.\.\./.test(id)) { + throw new Error( + `Invalid route ${id} — a rest route segment is always optional, remove the outer square brackets` + ); + } + + const { pattern, params } = parse_route_id(id); + + /** @type {import('types').RouteData} */ + const route = { + id, + parent, + + segment, + pattern, + params, + + layout: null, + error: null, + leaf: null, + page: null, + endpoint: null + }; + + // important to do this before walking children, so that child + // routes appear later + routes.push(route); + + // if we don't do this, the route map becomes unwieldy to console.log + Object.defineProperty(route, 'parent', { enumerable: false }); + + const dir = path.join(cwd, routes_base, id); + + // We can't use withFileTypes because of a NodeJs bug which returns wrong results + // with isDirectory() in case of symlinks: https://github.com/nodejs/node/issues/30646 + const files = fs.readdirSync(dir).map((name) => ({ + is_dir: fs.statSync(path.join(dir, name)).isDirectory(), + name + })); + + // process files first + for (const file of files) { + if (file.is_dir) continue; + if (!file.name.startsWith('+')) continue; + if (!valid_extensions.find((ext) => file.name.endsWith(ext))) continue; + + if (file.name.endsWith('.d.ts')) { + let name = file.name.slice(0, -5); + const ext = valid_extensions.find((ext) => name.endsWith(ext)); + if (ext) name = name.slice(0, -ext.length); + + const valid = + /^\+(?:(page(?:@(.*))?)|(layout(?:@(.*))?)|(error))$/.test(name) || + /^\+(?:(server)|(page(?:(@[a-zA-Z0-9_-]*))?(\.server)?)|(layout(?:(@[a-zA-Z0-9_-]*))?(\.server)?))$/.test( + name + ); + + if (valid) continue; + } + + const project_relative = posixify(path.relative(cwd, path.join(dir, file.name))); + + const item = analyze( + project_relative, + file.name, + config.extensions, + config.kit.moduleExtensions + ); + + /** + * @param {string} type + * @param {string} existing_file + */ + function duplicate_files_error(type, existing_file) { + return new Error( + `Multiple ${type} files found in ${routes_base}${route.id} : ${path.basename( + existing_file + )} and ${file.name}` + ); + } + + if (item.kind === 'component') { + if (item.is_error) { + route.error = { + depth, + component: project_relative + }; + } else if (item.is_layout) { + if (!route.layout) { + route.layout = { depth, child_pages: [] }; + } else if (route.layout.component) { + throw duplicate_files_error('layout component', route.layout.component); + } + + route.layout.component = project_relative; + if (item.uses_layout !== undefined) route.layout.parent_id = item.uses_layout; + } else { + if (!route.leaf) { + route.leaf = { depth }; + } else if (route.leaf.component) { + throw duplicate_files_error('page component', route.leaf.component); + } + + route.leaf.component = project_relative; + if (item.uses_layout !== undefined) route.leaf.parent_id = item.uses_layout; + } + } else if (item.is_layout) { + if (!route.layout) { + route.layout = { depth, child_pages: [] }; + } else if (route.layout[item.kind]) { + throw duplicate_files_error( + item.kind + ' layout module', + /** @type {string} */ (route.layout[item.kind]) + ); + } + + route.layout[item.kind] = project_relative; + } else if (item.is_page) { + if (!route.leaf) { + route.leaf = { depth }; + } else if (route.leaf[item.kind]) { + throw duplicate_files_error( + item.kind + ' page module', + /** @type {string} */ (route.leaf[item.kind]) + ); + } + + route.leaf[item.kind] = project_relative; + } else { + if (route.endpoint) { + throw duplicate_files_error('endpoint', route.endpoint.file); + } + + route.endpoint = { + file: project_relative + }; + } + } + + // then handle children + for (const file of files) { + if (file.is_dir) { + walk(depth + 1, path.posix.join(id, file.name), file.name, route); + } + } + }; + + walk(0, '/', '', null); + + if (routes.length === 1) { + const root = routes[0]; + if (!root.leaf && !root.error && !root.layout && !root.endpoint) { + throw new Error( + 'No routes found. If you are using a custom src/routes directory, make sure it is specified in svelte.config.js' + ); + } + } + } else { + // If there's no routes directory, we'll just create a single empty route. This ensures the root layout and + // error components are included in the manifest, which is needed for subsequent build/dev commands to work + routes.push({ + id: '/', + segment: '', + pattern: /^$/, + params: [], + parent: null, + layout: null, + error: null, + leaf: null, + page: null, + endpoint: null + }); + } + + prevent_conflicts(routes); + + const root = routes[0]; + + if (!root.layout?.component) { + if (!root.layout) root.layout = { depth: 0, child_pages: [] }; + root.layout.component = posixify(path.relative(cwd, `${fallback}/layout.svelte`)); + } + + if (!root.error?.component) { + if (!root.error) root.error = { depth: 0 }; + root.error.component = posixify(path.relative(cwd, `${fallback}/error.svelte`)); + } + + // we do layouts/errors first as they are more likely to be reused, + // and smaller indexes take fewer bytes. also, this guarantees that + // the default error/layout are 0/1 + for (const route of routes) { + if (route.layout) { + if (!route.layout?.component) { + route.layout.component = posixify(path.relative(cwd, `${fallback}/layout.svelte`)); + } + nodes.push(route.layout); + } + if (route.error) nodes.push(route.error); + } + + for (const route of routes) { + if (route.leaf) nodes.push(route.leaf); + } + + const indexes = new Map(nodes.map((node, i) => [node, i])); + + for (const route of routes) { + if (!route.leaf) continue; + + route.page = { + layouts: [], + errors: [], + leaf: /** @type {number} */ (indexes.get(route.leaf)) + }; + + /** @type {import('types').RouteData | null} */ + let current_route = route; + let current_node = route.leaf; + let parent_id = route.leaf.parent_id; + + while (current_route) { + if (parent_id === undefined || current_route.segment === parent_id) { + if (current_route.layout || current_route.error) { + route.page.layouts.unshift( + current_route.layout ? indexes.get(current_route.layout) : undefined + ); + route.page.errors.unshift( + current_route.error ? indexes.get(current_route.error) : undefined + ); + } + + if (current_route.layout) { + /** @type {import('types').PageNode[]} */ (current_route.layout.child_pages).push( + route.leaf + ); + current_node.parent = current_node = current_route.layout; + parent_id = current_node.parent_id; + } else { + parent_id = undefined; + } + } + + current_route = current_route.parent; + } + + if (parent_id !== undefined) { + throw new Error(`${current_node.component} references missing segment "${parent_id}"`); + } + } + + return { + nodes, + routes: sort_routes(routes) + }; +} + +/** + * @param {string} project_relative + * @param {string} file + * @param {string[]} component_extensions + * @param {string[]} module_extensions + * @returns {import('./types').RouteFile} + */ +function analyze(project_relative, file, component_extensions, module_extensions) { + const component_extension = component_extensions.find((ext) => file.endsWith(ext)); + if (component_extension) { + const name = file.slice(0, -component_extension.length); + const pattern = /^\+(?:(page(?:@(.*))?)|(layout(?:@(.*))?)|(error))$/; + const match = pattern.exec(name); + if (!match) { + throw new Error(`Files prefixed with + are reserved (saw ${project_relative})`); + } + + return { + kind: 'component', + is_page: !!match[1], + is_layout: !!match[3], + is_error: !!match[5], + uses_layout: match[2] ?? match[4] + }; + } + + const module_extension = module_extensions.find((ext) => file.endsWith(ext)); + if (module_extension) { + const name = file.slice(0, -module_extension.length); + const pattern = + /^\+(?:(server)|(page(?:(@[a-zA-Z0-9_-]*))?(\.server)?)|(layout(?:(@[a-zA-Z0-9_-]*))?(\.server)?))$/; + const match = pattern.exec(name); + if (!match) { + throw new Error(`Files prefixed with + are reserved (saw ${project_relative})`); + } else if (match[3] || match[6]) { + throw new Error( + // prettier-ignore + `Only Svelte files can reference named layouts. Remove '${match[3] || match[6]}' from ${file} (at ${project_relative})` + ); + } + + const kind = match[1] || match[4] || match[7] ? 'server' : 'universal'; + + return { + kind, + is_page: !!match[2], + is_layout: !!match[5] + }; + } + + throw new Error(`Files and directories prefixed with + are reserved (saw ${project_relative})`); +} + +/** + * @param {string} needle + * @param {string} haystack + */ +function count_occurrences(needle, haystack) { + let count = 0; + for (let i = 0; i < haystack.length; i += 1) { + if (haystack[i] === needle) count += 1; + } + return count; +} + +/** @param {import('types').RouteData[]} routes */ +function prevent_conflicts(routes) { + /** @type {Map} */ + const lookup = new Map(); + + for (const route of routes) { + if (!route.leaf && !route.endpoint) continue; + + const normalized = normalize_route_id(route.id); + + // find all permutations created by optional parameters + const split = normalized.split(/<\?(.+?)>/g); + + let permutations = [/** @type {string} */ (split[0])]; + + // turn `x/[[optional]]/y` into `x/y` and `x/[required]/y` + for (let i = 1; i < split.length; i += 2) { + const matcher = split[i]; + const next = split[i + 1]; + + permutations = permutations.reduce((a, b) => { + a.push(b + next); + if (!(matcher === '*' && b.endsWith('//'))) a.push(b + `<${matcher}>${next}`); + return a; + }, /** @type {string[]} */ ([])); + } + + for (const permutation of permutations) { + // remove leading/trailing/duplicated slashes caused by prior + // manipulation of optional parameters and (groups) + const key = permutation + .replace(/\/{2,}/, '/') + .replace(/^\//, '') + .replace(/\/$/, ''); + + if (lookup.has(key)) { + throw new Error( + `The "${lookup.get(key)}" and "${route.id}" routes conflict with each other` + ); + } + + lookup.set(key, route.id); + } + } +} + +/** @param {string} id */ +function normalize_route_id(id) { + return ( + id + // remove groups + .replace(/(?<=^|\/)\(.+?\)(?=$|\/)/g, '') + + .replace(/\[[ux]\+([0-9a-f]+)\]/g, (_, x) => + String.fromCharCode(parseInt(x, 16)).replace(/\//g, '%2f') + ) + + // replace `[param]` with `<*>`, `[param=x]` with ``, and `[[param]]` with `` + .replace( + /\[(?:(\[)|(\.\.\.))?.+?(=.+?)?\]\]?/g, + (_, optional, rest, matcher) => `<${optional ? '?' : ''}${rest ?? ''}${matcher ?? '*'}>` + ) + ); +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/sort.js b/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/sort.js new file mode 100644 index 0000000..9addd2c --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/sort.js @@ -0,0 +1,161 @@ +import { get_route_segments } from '../../../utils/routing.js'; + +/** + * @typedef {{ + * type: 'static' | 'required' | 'optional' | 'rest'; + * content: string; + * matched: boolean; + * }} Part + */ + +/** + * @typedef {Part[]} Segment + */ + +const EMPTY = { type: 'static', content: '', matched: false }; + +/** @param {import('types').RouteData[]} routes */ +export function sort_routes(routes) { + /** @type {Map} */ + const segment_cache = new Map(); + + /** @param {string} segment */ + function get_parts(segment) { + if (!segment_cache.has(segment)) { + segment_cache.set(segment, split(segment)); + } + + return segment_cache.get(segment); + } + + /** @param {string} id */ + function split(id) { + /** @type {Part[]} */ + const parts = []; + + let i = 0; + while (i <= id.length) { + const start = id.indexOf('[', i); + if (start === -1) { + parts.push({ type: 'static', content: id.slice(i), matched: false }); + break; + } + + parts.push({ type: 'static', content: id.slice(i, start), matched: false }); + + const type = id[start + 1] === '[' ? 'optional' : id[start + 1] === '.' ? 'rest' : 'required'; + const delimiter = type === 'optional' ? ']]' : ']'; + const end = id.indexOf(delimiter, start); + + if (end === -1) { + throw new Error(`Invalid route ID ${id}`); + } + + const content = id.slice(start, (i = end + delimiter.length)); + + parts.push({ + type, + content, + matched: content.includes('=') + }); + } + + return parts; + } + + return routes.sort((route_a, route_b) => { + const segments_a = split_route_id(route_a.id).map(get_parts); + const segments_b = split_route_id(route_b.id).map(get_parts); + + for (let i = 0; i < Math.max(segments_a.length, segments_b.length); i += 1) { + const segment_a = segments_a[i] ?? [EMPTY]; + const segment_b = segments_b[i] ?? [EMPTY]; + + for (let j = 0; j < Math.max(segment_a.length, segment_b.length); j += 1) { + const a = segment_a[j]; + const b = segment_b[j]; + + // first part of each segment is always static + // (though it may be the empty string), then + // it alternates between dynamic and static + // (i.e. [foo][bar] is disallowed) + const dynamic = j % 2 === 1; + + if (dynamic) { + if (!a) return -1; + if (!b) return +1; + + // get the next static chunk, so we can handle [...rest] edge cases + const next_a = segment_a[j + 1].content || segments_a[i + 1]?.[0].content; + const next_b = segment_b[j + 1].content || segments_b[i + 1]?.[0].content; + + // `[...rest]/x` outranks `[...rest]` + if (a.type === 'rest' && b.type === 'rest') { + if (next_a && next_b) continue; + if (next_a) return -1; + if (next_b) return +1; + } + + // `[...rest]/x` outranks `[required]` or `[required]/[required]` + // but not `[required]/x` + if (a.type === 'rest') { + return next_a && !next_b ? -1 : +1; + } + + if (b.type === 'rest') { + return next_b && !next_a ? +1 : -1; + } + + // part with matcher outranks one without + if (a.matched !== b.matched) { + return a.matched ? -1 : +1; + } + + if (a.type !== b.type) { + // `[...rest]` has already been accounted for, so here + // we're comparing between `[required]` and `[[optional]]` + if (a.type === 'required') return -1; + if (b.type === 'required') return +1; + } + } else if (a.content !== b.content) { + // shallower path outranks deeper path + if (a === EMPTY) return -1; + if (b === EMPTY) return +1; + + return sort_static(a.content, b.content); + } + } + } + + return route_a.id < route_b.id ? +1 : -1; + }); +} + +/** @param {string} id */ +function split_route_id(id) { + return get_route_segments( + id + // remove all [[optional]] parts unless they're at the very end + .replace(/\[\[[^\]]+\]\](?!$)/g, '') + ).filter(Boolean); +} + +/** + * Sort two strings lexicographically, except `foobar` outranks `foo` + * @param {string} a + * @param {string} b + */ +function sort_static(a, b) { + if (a === b) return 0; + + for (let i = 0; true; i += 1) { + const char_a = a[i]; + const char_b = b[i]; + + if (char_a !== char_b) { + if (char_a === undefined) return +1; + if (char_b === undefined) return -1; + return char_a < char_b ? -1 : +1; + } + } +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/types.d.ts b/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/types.d.ts new file mode 100644 index 0000000..ec5c01b --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/create_manifest_data/types.d.ts @@ -0,0 +1,37 @@ +import { PageNode } from 'types'; + +interface Part { + dynamic: boolean; + optional: boolean; + rest: boolean; + type: string | null; +} + +interface RouteTreeNode { + error: PageNode | undefined; + layout: PageNode | undefined; +} + +export type RouteTree = Map; + +interface RouteComponent { + kind: 'component'; + is_page: boolean; + is_layout: boolean; + is_error: boolean; + uses_layout: string | undefined; +} + +interface RouteSharedModule { + kind: 'universal'; + is_page: boolean; + is_layout: boolean; +} + +interface RouteServerModule { + kind: 'server'; + is_page: boolean; + is_layout: boolean; +} + +export type RouteFile = RouteComponent | RouteSharedModule | RouteServerModule; diff --git a/node_modules/@sveltejs/kit/src/core/sync/sync.js b/node_modules/@sveltejs/kit/src/core/sync/sync.js new file mode 100644 index 0000000..3d1f0f9 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/sync.js @@ -0,0 +1,78 @@ +import path from 'node:path'; +import create_manifest_data from './create_manifest_data/index.js'; +import { write_client_manifest } from './write_client_manifest.js'; +import { write_root } from './write_root.js'; +import { write_tsconfig } from './write_tsconfig.js'; +import { write_types, write_all_types } from './write_types/index.js'; +import { write_ambient } from './write_ambient.js'; +import { write_server } from './write_server.js'; + +/** + * Initialize SvelteKit's generated files. + * @param {import('types').ValidatedConfig} config + * @param {string} mode + */ +export function init(config, mode) { + write_tsconfig(config.kit); + write_ambient(config.kit, mode); +} + +/** + * Update SvelteKit's generated files + * @param {import('types').ValidatedConfig} config + */ +export async function create(config) { + const manifest_data = create_manifest_data({ config }); + + const output = path.join(config.kit.outDir, 'generated'); + + write_client_manifest(config.kit, manifest_data, `${output}/client`); + write_server(config, output); + write_root(manifest_data, output); + await write_all_types(config, manifest_data); + + return { manifest_data }; +} + +/** + * Update SvelteKit's generated files in response to a single file content update. + * Do not call this when the file in question was created/deleted. + * + * @param {import('types').ValidatedConfig} config + * @param {import('types').ManifestData} manifest_data + * @param {string} file + */ +export async function update(config, manifest_data, file) { + await write_types(config, manifest_data, file); + + return { manifest_data }; +} + +/** + * Run sync.init and sync.create in series, returning the result from sync.create. + * @param {import('types').ValidatedConfig} config + * @param {string} mode The Vite mode + */ +export async function all(config, mode) { + init(config, mode); + return await create(config); +} + +/** + * Run sync.init and then generate all type files. + * @param {import('types').ValidatedConfig} config + * @param {string} mode The Vite mode + */ +export async function all_types(config, mode) { + init(config, mode); + const manifest_data = create_manifest_data({ config }); + await write_all_types(config, manifest_data); +} + +/** + * Regenerate __SERVER__/internal.js in response to src/{app.html,error.html,service-worker.js} changing + * @param {import('types').ValidatedConfig} config + */ +export function server(config) { + write_server(config, path.join(config.kit.outDir, 'generated')); +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/ts.js b/node_modules/@sveltejs/kit/src/core/sync/ts.js new file mode 100644 index 0000000..61c79e3 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/ts.js @@ -0,0 +1,6 @@ +/** @type {import('typescript')} */ +// @ts-ignore +export let ts = undefined; +try { + ts = (await import('typescript')).default; +} catch {} diff --git a/node_modules/@sveltejs/kit/src/core/sync/utils.js b/node_modules/@sveltejs/kit/src/core/sync/utils.js new file mode 100644 index 0000000..0e01813 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/utils.js @@ -0,0 +1,70 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { mkdirp } from '../../utils/filesystem.js'; + +/** @type {Map} */ +const previous_contents = new Map(); + +/** + * @param {string} file + * @param {string} code + */ +export function write_if_changed(file, code) { + if (code !== previous_contents.get(file)) { + write(file, code); + } +} + +/** + * @param {string} file + * @param {string} code + */ +export function write(file, code) { + previous_contents.set(file, code); + mkdirp(path.dirname(file)); + fs.writeFileSync(file, code); +} + +/** @type {WeakMap} */ +const dedent_map = new WeakMap(); + +/** + * Allows indenting template strings without the extra indentation ending up in the result. + * Still allows indentation of lines relative to one another in the template string. + * @param {TemplateStringsArray} strings + * @param {any[]} values + */ +export function dedent(strings, ...values) { + let dedented = dedent_map.get(strings); + + if (!dedented) { + const indentation = /** @type {RegExpExecArray} */ (/\n?([ \t]*)/.exec(strings[0]))[1]; + const pattern = new RegExp(`^${indentation}`, 'gm'); + + dedented = { + strings: strings.map((str) => str.replace(pattern, '')), + indents: [] + }; + + let current = '\n'; + + for (let i = 0; i < values.length; i += 1) { + const string = dedented.strings[i]; + const match = /\n([ \t]*)$/.exec(string); + + if (match) current = match[0]; + dedented.indents[i] = current; + } + + dedent_map.set(strings, dedented); + } + + let str = dedented.strings[0]; + for (let i = 0; i < values.length; i += 1) { + str += String(values[i]).replace(/\n/g, dedented.indents[i]) + dedented.strings[i + 1]; + } + + str = str.trim(); + + return str; +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/write_ambient.js b/node_modules/@sveltejs/kit/src/core/sync/write_ambient.js new file mode 100644 index 0000000..40a871c --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/write_ambient.js @@ -0,0 +1,63 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { get_env } from '../../exports/vite/utils.js'; +import { GENERATED_COMMENT } from '../../constants.js'; +import { create_dynamic_types, create_static_types } from '../env.js'; +import { write_if_changed } from './utils.js'; + +// TODO these types should be described in a neutral place, rather than +// inside either `packages/kit` or `kit.svelte.dev` +const descriptions_dir = fileURLToPath(new URL('../../../src/types/synthetic', import.meta.url)); + +/** @param {string} filename */ +function read_description(filename) { + const content = fs.readFileSync(`${descriptions_dir}/${filename}`, 'utf8'); + return `/**\n${content + .trim() + .split('\n') + .map((line) => ` * ${line}`) + .join('\n')}\n */`; +} + +/** + * @param {import('types').Env} env + * @param {{ + * public_prefix: string; + * private_prefix: string; + * }} prefixes + */ +const template = (env, prefixes) => ` +${GENERATED_COMMENT} + +/// + +${read_description('$env+static+private.md')} +${create_static_types('private', env)} + +${read_description('$env+static+public.md')} +${create_static_types('public', env)} + +${read_description('$env+dynamic+private.md')} +${create_dynamic_types('private', env, prefixes)} + +${read_description('$env+dynamic+public.md')} +${create_dynamic_types('public', env, prefixes)} +`; + +/** + * Writes ambient declarations including types reference to @sveltejs/kit, + * and the existing environment variables in process.env to + * $env/static/private and $env/static/public + * @param {import('types').ValidatedKitConfig} config + * @param {string} mode The Vite mode + */ +export function write_ambient(config, mode) { + const env = get_env(config.env, mode); + const { publicPrefix: public_prefix, privatePrefix: private_prefix } = config.env; + + write_if_changed( + path.join(config.outDir, 'ambient.d.ts'), + template(env, { public_prefix, private_prefix }) + ); +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/write_client_manifest.js b/node_modules/@sveltejs/kit/src/core/sync/write_client_manifest.js new file mode 100644 index 0000000..623dbf4 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/write_client_manifest.js @@ -0,0 +1,153 @@ +import { relative_path, resolve_entry } from '../../utils/filesystem.js'; +import { s } from '../../utils/misc.js'; +import { dedent, write_if_changed } from './utils.js'; + +/** + * Writes the client manifest to disk. The manifest is used to power the router. It contains the + * list of routes and corresponding Svelte components (i.e. pages and layouts). + * @param {import('types').ValidatedKitConfig} kit + * @param {import('types').ManifestData} manifest_data + * @param {string} output + * @param {Array<{ has_server_load: boolean }>} [metadata] + */ +export function write_client_manifest(kit, manifest_data, output, metadata) { + /** + * Creates a module that exports a `CSRPageNode` + * @param {import('types').PageNode} node + */ + function generate_node(node) { + const declarations = []; + + if (node.universal) { + declarations.push( + `import * as universal from ${s(relative_path(`${output}/nodes`, node.universal))};`, + 'export { universal };' + ); + } + + if (node.component) { + declarations.push( + `export { default as component } from ${s( + relative_path(`${output}/nodes`, node.component) + )};` + ); + } + + return declarations.join('\n'); + } + + /** @type {Map} */ + const indices = new Map(); + const nodes = manifest_data.nodes + .map((node, i) => { + indices.set(node, i); + + write_if_changed(`${output}/nodes/${i}.js`, generate_node(node)); + return `() => import('./nodes/${i}')`; + }) + .join(',\n'); + + const layouts_with_server_load = new Set(); + + const dictionary = dedent` + { + ${manifest_data.routes + .map((route) => { + if (route.page) { + const errors = route.page.errors.slice(1).map((n) => n ?? ''); + const layouts = route.page.layouts.slice(1).map((n) => n ?? ''); + + while (layouts.at(-1) === '') layouts.pop(); + while (errors.at(-1) === '') errors.pop(); + + let leaf_has_server_load = false; + if (route.leaf) { + if (metadata) { + const i = /** @type {number} */ (indices.get(route.leaf)); + + leaf_has_server_load = metadata[i].has_server_load; + } else if (route.leaf.server) { + leaf_has_server_load = true; + } + } + + // Encode whether or not the route uses server data + // using the ones' complement, to save space + const array = [`${leaf_has_server_load ? '~' : ''}${route.page.leaf}`]; + + // Encode whether or not the layout uses server data. + // It's a different method compared to pages because layouts + // are reused across pages, so we save space by doing it this way. + route.page.layouts.forEach((layout) => { + if (layout == undefined) return; + + let layout_has_server_load = false; + + if (metadata) { + layout_has_server_load = metadata[layout].has_server_load; + } else if (manifest_data.nodes[layout].server) { + layout_has_server_load = true; + } + + if (layout_has_server_load) { + layouts_with_server_load.add(layout); + } + }); + + // only include non-root layout/error nodes if they exist + if (layouts.length > 0 || errors.length > 0) array.push(`[${layouts.join(',')}]`); + if (errors.length > 0) array.push(`[${errors.join(',')}]`); + + return `${s(route.id)}: [${array.join(',')}]`; + } + }) + .filter(Boolean) + .join(',\n')} + } + `; + + const hooks_file = resolve_entry(kit.files.hooks.client); + + write_if_changed( + `${output}/app.js`, + dedent` + ${hooks_file ? `import * as client_hooks from '${relative_path(output, hooks_file)}';` : ''} + + export { matchers } from './matchers.js'; + + export const nodes = [ + ${nodes} + ]; + + export const server_loads = [${[...layouts_with_server_load].join(',')}]; + + export const dictionary = ${dictionary}; + + export const hooks = { + handleError: ${ + hooks_file ? 'client_hooks.handleError || ' : '' + }(({ error }) => { console.error(error) }), + }; + + export { default as root } from '../root.svelte'; + ` + ); + + // write matchers to a separate module so that we don't + // need to worry about name conflicts + const imports = []; + const matchers = []; + + for (const key in manifest_data.matchers) { + const src = manifest_data.matchers[key]; + + imports.push(`import { match as ${key} } from ${s(relative_path(output, src))};`); + matchers.push(key); + } + + const module = imports.length + ? `${imports.join('\n')}\n\nexport const matchers = { ${matchers.join(', ')} };` + : 'export const matchers = {};'; + + write_if_changed(`${output}/matchers.js`, module); +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/write_root.js b/node_modules/@sveltejs/kit/src/core/sync/write_root.js new file mode 100644 index 0000000..04caa81 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/write_root.js @@ -0,0 +1,92 @@ +import { dedent, write_if_changed } from './utils.js'; + +/** + * @param {import('types').ManifestData} manifest_data + * @param {string} output + */ +export function write_root(manifest_data, output) { + // TODO remove default layout altogether + + const max_depth = Math.max( + ...manifest_data.routes.map((route) => + route.page ? route.page.layouts.filter(Boolean).length + 1 : 0 + ), + 1 + ); + + const levels = []; + for (let i = 0; i <= max_depth; i += 1) { + levels.push(i); + } + + let l = max_depth; + + let pyramid = ``; + + while (l--) { + pyramid = dedent` + {#if constructors[${l + 1}]} + + ${pyramid} + + {:else} + + {/if} + `; + } + + write_if_changed( + `${output}/root.svelte`, + dedent` + + + + ${pyramid} + + {#if mounted} +
+ {#if navigated} + {title} + {/if} +
+ {/if} + ` + ); +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/write_server.js b/node_modules/@sveltejs/kit/src/core/sync/write_server.js new file mode 100644 index 0000000..71ff99a --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/write_server.js @@ -0,0 +1,99 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { hash } from '../../runtime/hash.js'; +import { posixify, resolve_entry } from '../../utils/filesystem.js'; +import { s } from '../../utils/misc.js'; +import { load_error_page, load_template } from '../config/index.js'; +import { runtime_directory } from '../utils.js'; +import { write_if_changed } from './utils.js'; + +/** + * @param {{ + * hooks: string | null; + * config: import('types').ValidatedConfig; + * has_service_worker: boolean; + * runtime_directory: string; + * template: string; + * error_page: string; + * }} opts + */ +const server_template = ({ + config, + hooks, + has_service_worker, + runtime_directory, + template, + error_page +}) => ` +import root from '../root.svelte'; +import { set_building } from '__sveltekit/environment'; +import { set_assets } from '__sveltekit/paths'; +import { set_private_env, set_public_env } from '${runtime_directory}/shared-server.js'; + +export const options = { + app_template_contains_nonce: ${template.includes('%sveltekit.nonce%')}, + csp: ${s(config.kit.csp)}, + csrf_check_origin: ${s(config.kit.csrf.checkOrigin)}, + track_server_fetches: ${s(config.kit.dangerZone.trackServerFetches)}, + embedded: ${config.kit.embedded}, + env_public_prefix: '${config.kit.env.publicPrefix}', + env_private_prefix: '${config.kit.env.privatePrefix}', + hooks: null, // added lazily, via \`get_hooks\` + preload_strategy: ${s(config.kit.output.preloadStrategy)}, + root, + service_worker: ${has_service_worker}, + templates: { + app: ({ head, body, assets, nonce, env }) => ${s(template) + .replace('%sveltekit.head%', '" + head + "') + .replace('%sveltekit.body%', '" + body + "') + .replace(/%sveltekit\.assets%/g, '" + assets + "') + .replace(/%sveltekit\.nonce%/g, '" + nonce + "') + .replace( + /%sveltekit\.env\.([^%]+)%/g, + (_match, capture) => `" + (env[${s(capture)}] ?? "") + "` + )}, + error: ({ status, message }) => ${s(error_page) + .replace(/%sveltekit\.status%/g, '" + status + "') + .replace(/%sveltekit\.error\.message%/g, '" + message + "')} + }, + version_hash: ${s(hash(config.kit.version.name))} +}; + +export function get_hooks() { + return ${hooks ? `import(${s(hooks)})` : '{}'}; +} + +export { set_assets, set_building, set_private_env, set_public_env }; +`; + +// TODO need to re-run this whenever src/app.html or src/error.html are +// created or changed, or src/service-worker.js is created or deleted. +// Also, need to check that updating hooks.server.js works + +/** + * Write server configuration to disk + * @param {import('types').ValidatedConfig} config + * @param {string} output + */ +export function write_server(config, output) { + // TODO the casting shouldn't be necessary — investigate + const hooks_file = /** @type {string} */ (resolve_entry(config.kit.files.hooks.server)); + + /** @param {string} file */ + function relative(file) { + return posixify(path.relative(`${output}/server`, file)); + } + + write_if_changed( + `${output}/server/internal.js`, + server_template({ + config, + hooks: fs.existsSync(hooks_file) ? relative(hooks_file) : null, + has_service_worker: + config.kit.serviceWorker.register && !!resolve_entry(config.kit.files.serviceWorker), + runtime_directory: relative(runtime_directory), + template: load_template(process.cwd(), config), + error_page: load_error_page(config) + }) + ); +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/write_tsconfig.js b/node_modules/@sveltejs/kit/src/core/sync/write_tsconfig.js new file mode 100644 index 0000000..9f3a083 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/write_tsconfig.js @@ -0,0 +1,275 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import colors from 'kleur'; +import { posixify } from '../../utils/filesystem.js'; +import { write_if_changed } from './utils.js'; +import { ts } from './ts.js'; + +/** + * @param {string} cwd + * @param {string} file + */ +function maybe_file(cwd, file) { + const resolved = path.resolve(cwd, file); + if (fs.existsSync(resolved)) { + return resolved; + } +} + +/** + * @param {string} file + */ +function project_relative(file) { + return posixify(path.relative('.', file)); +} + +/** + * @param {string} file + */ +function remove_trailing_slashstar(file) { + if (file.endsWith('/*')) { + return file.slice(0, -2); + } else { + return file; + } +} + +/** + * Generates the tsconfig that the user's tsconfig inherits from. + * @param {import('types').ValidatedKitConfig} kit + */ +export function write_tsconfig(kit, cwd = process.cwd()) { + const out = path.join(kit.outDir, 'tsconfig.json'); + + const user_config = load_user_tsconfig(cwd); + if (user_config) validate_user_config(kit, cwd, out, user_config); + + // only specify baseUrl if a) the user doesn't specify their own baseUrl + // and b) they have non-relative paths. this causes problems with auto-imports, + // so we print a suggestion that they use relative paths instead + // TODO(v2): never include base URL, and skip the check below + let include_base_url = false; + + if (user_config && !user_config.options.compilerOptions?.baseUrl) { + const non_relative_paths = new Set(); + for (const paths of Object.values(user_config?.options.compilerOptions?.paths || {})) { + for (const path of paths) { + if (!path.startsWith('.')) non_relative_paths.add(path); + } + } + + if (non_relative_paths.size) { + include_base_url = true; + + console.log(colors.bold().yellow('Please replace non-relative compilerOptions.paths:\n')); + + for (const path of non_relative_paths) { + console.log(` - "${path}" -> "./${path}"`); + } + + console.log( + '\nDoing so allows us to omit "baseUrl" — which causes problems with imports — from the generated tsconfig.json. See https://github.com/sveltejs/kit/pull/8437 for more information.' + ); + } + } + + write_if_changed(out, JSON.stringify(get_tsconfig(kit, include_base_url), null, '\t')); +} + +/** + * Generates the tsconfig that the user's tsconfig inherits from. + * @param {import('types').ValidatedKitConfig} kit + * @param {boolean} include_base_url + */ +export function get_tsconfig(kit, include_base_url) { + /** @param {string} file */ + const config_relative = (file) => posixify(path.relative(kit.outDir, file)); + + const include = new Set([ + 'ambient.d.ts', + './types/**/$types.d.ts', + config_relative('vite.config.ts') + ]); + // TODO(v2): find a better way to include all src files. We can't just use routes/lib only because + // people might have other folders/files in src that they want included. + const src_includes = [kit.files.routes, kit.files.lib, path.resolve('src')].filter((dir) => { + const relative = path.relative(path.resolve('src'), dir); + return !relative || relative.startsWith('..'); + }); + for (const dir of src_includes) { + include.add(config_relative(`${dir}/**/*.js`)); + include.add(config_relative(`${dir}/**/*.ts`)); + include.add(config_relative(`${dir}/**/*.svelte`)); + } + + // Test folder is a special case - we advocate putting tests in a top-level test folder + // and it's not configurable (should we make it?) + const test_folder = project_relative('tests'); + include.add(config_relative(`${test_folder}/**/*.js`)); + include.add(config_relative(`${test_folder}/**/*.ts`)); + include.add(config_relative(`${test_folder}/**/*.svelte`)); + + const exclude = [config_relative('node_modules/**'), './[!ambient.d.ts]**']; + if (path.extname(kit.files.serviceWorker)) { + exclude.push(config_relative(kit.files.serviceWorker)); + } else { + exclude.push(config_relative(`${kit.files.serviceWorker}.js`)); + exclude.push(config_relative(`${kit.files.serviceWorker}.ts`)); + exclude.push(config_relative(`${kit.files.serviceWorker}.d.ts`)); + } + + const config = { + compilerOptions: { + // generated options + baseUrl: include_base_url ? config_relative('.') : undefined, + paths: get_tsconfig_paths(kit, include_base_url), + rootDirs: [config_relative('.'), './types'], + + // essential options + // svelte-preprocess cannot figure out whether you have a value or a type, so tell TypeScript + // to enforce using \`import type\` instead of \`import\` for Types. + importsNotUsedAsValues: 'error', + // Vite compiles modules one at a time + isolatedModules: true, + // TypeScript doesn't know about import usages in the template because it only sees the + // script of a Svelte file. Therefore preserve all value imports. Requires TS 4.5 or higher. + preserveValueImports: true, + + // This is required for svelte-package to work as expected + // Can be overwritten + lib: ['esnext', 'DOM', 'DOM.Iterable'], + moduleResolution: 'node', + module: 'esnext', + target: 'esnext', + + // TODO(v2): use the new flag verbatimModuleSyntax instead (requires support by Vite/Esbuild) + ignoreDeprecations: ts && Number(ts.version.split('.')[0]) >= 5 ? '5.0' : undefined + }, + include: [...include], + exclude + }; + + return kit.typescript.config(config) ?? config; +} + +/** @param {string} cwd */ +function load_user_tsconfig(cwd) { + const file = maybe_file(cwd, 'tsconfig.json') || maybe_file(cwd, 'jsconfig.json'); + + if (!file) return; + + // we have to eval the file, since it's not parseable as JSON (contains comments) + const json = fs.readFileSync(file, 'utf-8'); + + return { + kind: path.basename(file), + options: (0, eval)(`(${json})`) + }; +} + +/** + * @param {import('types').ValidatedKitConfig} kit + * @param {string} cwd + * @param {string} out + * @param {{ kind: string, options: any }} config + */ +function validate_user_config(kit, cwd, out, config) { + // we need to check that the user's tsconfig extends the framework config + const extend = config.options.extends; + const extends_framework_config = + typeof extend === 'string' + ? path.resolve(cwd, extend) === out + : Array.isArray(extend) + ? extend.some((e) => path.resolve(cwd, e) === out) + : false; + + const options = config.options.compilerOptions || {}; + + if (extends_framework_config) { + const { paths: user_paths } = options; + + if (user_paths && fs.existsSync(kit.files.lib)) { + /** @type {string[]} */ + const lib = user_paths['$lib'] || []; + /** @type {string[]} */ + const lib_ = user_paths['$lib/*'] || []; + + // TODO(v2): check needs to be adjusted when we remove the base path + const missing_lib_paths = + !lib.some((relative) => path.resolve(cwd, relative) === kit.files.lib) || + !lib_.some((relative) => path.resolve(cwd, relative) === path.join(kit.files.lib, '/*')); + + if (missing_lib_paths) { + console.warn( + colors + .bold() + .yellow(`Your compilerOptions.paths in ${config.kind} should include the following:`) + ); + let relative = posixify(path.relative('.', kit.files.lib)); + if (!relative.startsWith('.')) relative = `./${relative}`; + console.warn(`{\n "$lib":["${relative}"],\n "$lib/*":["${relative}/*"]\n}`); + } + } + } else { + let relative = posixify(path.relative('.', out)); + if (!relative.startsWith('./')) relative = './' + relative; + + console.warn( + colors + .bold() + .yellow(`Your ${config.kind} should extend the configuration generated by SvelteKit:`) + ); + console.warn(`{\n "extends": "${relative}"\n}`); + } +} + +// +const alias_regex = /^(.+?)(\/\*)?$/; +// +const value_regex = /^(.*?)((\/\*)|(\.\w+))?$/; + +/** + * Generates tsconfig path aliases from kit's aliases. + * Related to vite alias creation. + * + * @param {import('types').ValidatedKitConfig} config + * @param {boolean} include_base_url + */ +function get_tsconfig_paths(config, include_base_url) { + /** @param {string} file */ + const config_relative = (file) => posixify(path.relative(config.outDir, file)); + + const alias = { ...config.alias }; + if (fs.existsSync(project_relative(config.files.lib))) { + alias['$lib'] = project_relative(config.files.lib); + } + + /** @type {Record} */ + const paths = {}; + + for (const [key, value] of Object.entries(alias)) { + const key_match = alias_regex.exec(key); + if (!key_match) throw new Error(`Invalid alias key: ${key}`); + + const value_match = value_regex.exec(value); + if (!value_match) throw new Error(`Invalid alias value: ${value}`); + + const rel_path = (include_base_url ? project_relative : config_relative)( + remove_trailing_slashstar(value) + ); + const slashstar = key_match[2]; + + if (slashstar) { + paths[key] = [rel_path + '/*']; + } else { + paths[key] = [rel_path]; + const fileending = value_match[4]; + + if (!fileending && !(key + '/*' in alias)) { + paths[key + '/*'] = [rel_path + '/*']; + } + } + } + + return paths; +} diff --git a/node_modules/@sveltejs/kit/src/core/sync/write_types/index.js b/node_modules/@sveltejs/kit/src/core/sync/write_types/index.js new file mode 100644 index 0000000..e5f9afb --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/sync/write_types/index.js @@ -0,0 +1,822 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import MagicString from 'magic-string'; +import { posixify, rimraf, walk } from '../../../utils/filesystem.js'; +import { compact } from '../../../utils/array.js'; +import { ts } from '../ts.js'; + +/** + * @typedef {{ + * file_name: string; + * modified: boolean; + * code: string; + * exports: any[]; + * } | null} Proxy + * + * @typedef {{ + * server: Proxy, + * universal: Proxy + * }} Proxies + * + * @typedef {Map} RoutesMap + */ + +const cwd = process.cwd(); + +/** + * Creates types for the whole manifest + * @param {import('types').ValidatedConfig} config + * @param {import('types').ManifestData} manifest_data + */ +export async function write_all_types(config, manifest_data) { + if (!ts) return; + + const types_dir = `${config.kit.outDir}/types`; + + // empty out files that no longer need to exist + const routes_dir = posixify(path.relative('.', config.kit.files.routes)).replace(/\.\.\//g, ''); + const expected_directories = new Set( + manifest_data.routes.map((route) => path.join(routes_dir, route.id)) + ); + + if (fs.existsSync(types_dir)) { + for (const file of walk(types_dir)) { + const dir = path.dirname(file); + if (!expected_directories.has(dir)) { + rimraf(path.join(types_dir, file)); + } + } + } + + // Read/write meta data on each invocation, not once per node process, + // it could be invoked by another process in the meantime. + const meta_data_file = `${types_dir}/route_meta_data.json`; + const has_meta_data = fs.existsSync(meta_data_file); + const meta_data = has_meta_data + ? /** @type {Record} */ (JSON.parse(fs.readFileSync(meta_data_file, 'utf-8'))) + : {}; + const routes_map = create_routes_map(manifest_data); + // For each directory, write $types.d.ts + for (const route of manifest_data.routes) { + if (!route.leaf && !route.layout && !route.endpoint) continue; // nothing to do + + const outdir = path.join(config.kit.outDir, 'types', routes_dir, route.id); + + // check if the types are out of date + /** @type {string[]} */ + const input_files = []; + + /** @type {import('types').PageNode | null} */ + let node = route.leaf; + while (node) { + if (node.universal) input_files.push(node.universal); + if (node.server) input_files.push(node.server); + node = node.parent ?? null; + } + + /** @type {import('types').PageNode | null} */ + node = route.layout; + while (node) { + if (node.universal) input_files.push(node.universal); + if (node.server) input_files.push(node.server); + node = node.parent ?? null; + } + + if (route.endpoint) { + input_files.push(route.endpoint.file); + } + + try { + fs.mkdirSync(outdir, { recursive: true }); + } catch {} + + const output_files = compact( + fs.readdirSync(outdir).map((name) => { + const stats = fs.statSync(path.join(outdir, name)); + if (stats.isDirectory()) return; + return { + name, + updated: stats.mtimeMs + }; + }) + ); + + const source_last_updated = Math.max( + // ctimeMs includes move operations whereas mtimeMs does not + ...input_files.map((file) => fs.statSync(file).ctimeMs) + ); + const types_last_updated = Math.max(...output_files.map((file) => file.updated)); + + const should_generate = + // source files were generated more recently than the types + source_last_updated > types_last_updated || + // no meta data file exists yet + !has_meta_data || + // some file was deleted + !meta_data[route.id]?.every((file) => input_files.includes(file)); + + if (should_generate) { + // track which old files end up being surplus to requirements + const to_delete = new Set(output_files.map((file) => file.name)); + update_types(config, routes_map, route, to_delete); + meta_data[route.id] = input_files; + } + } + + fs.writeFileSync(meta_data_file, JSON.stringify(meta_data, null, '\t')); +} + +/** + * Creates types related to the given file. This should only be called + * if the file in question was edited, not if it was created/deleted/moved. + * @param {import('types').ValidatedConfig} config + * @param {import('types').ManifestData} manifest_data + * @param {string} file + */ +export async function write_types(config, manifest_data, file) { + if (!ts) return; + + if (!path.basename(file).startsWith('+')) { + // Not a route file + return; + } + + const id = '/' + posixify(path.relative(config.kit.files.routes, path.dirname(file))); + + const route = manifest_data.routes.find((route) => route.id === id); + if (!route) return; + if (!route.leaf && !route.layout && !route.endpoint) return; // nothing to do + + update_types(config, create_routes_map(manifest_data), route); +} + +/** + * Collect all leafs into a leaf -> route map + * @param {import('types').ManifestData} manifest_data + */ +function create_routes_map(manifest_data) { + /** @type {RoutesMap} */ + const map = new Map(); + for (const route of manifest_data.routes) { + if (route.leaf) { + map.set(route.leaf, { route, proxies: { server: null, universal: null } }); + } + } + return map; +} + +/** + * Update types for a specific route + * @param {import('types').ValidatedConfig} config + * @param {RoutesMap} routes + * @param {import('types').RouteData} route + * @param {Set} [to_delete] + */ +function update_types(config, routes, route, to_delete = new Set()) { + const routes_dir = posixify(path.relative('.', config.kit.files.routes)).replace(/\.\.\//g, ''); + const outdir = path.join(config.kit.outDir, 'types', routes_dir, route.id); + + // now generate new types + const imports = ["import type * as Kit from '@sveltejs/kit';"]; + + /** @type {string[]} */ + const declarations = []; + + /** @type {string[]} */ + const exports = []; + + // add 'Expand' helper + // Makes sure a type is "repackaged" and therefore more readable + declarations.push('type Expand = T extends infer O ? { [K in keyof O]: O[K] } : never;'); + declarations.push( + `type RouteParams = { ${route.params + .map((param) => `${param.name}${param.optional ? '?' : ''}: string`) + .join('; ')} }` + ); + + if (route.params.length > 0) { + exports.push( + 'export type EntryGenerator = () => Promise> | Array;' + ); + } + + declarations.push(`type RouteId = '${route.id}';`); + + // These could also be placed in our public types, but it would bloat them unnecessarily and we may want to change these in the future + if (route.layout || route.leaf) { + declarations.push( + // If T extends the empty object, void is also allowed as a return type + 'type MaybeWithVoid = {} extends T ? T | void : T;', + + // Returns the key of the object whose values are required. + 'export type RequiredKeys = { [K in keyof T]-?: {} extends { [P in K]: T[K] } ? never : K; }[keyof T];', + + // Helper type to get the correct output type for load functions. It should be passed the parent type to check what types from App.PageData are still required. + // If none, void is also allowed as a return type. + 'type OutputDataShape = MaybeWithVoid> & Partial> & Record>', + + // null & {} == null, we need to prevent that in some situations + 'type EnsureDefined = T extends null | undefined ? {} : T;', + + // Takes a union type and returns a union type where each type also has all properties + // of all possible types (typed as undefined), making accessing them more ergonomic + 'type OptionalUnion, A extends keyof U = U extends U ? keyof U : never> = U extends unknown ? { [P in Exclude]?: never } & U : never;', + + // Re-export `Snapshot` from @sveltejs/kit — in future we could use this to infer from the return type of `snapshot.capture` + 'export type Snapshot = Kit.Snapshot;' + ); + } + + if (route.leaf) { + let route_info = routes.get(route.leaf); + if (!route_info) { + // This should be defined, but belts and braces + route_info = { route, proxies: { server: null, universal: null } }; + routes.set(route.leaf, route_info); + } + + const { + declarations: d, + exports: e, + proxies + } = process_node(route.leaf, outdir, true, route_info.proxies); + + exports.push(...e); + declarations.push(...d); + + if (proxies.server) { + route_info.proxies.server = proxies.server; + if (proxies.server?.modified) to_delete.delete(proxies.server.file_name); + } + if (proxies.universal) { + route_info.proxies.universal = proxies.universal; + if (proxies.universal?.modified) to_delete.delete(proxies.universal.file_name); + } + + if (route.leaf.server) { + exports.push( + 'export type Action | void = Record | void> = Kit.Action' + ); + exports.push( + 'export type Actions | void = Record | void> = Kit.Actions' + ); + } + } + + if (route.layout) { + let all_pages_have_load = true; + const layout_params = new Set(); + const ids = ['RouteId']; + + route.layout.child_pages?.forEach((page) => { + const leaf = routes.get(page); + if (leaf) { + if (leaf.route.page) ids.push(`"${leaf.route.id}"`); + + for (const param of leaf.route.params) { + layout_params.add(param.name); + } + + ensureProxies(page, leaf.proxies); + + if ( + // Be defensive - if a proxy doesn't exist (because it couldn't be created), assume a load function exists. + // If we didn't and it's a false negative, the user could wrongfully get a type error on layouts. + (leaf.proxies.server && !leaf.proxies.server.exports.includes('load')) || + (leaf.proxies.universal && !leaf.proxies.universal.exports.includes('load')) + ) { + all_pages_have_load = false; + } + } + if (!page.server && !page.universal) { + all_pages_have_load = false; + } + }); + + if (route.id === '/') { + // root layout is used for fallback error page, where ID can be null + ids.push('null'); + } + + declarations.push(`type LayoutRouteId = ${ids.join(' | ')}`); + + declarations.push( + `type LayoutParams = RouteParams & { ${Array.from(layout_params).map( + (param) => `${param}?: string` + )} }` + ); + + const { + exports: e, + declarations: d, + proxies + } = process_node( + route.layout, + outdir, + false, + { server: null, universal: null }, + all_pages_have_load + ); + + exports.push(...e); + declarations.push(...d); + + if (proxies.server?.modified) to_delete.delete(proxies.server.file_name); + if (proxies.universal?.modified) to_delete.delete(proxies.universal.file_name); + } + + if (route.endpoint) { + exports.push('export type RequestHandler = Kit.RequestHandler;'); + } + + if (route.leaf?.server || route.layout?.server || route.endpoint) { + exports.push('export type RequestEvent = Kit.RequestEvent;'); + } + + const output = [imports.join('\n'), declarations.join('\n'), exports.join('\n')] + .filter(Boolean) + .join('\n\n'); + + fs.writeFileSync(`${outdir}/$types.d.ts`, output); + to_delete.delete('$types.d.ts'); + + for (const file of to_delete) { + fs.unlinkSync(path.join(outdir, file)); + } +} + +/** + * @param {import('types').PageNode} node + * @param {string} outdir + * @param {boolean} is_page + * @param {Proxies} proxies + * @param {boolean} [all_pages_have_load] + */ +function process_node(node, outdir, is_page, proxies, all_pages_have_load = true) { + const params = `${is_page ? 'Route' : 'Layout'}Params`; + const prefix = is_page ? 'Page' : 'Layout'; + + const route_id = is_page ? 'RouteId' : 'LayoutRouteId'; + + /** @type {string[]} */ + const declarations = []; + /** @type {string[]} */ + const exports = []; + + /** @type {string} */ + let server_data; + /** @type {string} */ + let data; + + ensureProxies(node, proxies); + + if (node.server) { + const basename = path.basename(node.server); + const proxy = proxies.server; + if (proxy?.modified) { + fs.writeFileSync(`${outdir}/proxy${basename}`, proxy.code); + } + + server_data = get_data_type(node.server, 'null', proxy, true); + + const parent_type = `${prefix}ServerParentData`; + + declarations.push(`type ${parent_type} = ${get_parent_type(node, 'LayoutServerData')};`); + + // +page.js load present -> server can return all-optional data + const output_data_shape = + node.universal || (!is_page && all_pages_have_load) + ? 'Partial & Record | void' + : `OutputDataShape<${parent_type}>`; + exports.push( + `export type ${prefix}ServerLoad = Kit.ServerLoad<${params}, ${parent_type}, OutputData, ${route_id}>;` + ); + + exports.push(`export type ${prefix}ServerLoadEvent = Parameters<${prefix}ServerLoad>[0];`); + + if (is_page) { + let type = 'unknown'; + if (proxy && proxy.exports.includes('actions')) { + // If the file wasn't tweaked, we can use the return type of the original file. + // The advantage is that type updates are reflected without saving. + const from = proxy.modified + ? `./proxy${replace_ext_with_js(basename)}` + : path_to_original(outdir, node.server); + + exports.push( + 'type ExcludeActionFailure = T extends Kit.ActionFailure ? never : T extends void ? never : T;', + 'type ActionsSuccess any>> = { [Key in keyof T]: ExcludeActionFailure>>; }[keyof T];', + 'type ExtractActionFailure = T extends Kit.ActionFailure ? X extends void ? never : X : never;', + 'type ActionsFailure any>> = { [Key in keyof T]: Exclude>>, void>; }[keyof T];', + `type ActionsExport = typeof import('${from}').actions`, + 'export type SubmitFunction = Kit.SubmitFunction>, Expand>>' + ); + + type = 'Expand> | null'; + } + exports.push(`export type ActionData = ${type};`); + } + } else { + server_data = 'null'; + } + exports.push(`export type ${prefix}ServerData = ${server_data};`); + + const parent_type = `${prefix}ParentData`; + declarations.push(`type ${parent_type} = ${get_parent_type(node, 'LayoutData')};`); + + if (node.universal) { + const proxy = proxies.universal; + if (proxy?.modified) { + fs.writeFileSync(`${outdir}/proxy${path.basename(node.universal)}`, proxy.code); + } + + const type = get_data_type( + node.universal, + `${parent_type} & EnsureDefined<${prefix}ServerData>`, + proxy + ); + + data = `Expand & OptionalUnion>>`; + + const output_data_shape = + !is_page && all_pages_have_load + ? 'Partial & Record | void' + : `OutputDataShape<${parent_type}>`; + exports.push( + `export type ${prefix}Load = Kit.Load<${params}, ${prefix}ServerData, ${parent_type}, OutputData, ${route_id}>;` + ); + + exports.push(`export type ${prefix}LoadEvent = Parameters<${prefix}Load>[0];`); + } else if (server_data === 'null') { + data = `Expand<${parent_type}>`; + } else { + data = `Expand & EnsureDefined<${prefix}ServerData>>`; + } + + exports.push(`export type ${prefix}Data = ${data};`); + + return { declarations, exports, proxies }; + + /** + * @param {string} file_path + * @param {string} fallback + * @param {Proxy} proxy + * @param {boolean} expand + */ + function get_data_type(file_path, fallback, proxy, expand = false) { + if (proxy) { + if (proxy.exports.includes('load')) { + // If the file wasn't tweaked, we can use the return type of the original file. + // The advantage is that type updates are reflected without saving. + const from = proxy.modified + ? `./proxy${replace_ext_with_js(path.basename(file_path))}` + : path_to_original(outdir, file_path); + const type = `Kit.AwaitedProperties>>`; + return expand ? `Expand>>` : type; + } else { + return fallback; + } + } else { + return 'unknown'; + } + } +} + +/** + * This function populates the proxies object, if necessary and not already done. + * Proxies are used to tweak the code of a file before it's typechecked. + * They are needed in two places - when generating the types for a page or layout. + * To not do the same work twice, we generate the proxies once and pass them around. + * + * @param {import('types').PageNode} node + * @param {Proxies} proxies + */ +function ensureProxies(node, proxies) { + if (node.server && !proxies.server) { + proxies.server = createProxy(node.server, true); + } + + if (node.universal && !proxies.universal) { + proxies.universal = createProxy(node.universal, false); + } +} + +/** + * @param {string} file_path + * @param {boolean} is_server + * @returns {Proxy} + */ +function createProxy(file_path, is_server) { + const proxy = tweak_types(fs.readFileSync(file_path, 'utf8'), is_server); + if (proxy) { + return { + ...proxy, + file_name: `proxy${path.basename(file_path)}` + }; + } else { + return null; + } +} + +/** + * Get the parent type string by recursively looking up the parent layout and accumulate them to one type. + * @param {import('types').PageNode} node + * @param {string} type + */ +function get_parent_type(node, type) { + const parent_imports = []; + + let parent = node.parent; + + while (parent) { + const d = node.depth - parent.depth; + // unshift because we need it the other way round for the import string + parent_imports.unshift( + `${d === 0 ? '' : `import('${'../'.repeat(d)}${'$types.js'}').`}${type}` + ); + parent = parent.parent; + } + + let parent_str = `EnsureDefined<${parent_imports[0] || '{}'}>`; + for (let i = 1; i < parent_imports.length; i++) { + // Omit is necessary because a parent could have a property with the same key which would + // cause a type conflict. At runtime the child overwrites the parent property in this case, + // so reflect that in the type definition. + // EnsureDefined is necessary because {something: string} & null becomes null. + // Output types of server loads can be null but when passed in through the `parent` parameter they are the empty object instead. + parent_str = `Omit<${parent_str}, keyof ${parent_imports[i]}> & EnsureDefined<${parent_imports[i]}>`; + } + return parent_str; +} + +/** + * @param {string} outdir + * @param {string} file_path + */ +function path_to_original(outdir, file_path) { + return posixify(path.relative(outdir, path.join(cwd, replace_ext_with_js(file_path)))); +} + +/** + * @param {string} file_path + */ +function replace_ext_with_js(file_path) { + // Another extension than `.js` (or nothing, but that fails with node16 moduleResolution) + // will result in TS failing to lookup the file + const ext = path.extname(file_path); + return file_path.slice(0, -ext.length) + '.js'; +} + +/** + * @param {string} content + * @param {boolean} is_server + * @returns {Omit, 'file_name'> | null} + */ +export function tweak_types(content, is_server) { + const names = new Set(is_server ? ['load', 'actions'] : ['load']); + + try { + let modified = false; + + const ast = ts.createSourceFile( + 'filename.ts', + content, + ts.ScriptTarget.Latest, + false, + ts.ScriptKind.TS + ); + + const code = new MagicString(content); + + const exports = new Map(); + + ast.forEachChild((node) => { + if ( + ts.isExportDeclaration(node) && + node.exportClause && + ts.isNamedExports(node.exportClause) + ) { + node.exportClause.elements.forEach((element) => { + const exported = element.name; + if (names.has(element.name.text)) { + const local = element.propertyName || element.name; + exports.set(exported.text, local.text); + } + }); + } + + if ( + ts.canHaveModifiers(node) && + ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) + ) { + if (ts.isFunctionDeclaration(node) && node.name?.text && names.has(node.name?.text)) { + exports.set(node.name.text, node.name.text); + } + + if (ts.isVariableStatement(node)) { + node.declarationList.declarations.forEach((declaration) => { + if (ts.isIdentifier(declaration.name) && names.has(declaration.name.text)) { + exports.set(declaration.name.text, declaration.name.text); + } + }); + } + } + }); + + /** + * @param {import('typescript').Node} node + * @param {import('typescript').Node} value + */ + function replace_jsdoc_type_tags(node, value) { + let _modified = false; + // @ts-ignore + if (node.jsDoc) { + // @ts-ignore + for (const comment of node.jsDoc) { + for (const tag of comment.tags ?? []) { + if (ts.isJSDocTypeTag(tag)) { + const is_fn = + ts.isFunctionDeclaration(value) || + ts.isFunctionExpression(value) || + ts.isArrowFunction(value); + + if (is_fn && value.parameters?.length > 0) { + const name = ts.isIdentifier(value.parameters[0].name) + ? value.parameters[0].name.text + : 'event'; + code.overwrite(tag.tagName.pos, tag.tagName.end, 'param'); + code.prependRight(tag.typeExpression.pos + 1, 'Parameters<'); + code.appendLeft(tag.typeExpression.end - 1, '>[0]'); + code.appendLeft(tag.typeExpression.end, ` ${name}`); + } else { + code.overwrite(tag.pos, tag.end, ''); + } + _modified = true; + } + } + } + } + modified = modified || _modified; + return _modified; + } + + ast.forEachChild((node) => { + if (ts.isFunctionDeclaration(node) && node.name?.text && node.name?.text === 'load') { + // remove JSDoc comment above `export function load ...` + replace_jsdoc_type_tags(node, node); + } + + if (ts.isVariableStatement(node)) { + // remove JSDoc comment above `export const load = ...` + if ( + ts.isIdentifier(node.declarationList.declarations[0].name) && + names.has(node.declarationList.declarations[0].name.text) && + node.declarationList.declarations[0].initializer + ) { + replace_jsdoc_type_tags(node, node.declarationList.declarations[0].initializer); + } + + for (const declaration of node.declarationList.declarations) { + if ( + ts.isIdentifier(declaration.name) && + declaration.name.text === 'load' && + declaration.initializer + ) { + // edge case — remove JSDoc comment above individual export + replace_jsdoc_type_tags(declaration, declaration.initializer); + + // remove type from `export const load: Load ...` + if (declaration.type) { + let a = declaration.type.pos; + const b = declaration.type.end; + while (/\s/.test(content[a])) a += 1; + + const type = content.slice(a, b); + code.remove(declaration.name.end, declaration.type.end); + + const rhs = declaration.initializer; + + if ( + rhs && + (ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs)) && + rhs.parameters.length + ) { + const arg = rhs.parameters[0]; + const add_parens = content[arg.pos - 1] !== '('; + + if (add_parens) code.prependRight(arg.pos, '('); + + if (arg && !arg.type) { + code.appendLeft( + arg.name.end, + `: Parameters<${type}>[0]` + (add_parens ? ')' : '') + ); + } else { + // prevent "type X is imported but not used" (isn't silenced by @ts-nocheck) when svelte-check runs + code.append(`;null as any as ${type};`); + } + } else { + // prevent "type X is imported but not used" (isn't silenced by @ts-nocheck) when svelte-check runs + code.append(`;null as any as ${type};`); + } + + modified = true; + } + } else if ( + is_server && + ts.isIdentifier(declaration.name) && + declaration.name?.text === 'actions' && + declaration.initializer + ) { + // remove JSDoc comment from `export const actions = ..` + const removed = replace_jsdoc_type_tags(node, declaration.initializer); + // ... and move type to each individual action + if (removed) { + const rhs = declaration.initializer; + if (ts.isObjectLiteralExpression(rhs)) { + for (const prop of rhs.properties) { + if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) { + const rhs = prop.initializer; + const replaced = replace_jsdoc_type_tags(prop, rhs); + if ( + !replaced && + rhs && + (ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs)) && + rhs.parameters?.[0] + ) { + const name = ts.isIdentifier(rhs.parameters[0].name) + ? rhs.parameters[0].name.text + : 'event'; + code.prependRight( + rhs.pos, + `/** @param {import('./$types').RequestEvent} ${name} */ ` + ); + } + } + } + } + } + + // remove type from `export const actions: Actions ...` + if (declaration.type) { + let a = declaration.type.pos; + const b = declaration.type.end; + while (/\s/.test(content[a])) a += 1; + + const type = content.slice(a, b); + code.remove(declaration.name.end, declaration.type.end); + code.append(`;null as any as ${type};`); + modified = true; + + // ... and move type to each individual action + const rhs = declaration.initializer; + if (ts.isObjectLiteralExpression(rhs)) { + for (const prop of rhs.properties) { + if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) { + const rhs = prop.initializer; + + if ( + rhs && + (ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs)) && + rhs.parameters.length + ) { + const arg = rhs.parameters[0]; + const add_parens = content[arg.pos - 1] !== '('; + + if (add_parens) code.prependRight(arg.pos, '('); + + if (arg && !arg.type) { + code.appendLeft( + arg.name.end, + ": import('./$types').RequestEvent" + (add_parens ? ')' : '') + ); + } + } + } + } + } + } + } + } + } + }); + + if (modified) { + // Ignore all type errors so they don't show up twice when svelte-check runs + // Account for possible @ts-check which would overwrite @ts-nocheck + if (code.original.startsWith('// @ts-check')) { + code.prependLeft('// @ts-check'.length, '\n// @ts-nocheck\n'); + } else { + code.prepend('// @ts-nocheck\n'); + } + } + + return { + modified, + code: code.toString(), + exports: Array.from(exports.keys()) + }; + } catch { + return null; + } +} diff --git a/node_modules/@sveltejs/kit/src/core/utils.js b/node_modules/@sveltejs/kit/src/core/utils.js new file mode 100644 index 0000000..6ab57f2 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/core/utils.js @@ -0,0 +1,86 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import colors from 'kleur'; +import { posixify, to_fs } from '../utils/filesystem.js'; + +/** + * Resolved path of the `runtime` directory + * + * TODO Windows issue: + * Vite or sth else somehow sets the driver letter inconsistently to lower or upper case depending on the run environment. + * In playwright debug mode run through VS Code this a root-to-lowercase conversion is needed in order for the tests to run. + * If we do this conversion in other cases it has the opposite effect though and fails. + */ +export const runtime_directory = posixify(fileURLToPath(new URL('../runtime', import.meta.url))); + +/** + * This allows us to import SvelteKit internals that aren't exposed via `pkg.exports` in a + * way that works whether `@sveltejs/kit` is installed inside the project's `node_modules` + * or in a workspace root + */ +export const runtime_base = runtime_directory.startsWith(process.cwd()) + ? `/${path.relative('.', runtime_directory)}` + : to_fs(runtime_directory); + +function noop() {} + +/** @param {{ verbose: boolean }} opts */ +export function logger({ verbose }) { + /** @type {import('types').Logger} */ + const log = (msg) => console.log(msg.replace(/^/gm, ' ')); + + /** @param {string} msg */ + const err = (msg) => console.error(msg.replace(/^/gm, ' ')); + + log.success = (msg) => log(colors.green(`✔ ${msg}`)); + log.error = (msg) => err(colors.bold().red(msg)); + log.warn = (msg) => log(colors.bold().yellow(msg)); + + log.minor = verbose ? (msg) => log(colors.grey(msg)) : noop; + log.info = verbose ? log : noop; + + return log; +} + +/** @param {import('types').ManifestData} manifest_data */ +export function get_mime_lookup(manifest_data) { + /** @type {Record} */ + const mime = {}; + + manifest_data.assets.forEach((asset) => { + if (asset.type) { + const ext = path.extname(asset.file); + mime[ext] = asset.type; + } + }); + + return mime; +} + +/** + * @param {string} dir + * @param {(file: string) => boolean} [filter] + */ +export function list_files(dir, filter) { + /** @type {string[]} */ + const files = []; + + /** @param {string} current */ + function walk(current) { + for (const file of fs.readdirSync(path.resolve(dir, current))) { + const child = path.posix.join(current, file); + if (fs.statSync(path.resolve(dir, child)).isDirectory()) { + walk(child); + } else { + if (!filter || filter(child)) { + files.push(child); + } + } + } + } + + if (fs.existsSync(dir)) walk(''); + + return files; +} diff --git a/node_modules/@sveltejs/kit/src/exports/hooks/index.js b/node_modules/@sveltejs/kit/src/exports/hooks/index.js new file mode 100644 index 0000000..98e1e53 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/hooks/index.js @@ -0,0 +1 @@ +export { sequence } from './sequence.js'; diff --git a/node_modules/@sveltejs/kit/src/exports/hooks/sequence.js b/node_modules/@sveltejs/kit/src/exports/hooks/sequence.js new file mode 100644 index 0000000..3a6995f --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/hooks/sequence.js @@ -0,0 +1,120 @@ +/** + * A helper function for sequencing multiple `handle` calls in a middleware-like manner. + * The behavior for the `handle` options is as follows: + * - `transformPageChunk` is applied in reverse order and merged + * - `preload` is applied in forward order, the first option "wins" and no `preload` options after it are called + * - `filterSerializedResponseHeaders` behaves the same as `preload` + * + * ```js + * /// file: src/hooks.server.js + * import { sequence } from '@sveltejs/kit/hooks'; + * + * /// type: import('@sveltejs/kit').Handle + * async function first({ event, resolve }) { + * console.log('first pre-processing'); + * const result = await resolve(event, { + * transformPageChunk: ({ html }) => { + * // transforms are applied in reverse order + * console.log('first transform'); + * return html; + * }, + * preload: () => { + * // this one wins as it's the first defined in the chain + * console.log('first preload'); + * } + * }); + * console.log('first post-processing'); + * return result; + * } + * + * /// type: import('@sveltejs/kit').Handle + * async function second({ event, resolve }) { + * console.log('second pre-processing'); + * const result = await resolve(event, { + * transformPageChunk: ({ html }) => { + * console.log('second transform'); + * return html; + * }, + * preload: () => { + * console.log('second preload'); + * }, + * filterSerializedResponseHeaders: () => { + * // this one wins as it's the first defined in the chain + * console.log('second filterSerializedResponseHeaders'); + * } + * }); + * console.log('second post-processing'); + * return result; + * } + * + * export const handle = sequence(first, second); + * ``` + * + * The example above would print: + * + * ``` + * first pre-processing + * first preload + * second pre-processing + * second filterSerializedResponseHeaders + * second transform + * first transform + * second post-processing + * first post-processing + * ``` + * + * @param {...import('@sveltejs/kit').Handle} handlers The chain of `handle` functions + * @returns {import('@sveltejs/kit').Handle} + */ +export function sequence(...handlers) { + const length = handlers.length; + if (!length) return ({ event, resolve }) => resolve(event); + + return ({ event, resolve }) => { + return apply_handle(0, event, {}); + + /** + * @param {number} i + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('@sveltejs/kit').ResolveOptions | undefined} parent_options + * @returns {import('types').MaybePromise} + */ + function apply_handle(i, event, parent_options) { + const handle = handlers[i]; + + return handle({ + event, + resolve: (event, options) => { + /** @type {import('@sveltejs/kit').ResolveOptions['transformPageChunk']} */ + const transformPageChunk = async ({ html, done }) => { + if (options?.transformPageChunk) { + html = (await options.transformPageChunk({ html, done })) ?? ''; + } + + if (parent_options?.transformPageChunk) { + html = (await parent_options.transformPageChunk({ html, done })) ?? ''; + } + + return html; + }; + + /** @type {import('@sveltejs/kit').ResolveOptions['filterSerializedResponseHeaders']} */ + const filterSerializedResponseHeaders = + parent_options?.filterSerializedResponseHeaders ?? + options?.filterSerializedResponseHeaders; + + /** @type {import('@sveltejs/kit').ResolveOptions['preload']} */ + const preload = parent_options?.preload ?? options?.preload; + + return i < length - 1 + ? apply_handle(i + 1, event, { + transformPageChunk, + filterSerializedResponseHeaders, + preload + }) + : resolve(event, { transformPageChunk, filterSerializedResponseHeaders, preload }); + } + }); + } + }; +} diff --git a/node_modules/@sveltejs/kit/src/exports/index.js b/node_modules/@sveltejs/kit/src/exports/index.js new file mode 100644 index 0000000..cfe942f --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/index.js @@ -0,0 +1,158 @@ +import { HttpError, Redirect, ActionFailure } from '../runtime/control.js'; +import { BROWSER, DEV } from 'esm-env'; +import { get_route_segments } from '../utils/routing.js'; + +export { VERSION } from '../version.js'; + +/** + * @overload + * @param {number} status + * @param {App.Error} body + * @return {HttpError} + */ + +/** + * @overload + * @param {number} status + * @param {{ message: string } extends App.Error ? App.Error | string | undefined : never} [body] + * @return {HttpError} + */ + +/** + * Creates an `HttpError` object with an HTTP status code and an optional message. + * This object, if thrown during request handling, will cause SvelteKit to + * return an error response without invoking `handleError`. + * Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it. + * @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. + * @param {{ message: string } extends App.Error ? App.Error | string | undefined : never} body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. + */ +export function error(status, body) { + if ((!BROWSER || DEV) && (isNaN(status) || status < 400 || status > 599)) { + throw new Error(`HTTP error status codes must be between 400 and 599 — ${status} is invalid`); + } + + return new HttpError(status, body); +} + +/** + * Create a `Redirect` object. If thrown during request handling, SvelteKit will return a redirect response. + * Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it. + * @param {300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages). Must be in the range 300-308. + * @param {string} location The location to redirect to. + */ +export function redirect(status, location) { + if ((!BROWSER || DEV) && (isNaN(status) || status < 300 || status > 308)) { + throw new Error('Invalid status code'); + } + + return new Redirect(status, location); +} + +/** + * Create a JSON `Response` object from the supplied data. + * @param {any} data The value that will be serialized as JSON. + * @param {ResponseInit} [init] Options such as `status` and `headers` that will be added to the response. `Content-Type: application/json` and `Content-Length` headers will be added automatically. + */ +export function json(data, init) { + // TODO deprecate this in favour of `Response.json` when it's + // more widely supported + const body = JSON.stringify(data); + + // we can't just do `text(JSON.stringify(data), init)` because + // it will set a default `content-type` header. duplicated code + // means less duplicated work + const headers = new Headers(init?.headers); + if (!headers.has('content-length')) { + headers.set('content-length', encoder.encode(body).byteLength.toString()); + } + + if (!headers.has('content-type')) { + headers.set('content-type', 'application/json'); + } + + return new Response(body, { + ...init, + headers + }); +} + +const encoder = new TextEncoder(); + +/** + * Create a `Response` object from the supplied body. + * @param {string} body The value that will be used as-is. + * @param {ResponseInit} [init] Options such as `status` and `headers` that will be added to the response. A `Content-Length` header will be added automatically. + */ +export function text(body, init) { + const headers = new Headers(init?.headers); + if (!headers.has('content-length')) { + const encoded = encoder.encode(body); + headers.set('content-length', encoded.byteLength.toString()); + return new Response(encoded, { + ...init, + headers + }); + } + + return new Response(body, { + ...init, + headers + }); +} + +/** + * Create an `ActionFailure` object. + * @template {Record | undefined} [T=undefined] + * @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. + * @param {T} [data] Data associated with the failure (e.g. validation errors) + * @returns {ActionFailure} + */ +export function fail(status, data) { + return new ActionFailure(status, data); +} + +const basic_param_pattern = /\[(\[)?(\.\.\.)?(\w+?)(?:=(\w+))?\]\]?/g; + +/** + * Populate a route ID with params to resolve a pathname. + * @example + * ```js + * resolvePath( + * `/blog/[slug]/[...somethingElse]`, + * { + * slug: 'hello-world', + * somethingElse: 'something/else' + * } + * ); // `/blog/hello-world/something/else` + * ``` + * @param {string} id + * @param {Record} params + * @returns {string} + */ +export function resolvePath(id, params) { + const segments = get_route_segments(id); + return ( + '/' + + segments + .map((segment) => + segment.replace(basic_param_pattern, (_, optional, rest, name) => { + const param_value = params[name]; + + // This is nested so TS correctly narrows the type + if (!param_value) { + if (optional) return ''; + if (rest && param_value !== undefined) return ''; + throw new Error(`Missing parameter '${name}' in route ${id}`); + } + + if (param_value.startsWith('/') || param_value.endsWith('/')) + throw new Error( + `Parameter '${name}' in route ${id} cannot start or end with a slash -- this would cause an invalid route like foo//bar` + ); + return param_value; + }) + ) + .filter(Boolean) + .join('/') + ); +} diff --git a/node_modules/@sveltejs/kit/src/exports/node/index.js b/node_modules/@sveltejs/kit/src/exports/node/index.js new file mode 100644 index 0000000..1f41752 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/node/index.js @@ -0,0 +1,190 @@ +import * as set_cookie_parser from 'set-cookie-parser'; +import { error } from '../index.js'; + +/** + * @param {import('http').IncomingMessage} req + * @param {number} [body_size_limit] + */ +function get_raw_body(req, body_size_limit) { + const h = req.headers; + + if (!h['content-type']) { + return null; + } + + const content_length = Number(h['content-length']); + + // check if no request body + if ( + (req.httpVersionMajor === 1 && isNaN(content_length) && h['transfer-encoding'] == null) || + content_length === 0 + ) { + return null; + } + + let length = content_length; + + if (body_size_limit) { + if (!length) { + length = body_size_limit; + } else if (length > body_size_limit) { + throw error( + 413, + `Received content-length of ${length}, but only accept up to ${body_size_limit} bytes.` + ); + } + } + + if (req.destroyed) { + const readable = new ReadableStream(); + readable.cancel(); + return readable; + } + + let size = 0; + let cancelled = false; + + return new ReadableStream({ + start(controller) { + req.on('error', (error) => { + cancelled = true; + controller.error(error); + }); + + req.on('end', () => { + if (cancelled) return; + controller.close(); + }); + + req.on('data', (chunk) => { + if (cancelled) return; + + size += chunk.length; + if (size > length) { + cancelled = true; + controller.error( + error( + 413, + `request body size exceeded ${ + content_length ? "'content-length'" : 'BODY_SIZE_LIMIT' + } of ${length}` + ) + ); + return; + } + + controller.enqueue(chunk); + + if (controller.desiredSize === null || controller.desiredSize <= 0) { + req.pause(); + } + }); + }, + + pull() { + req.resume(); + }, + + cancel(reason) { + cancelled = true; + req.destroy(reason); + } + }); +} + +/** + * @param {{ + * request: import('http').IncomingMessage; + * base: string; + * bodySizeLimit?: number; + * }} options + * @returns {Promise} + */ +export async function getRequest({ request, base, bodySizeLimit }) { + return new Request(base + request.url, { + // @ts-expect-error + duplex: 'half', + method: request.method, + headers: /** @type {Record} */ (request.headers), + body: get_raw_body(request, bodySizeLimit) + }); +} + +/** + * @param {import('http').ServerResponse} res + * @param {Response} response + * @returns {Promise} + */ +export async function setResponse(res, response) { + for (const [key, value] of response.headers) { + try { + res.setHeader( + key, + key === 'set-cookie' + ? set_cookie_parser.splitCookiesString( + // This is absurd but necessary, TODO: investigate why + /** @type {string}*/ (response.headers.get(key)) + ) + : value + ); + } catch (error) { + res.getHeaderNames().forEach((name) => res.removeHeader(name)); + res.writeHead(500).end(String(error)); + return; + } + } + + res.writeHead(response.status); + + if (!response.body) { + res.end(); + return; + } + + if (response.body.locked) { + res.end( + 'Fatal error: Response body is locked. ' + + "This can happen when the response was already read (for example through 'response.json()' or 'response.text()')." + ); + return; + } + + const reader = response.body.getReader(); + + if (res.destroyed) { + reader.cancel(); + return; + } + + const cancel = (/** @type {Error|undefined} */ error) => { + res.off('close', cancel); + res.off('error', cancel); + + // If the reader has already been interrupted with an error earlier, + // then it will appear here, it is useless, but it needs to be catch. + reader.cancel(error).catch(() => {}); + if (error) res.destroy(error); + }; + + res.on('close', cancel); + res.on('error', cancel); + + next(); + async function next() { + try { + for (;;) { + const { done, value } = await reader.read(); + + if (done) break; + + if (!res.write(value)) { + res.once('drain', next); + return; + } + } + res.end(); + } catch (error) { + cancel(error instanceof Error ? error : new Error(String(error))); + } + } +} diff --git a/node_modules/@sveltejs/kit/src/exports/node/polyfills.js b/node_modules/@sveltejs/kit/src/exports/node/polyfills.js new file mode 100644 index 0000000..d1bb58d --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/node/polyfills.js @@ -0,0 +1,42 @@ +import { ReadableStream, TransformStream, WritableStream } from 'node:stream/web'; +import buffer from 'node:buffer'; +import { webcrypto as crypto } from 'node:crypto'; +import { fetch, Response, Request, Headers, FormData, File as UndiciFile } from 'undici'; + +// @ts-expect-error +const File = buffer.File ?? UndiciFile; + +/** @type {Record} */ +const globals = { + crypto, + fetch, + Response, + Request, + Headers, + ReadableStream, + TransformStream, + WritableStream, + FormData, + File +}; + +// exported for dev/preview and node environments +// TODO: remove this once we only support Node 18.11+ (the version multipart/form-data was added) +/** + * Make various web APIs available as globals: + * - `crypto` + * - `fetch` + * - `Headers` + * - `Request` + * - `Response` + */ +export function installPolyfills() { + for (const name in globals) { + Object.defineProperty(globalThis, name, { + enumerable: true, + configurable: true, + writable: true, + value: globals[name] + }); + } +} diff --git a/node_modules/@sveltejs/kit/src/exports/public.d.ts b/node_modules/@sveltejs/kit/src/exports/public.d.ts new file mode 100644 index 0000000..905f67d --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/public.d.ts @@ -0,0 +1,1275 @@ +import 'svelte'; // pick up `declare module "*.svelte"` +import 'vite/client'; // pick up `declare module "*.jpg"`, etc. +import '../types/ambient.js'; + +import { CompileOptions } from 'svelte/types/compiler/interfaces'; +import { + AdapterEntry, + CspDirectives, + HttpMethod, + Logger, + MaybePromise, + Prerendered, + PrerenderEntryGeneratorMismatchHandlerValue, + PrerenderHttpErrorHandlerValue, + PrerenderMissingIdHandlerValue, + PrerenderOption, + RequestOptions, + RouteSegment +} from '../types/private.js'; +import { ActionFailure } from '../runtime/control.js'; +import { BuildData, SSRNodeLoader, SSRRoute, ValidatedConfig } from 'types'; +import type { PluginOptions } from '@sveltejs/vite-plugin-svelte'; + +export { PrerenderOption } from '../types/private.js'; +export { ActionFailure }; + +/** + * [Adapters](https://kit.svelte.dev/docs/adapters) are responsible for taking the production build and turning it into something that can be deployed to a platform of your choosing. + */ +export interface Adapter { + /** + * The name of the adapter, using for logging. Will typically correspond to the package name. + */ + name: string; + /** + * This function is called after SvelteKit has built your app. + * @param builder An object provided by SvelteKit that contains methods for adapting the app + */ + adapt(builder: Builder): MaybePromise; +} + +type AwaitedPropertiesUnion | void> = input extends void + ? undefined // needs to be undefined, because void will break intellisense + : input extends Record + ? { + [key in keyof input]: Awaited; + } + : {} extends input // handles the any case + ? input + : unknown; + +export type AwaitedProperties | void> = + AwaitedPropertiesUnion extends Record + ? OptionalUnion> + : AwaitedPropertiesUnion; + +export type AwaitedActions any>> = OptionalUnion< + { + [Key in keyof T]: UnpackValidationError>>; + }[keyof T] +>; + +// Takes a union type and returns a union type where each type also has all properties +// of all possible types (typed as undefined), making accessing them more ergonomic +type OptionalUnion< + U extends Record, // not unknown, else interfaces don't satisfy this constraint + A extends keyof U = U extends U ? keyof U : never +> = U extends unknown ? { [P in Exclude]?: never } & U : never; + +type UnpackValidationError = T extends ActionFailure + ? X + : T extends void + ? undefined // needs to be undefined, because void will corrupt union type + : T; + +/** + * This object is passed to the `adapt` function of adapters. + * It contains various methods and properties that are useful for adapting the app. + */ +export interface Builder { + /** Print messages to the console. `log.info` and `log.minor` are silent unless Vite's `logLevel` is `info`. */ + log: Logger; + /** Remove `dir` and all its contents. */ + rimraf(dir: string): void; + /** Create `dir` and any required parent directories. */ + mkdirp(dir: string): void; + + /** The fully resolved `svelte.config.js`. */ + config: ValidatedConfig; + /** Information about prerendered pages and assets, if any. */ + prerendered: Prerendered; + /** An array of all routes (including prerendered) */ + routes: RouteDefinition[]; + + /** + * Create separate functions that map to one or more routes of your app. + * @param fn A function that groups a set of routes into an entry point + * @deprecated Use `builder.routes` instead + */ + createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise; + + /** + * Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps. + */ + generateFallback(dest: string): Promise; + + /** + * Generate a server-side manifest to initialise the SvelteKit [server](https://kit.svelte.dev/docs/types#public-types-server) with. + * @param opts a relative path to the base directory of the app and optionally in which format (esm or cjs) the manifest should be generated + */ + generateManifest(opts: { relativePath: string; routes?: RouteDefinition[] }): string; + + /** + * Resolve a path to the `name` directory inside `outDir`, e.g. `/path/to/.svelte-kit/my-adapter`. + * @param name path to the file, relative to the build directory + */ + getBuildDirectory(name: string): string; + /** Get the fully resolved path to the directory containing client-side assets, including the contents of your `static` directory. */ + getClientDirectory(): string; + /** Get the fully resolved path to the directory containing server-side code. */ + getServerDirectory(): string; + /** Get the application path including any configured `base` path, e.g. `/my-base-path/_app`. */ + getAppPath(): string; + + /** + * Write client assets to `dest`. + * @param dest the destination folder + * @returns an array of files written to `dest` + */ + writeClient(dest: string): string[]; + /** + * Write prerendered files to `dest`. + * @param dest the destination folder + * @returns an array of files written to `dest` + */ + writePrerendered(dest: string): string[]; + /** + * Write server-side code to `dest`. + * @param dest the destination folder + * @returns an array of files written to `dest` + */ + writeServer(dest: string): string[]; + /** + * Copy a file or directory. + * @param from the source file or directory + * @param to the destination file or directory + * @param opts.filter a function to determine whether a file or directory should be copied + * @param opts.replace a map of strings to replace + * @returns an array of files that were copied + */ + copy( + from: string, + to: string, + opts?: { + filter?(basename: string): boolean; + replace?: Record; + } + ): string[]; + + /** + * Compress files in `directory` with gzip and brotli, where appropriate. Generates `.gz` and `.br` files alongside the originals. + * @param {string} directory The directory containing the files to be compressed + */ + compress(directory: string): Promise; +} + +export interface Config { + /** + * Options passed to [`svelte.compile`](https://svelte.dev/docs#compile-time-svelte-compile). + * @default {} + */ + compilerOptions?: CompileOptions; + /** + * List of file extensions that should be treated as Svelte files. + * @default [".svelte"] + */ + extensions?: string[]; + /** SvelteKit options */ + kit?: KitConfig; + /** [`@sveltejs/package`](/docs/packaging) options. */ + package?: { + source?: string; + dir?: string; + emitTypes?: boolean; + exports?(filepath: string): boolean; + files?(filepath: string): boolean; + }; + /** Preprocessor options, if any. Preprocessing can alternatively also be done through Vite's preprocessor capabilities. */ + preprocess?: any; + /** `vite-plugin-svelte` plugin options. */ + vitePlugin?: PluginOptions; + /** Any additional options required by tooling that integrates with Svelte. */ + [key: string]: any; +} + +export interface Cookies { + /** + * Gets a cookie that was previously set with `cookies.set`, or from the request headers. + * @param name the name of the cookie + * @param opts the options, passed directly to `cookie.parse`. See documentation [here](https://github.com/jshttp/cookie#cookieparsestr-options) + */ + get(name: string, opts?: import('cookie').CookieParseOptions): string | undefined; + + /** + * Gets all cookies that were previously set with `cookies.set`, or from the request headers. + * @param opts the options, passed directily to `cookie.parse`. See documentation [here](https://github.com/jshttp/cookie#cookieparsestr-options) + */ + getAll(opts?: import('cookie').CookieParseOptions): Array<{ name: string; value: string }>; + + /** + * Sets a cookie. This will add a `set-cookie` header to the response, but also make the cookie available via `cookies.get` or `cookies.getAll` during the current request. + * + * The `httpOnly` and `secure` options are `true` by default (except on http://localhost, where `secure` is `false`), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The `sameSite` option defaults to `lax`. + * + * By default, the `path` of a cookie is the 'directory' of the current pathname. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. + * @param name the name of the cookie + * @param value the cookie value + * @param opts the options, passed directory to `cookie.serialize`. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) + */ + set(name: string, value: string, opts?: import('cookie').CookieSerializeOptions): void; + + /** + * Deletes a cookie by setting its value to an empty string and setting the expiry date in the past. + * + * By default, the `path` of a cookie is the 'directory' of the current pathname. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. + * @param name the name of the cookie + * @param opts the options, passed directory to `cookie.serialize`. The `path` must match the path of the cookie you want to delete. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) + */ + delete(name: string, opts?: import('cookie').CookieSerializeOptions): void; + + /** + * Serialize a cookie name-value pair into a `Set-Cookie` header string, but don't apply it to the response. + * + * The `httpOnly` and `secure` options are `true` by default (except on http://localhost, where `secure` is `false`), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The `sameSite` option defaults to `lax`. + * + * By default, the `path` of a cookie is the current pathname. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. + * + * @param name the name of the cookie + * @param value the cookie value + * @param opts the options, passed directory to `cookie.serialize`. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) + */ + serialize(name: string, value: string, opts?: import('cookie').CookieSerializeOptions): string; +} + +export interface KitConfig { + /** + * Your [adapter](https://kit.svelte.dev/docs/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms. + * @default undefined + */ + adapter?: Adapter; + /** + * An object containing zero or more aliases used to replace values in `import` statements. These aliases are automatically passed to Vite and TypeScript. + * + * ```js + * /// file: svelte.config.js + * /// type: import('@sveltejs/kit').Config + * const config = { + * kit: { + * alias: { + * // this will match a file + * 'my-file': 'path/to/my-file.js', + * + * // this will match a directory and its contents + * // (`my-directory/x` resolves to `path/to/my-directory/x`) + * 'my-directory': 'path/to/my-directory', + * + * // an alias ending /* will only match + * // the contents of a directory, not the directory itself + * 'my-directory/*': 'path/to/my-directory/*' + * } + * } + * }; + * ``` + * + * > The built-in `$lib` alias is controlled by `config.kit.files.lib` as it is used for packaging. + * + * > You will need to run `npm run dev` to have SvelteKit automatically generate the required alias configuration in `jsconfig.json` or `tsconfig.json`. + * @default {} + */ + alias?: Record; + /** + * The directory relative to `paths.assets` where the built JS and CSS (and imported assets) are served from. (The filenames therein contain content-based hashes, meaning they can be cached indefinitely). Must not start or end with `/`. + * @default "_app" + */ + appDir?: string; + /** + * [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) configuration. CSP helps to protect your users against cross-site scripting (XSS) attacks, by limiting the places resources can be loaded from. For example, a configuration like this... + * + * ```js + * /// file: svelte.config.js + * /// type: import('@sveltejs/kit').Config + * const config = { + * kit: { + * csp: { + * directives: { + * 'script-src': ['self'] + * }, + * reportOnly: { + * 'script-src': ['self'] + * } + * } + * } + * }; + * + * export default config; + * ``` + * + * ...would prevent scripts loading from external sites. SvelteKit will augment the specified directives with nonces or hashes (depending on `mode`) for any inline styles and scripts it generates. + * + * To add a nonce for scripts and links manually included in `src/app.html`, you may use the placeholder `%sveltekit.nonce%` (for example ` + * ``` + * + * If you set `pollInterval` to a non-zero value, SvelteKit will poll for new versions in the background and set the value of the [`updated`](/docs/modules#$app-stores-updated) store to `true` when it detects one. + */ + version?: { + /** + * The current app version string. If specified, this must be deterministic (e.g. a commit ref rather than `Math.random()` or `Date.now().toString()`), otherwise defaults to a timestamp of the build. + * + * For example, to use the current commit hash, you could do use `git rev-parse HEAD`: + * + * ```js + * /// file: svelte.config.js + * import * as child_process from 'node:child_process'; + * + * export default { + * kit: { + * version: { + * name: child_process.execSync('git rev-parse HEAD').toString().trim() + * } + * } + * }; + * ``` + */ + name?: string; + /** + * The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs. + * @default 0 + */ + pollInterval?: number; + }; +} + +/** + * The [`handle`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) hook runs every time the SvelteKit server receives a [request](https://kit.svelte.dev/docs/web-standards#fetch-apis-request) and + * determines the [response](https://kit.svelte.dev/docs/web-standards#fetch-apis-response). + * It receives an `event` object representing the request and a function called `resolve`, which renders the route and generates a `Response`. + * This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example). + */ +export type Handle = (input: { + event: RequestEvent; + resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise; +}) => MaybePromise; + +/** + * The server-side [`handleError`](https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror) hook runs when an unexpected error is thrown while responding to a request. + * + * If an unexpected error is thrown during loading or rendering, this function will be called with the error and the event. + * Make sure that this function _never_ throws an error. + */ +export type HandleServerError = (input: { + error: unknown; + event: RequestEvent; +}) => MaybePromise; + +/** + * The client-side [`handleError`](https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror) hook runs when an unexpected error is thrown while navigating. + * + * If an unexpected error is thrown during loading or the following render, this function will be called with the error and the event. + * Make sure that this function _never_ throws an error. + */ +export type HandleClientError = (input: { + error: unknown; + event: NavigationEvent; +}) => MaybePromise; + +/** + * The [`handleFetch`](https://kit.svelte.dev/docs/hooks#server-hooks-handlefetch) hook allows you to modify (or replace) a `fetch` request that happens inside a `load` function that runs on the server (or during pre-rendering) + */ +export type HandleFetch = (input: { + event: RequestEvent; + request: Request; + fetch: typeof fetch; +}) => MaybePromise; + +/** + * The generic form of `PageLoad` and `LayoutLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) + * rather than using `Load` directly. + */ +export type Load< + Params extends Partial> = Partial>, + InputData extends Record | null = Record | null, + ParentData extends Record = Record, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null +> = (event: LoadEvent) => MaybePromise; + +/** + * The generic form of `PageLoadEvent` and `LayoutLoadEvent`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) + * rather than using `LoadEvent` directly. + */ +export interface LoadEvent< + Params extends Partial> = Partial>, + Data extends Record | null = Record | null, + ParentData extends Record = Record, + RouteId extends string | null = string | null +> extends NavigationEvent { + /** + * `fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features: + * + * - It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request. + * - It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context). + * - Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call. + * - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) + * - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request. + * + * You can learn more about making credentialed requests with cookies [here](https://kit.svelte.dev/docs/load#cookies) + */ + fetch: typeof fetch; + /** + * Contains the data returned by the route's server `load` function (in `+layout.server.js` or `+page.server.js`), if any. + */ + data: Data; + /** + * If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: + * + * ```js + * /// file: src/routes/blog/+page.js + * export async function load({ fetch, setHeaders }) { + * const url = `https://cms.example.com/articles.json`; + * const response = await fetch(url); + * + * setHeaders({ + * age: response.headers.get('age'), + * 'cache-control': response.headers.get('cache-control') + * }); + * + * return response.json(); + * } + * ``` + * + * Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once. + * + * You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](https://kit.svelte.dev/docs/types#public-types-cookies) API in a server-only `load` function instead. + * + * `setHeaders` has no effect when a `load` function runs in the browser. + */ + setHeaders(headers: Record): void; + /** + * `await parent()` returns data from parent `+layout.js` `load` functions. + * Implicitly, a missing `+layout.js` is treated as a `({ data }) => data` function, meaning that it will return and forward data from parent `+layout.server.js` files. + * + * Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data. + */ + parent(): Promise; + /** + * This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/modules#$app-navigation-invalidate) to cause `load` to rerun. + * + * Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`. + * + * URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). + * + * Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html). + * + * The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun. + * + * ```js + * /// file: src/routes/+page.js + * let count = 0; + * export async function load({ depends }) { + * depends('increase:count'); + * + * return { count: count++ }; + * } + * ``` + * + * ```html + * /// file: src/routes/+page.svelte + * + * + *

{data.count}

+ * + * ``` + */ + depends(...deps: string[]): void; +} + +export interface NavigationEvent< + Params extends Partial> = Partial>, + RouteId extends string | null = string | null +> { + /** + * The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + */ + params: Params; + /** + * Info about the current route + */ + route: { + /** + * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + */ + id: RouteId; + }; + /** + * The URL of the current page + */ + url: URL; +} + +/** + * Information about the target of a specific navigation. + */ +export interface NavigationTarget { + /** + * Parameters of the target page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object. + * Is `null` if the target is not part of the SvelteKit app (could not be resolved to a route). + */ + params: Record | null; + /** + * Info about the target route + */ + route: { id: string | null }; + /** + * The URL that is navigated to + */ + url: URL; +} + +/** + * - `enter`: The app has hydrated + * - `form`: The user submitted a `

` with a GET method + * - `leave`: The user is leaving the app by closing the tab or using the back/forward buttons to go to a different document + * - `link`: Navigation was triggered by a link click + * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect + * - `popstate`: Navigation was triggered by back/forward navigation + */ +export type NavigationType = 'enter' | 'form' | 'leave' | 'link' | 'goto' | 'popstate'; + +export interface Navigation { + /** + * Where navigation was triggered from + */ + from: NavigationTarget | null; + /** + * Where navigation is going to/has gone to + */ + to: NavigationTarget | null; + /** + * The type of navigation: + * - `form`: The user submitted a `` + * - `leave`: The user is leaving the app by closing the tab or using the back/forward buttons to go to a different document + * - `link`: Navigation was triggered by a link click + * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect + * - `popstate`: Navigation was triggered by back/forward navigation + */ + type: Omit; + /** + * Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation) + */ + willUnload: boolean; + /** + * In case of a history back/forward navigation, the number of steps to go back/forward + */ + delta?: number; +} + +/** + * The argument passed to [`beforeNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-beforenavigate) callbacks. + */ +export interface BeforeNavigate extends Navigation { + /** + * Call this to prevent the navigation from starting. + */ + cancel(): void; +} + +/** + * The argument passed to [`afterNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-afternavigate) callbacks. + */ +export interface AfterNavigate extends Navigation { + /** + * The type of navigation: + * - `enter`: The app has hydrated + * - `form`: The user submitted a `` + * - `link`: Navigation was triggered by a link click + * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect + * - `popstate`: Navigation was triggered by back/forward navigation + */ + type: Omit; + /** + * Since `afterNavigate` is called after a navigation completes, it will never be called with a navigation that unloads the page. + */ + willUnload: false; +} + +/** + * The shape of the `$page` store + */ +export interface Page< + Params extends Record = Record, + RouteId extends string | null = string | null +> { + /** + * The URL of the current page + */ + url: URL; + /** + * The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + */ + params: Params; + /** + * Info about the current route + */ + route: { + /** + * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + */ + id: RouteId; + }; + /** + * Http status code of the current page + */ + status: number; + /** + * The error object of the current page, if any. Filled from the `handleError` hooks. + */ + error: App.Error | null; + /** + * The merged result of all data from all `load` functions on the current page. You can type a common denominator through `App.PageData`. + */ + data: App.PageData & Record; + /** + * Filled only after a form submission. See [form actions](https://kit.svelte.dev/docs/form-actions) for more info. + */ + form: any; +} + +/** + * The shape of a param matcher. See [matching](https://kit.svelte.dev/docs/advanced-routing#matching) for more info. + */ +export type ParamMatcher = (param: string) => boolean; + +export interface RequestEvent< + Params extends Partial> = Partial>, + RouteId extends string | null = string | null +> { + /** + * Get or set cookies related to the current request + */ + cookies: Cookies; + /** + * `fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features: + * + * - It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request. + * - It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context). + * - Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call. + * - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) + * - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request. + * + * You can learn more about making credentialed requests with cookies [here](https://kit.svelte.dev/docs/load#cookies) + */ + fetch: typeof fetch; + /** + * The client's IP address, set by the adapter. + */ + getClientAddress(): string; + /** + * Contains custom data that was added to the request within the [`handle hook`](https://kit.svelte.dev/docs/hooks#server-hooks-handle). + */ + locals: App.Locals; + /** + * The parameters of the current route - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + */ + params: Params; + /** + * Additional data made available through the adapter. + */ + platform: Readonly | undefined; + /** + * The original request object + */ + request: Request; + /** + * Info about the current route + */ + route: { + /** + * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + */ + id: RouteId; + }; + /** + * If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: + * + * ```js + * /// file: src/routes/blog/+page.js + * export async function load({ fetch, setHeaders }) { + * const url = `https://cms.example.com/articles.json`; + * const response = await fetch(url); + * + * setHeaders({ + * age: response.headers.get('age'), + * 'cache-control': response.headers.get('cache-control') + * }); + * + * return response.json(); + * } + * ``` + * + * Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once. + * + * You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](https://kit.svelte.dev/docs/types#public-types-cookies) API instead. + */ + setHeaders(headers: Record): void; + /** + * The requested URL. + */ + url: URL; + /** + * `true` if the request comes from the client asking for `+page/layout.server.js` data. The `url` property will be stripped of the internal information + * related to the data request in this case. Use this property instead if the distinction is important to you. + */ + isDataRequest: boolean; + /** + * `true` for `+server.js` calls coming from SvelteKit without the overhead of actually making an HTTP request. This happens when you make same-origin `fetch` requests on the server. + */ + isSubRequest: boolean; +} + +/** + * A `(event: RequestEvent) => Response` function exported from a `+server.js` file that corresponds to an HTTP verb (`GET`, `PUT`, `PATCH`, etc) and handles requests with that method. + * + * It receives `Params` as the first generic argument, which you can skip by using [generated types](https://kit.svelte.dev/docs/types#generated-types) instead. + */ +export type RequestHandler< + Params extends Partial> = Partial>, + RouteId extends string | null = string | null +> = (event: RequestEvent) => MaybePromise; + +export interface ResolveOptions { + /** + * Applies custom transforms to HTML. If `done` is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML + * (they could include an element's opening tag but not its closing tag, for example) + * but they will always be split at sensible boundaries such as `%sveltekit.head%` or layout/page components. + * @param input the html chunk and the info if this is the last chunk + */ + transformPageChunk?(input: { html: string; done: boolean }): MaybePromise; + /** + * Determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`. + * By default, none will be included. + * @param name header name + * @param value header value + */ + filterSerializedResponseHeaders?(name: string, value: string): boolean; + /** + * Determines what should be added to the `` tag to preload it. + * By default, `js` and `css` files will be preloaded. + * @param input the type of the file and its path + */ + preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean; +} + +export interface RouteDefinition { + id: string; + api: { + methods: HttpMethod[]; + }; + page: { + methods: Extract[]; + }; + pattern: RegExp; + prerender: PrerenderOption; + segments: RouteSegment[]; + methods: HttpMethod[]; + config: Config; +} + +export class Server { + constructor(manifest: SSRManifest); + init(options: ServerInitOptions): Promise; + respond(request: Request, options: RequestOptions): Promise; +} + +export interface ServerInitOptions { + env: Record; +} + +export interface SSRManifest { + appDir: string; + appPath: string; + assets: Set; + mimeTypes: Record; + + /** private fields */ + _: { + client: NonNullable; + nodes: SSRNodeLoader[]; + routes: SSRRoute[]; + matchers(): Promise>; + }; +} + +/** + * The generic form of `PageServerLoad` and `LayoutServerLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) + * rather than using `ServerLoad` directly. + */ +export type ServerLoad< + Params extends Partial> = Partial>, + ParentData extends Record = Record, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null +> = (event: ServerLoadEvent) => MaybePromise; + +export interface ServerLoadEvent< + Params extends Partial> = Partial>, + ParentData extends Record = Record, + RouteId extends string | null = string | null +> extends RequestEvent { + /** + * `await parent()` returns data from parent `+layout.server.js` `load` functions. + * + * Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data. + */ + parent(): Promise; + /** + * This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/modules#$app-navigation-invalidate) to cause `load` to rerun. + * + * Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`. + * + * URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). + * + * Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html). + * + * The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun. + * + * ```js + * /// file: src/routes/+page.js + * let count = 0; + * export async function load({ depends }) { + * depends('increase:count'); + * + * return { count: count++ }; + * } + * ``` + * + * ```html + * /// file: src/routes/+page.svelte + * + * + *

{data.count}

+ * + * ``` + */ + depends(...deps: string[]): void; +} + +/** + * Shape of a form action method that is part of `export const actions = {..}` in `+page.server.js`. + * See [form actions](https://kit.svelte.dev/docs/form-actions) for more information. + */ +export type Action< + Params extends Partial> = Partial>, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null +> = (event: RequestEvent) => MaybePromise; + +/** + * Shape of the `export const actions = {..}` object in `+page.server.js`. + * See [form actions](https://kit.svelte.dev/docs/form-actions) for more information. + */ +export type Actions< + Params extends Partial> = Partial>, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null +> = Record>; + +/** + * When calling a form action via fetch, the response will be one of these shapes. + * ```svelte + * { + * return ({ result }) => { + * // result is of type ActionResult + * }; + * }} + * ``` + */ +export type ActionResult< + Success extends Record | undefined = Record, + Failure extends Record | undefined = Record +> = + | { type: 'success'; status: number; data?: Success } + | { type: 'failure'; status: number; data?: Failure } + | { type: 'redirect'; status: number; location: string } + | { type: 'error'; status?: number; error: any }; + +/** + * The object returned by the [`error`](https://kit.svelte.dev/docs/modules#sveltejs-kit-error) function. + */ +export interface HttpError { + /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses), in the range 400-599. */ + status: number; + /** The content of the error. */ + body: App.Error; +} + +/** + * The object returned by the [`redirect`](https://kit.svelte.dev/docs/modules#sveltejs-kit-redirect) function + */ +export interface Redirect { + /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages), in the range 300-308. */ + status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308; + /** The location to redirect to. */ + location: string; +} + +export type SubmitFunction< + Success extends Record | undefined = Record, + Failure extends Record | undefined = Record +> = (input: { + action: URL; + /** + * use `formData` instead of `data` + * @deprecated + */ + data: FormData; + formData: FormData; + /** + * use `formElement` instead of `form` + * @deprecated + */ + form: HTMLFormElement; + formElement: HTMLFormElement; + controller: AbortController; + submitter: HTMLElement | null; + cancel(): void; +}) => MaybePromise< + | void + | ((opts: { + /** + * use `formData` instead of `data` + * @deprecated + */ + data: FormData; + formData: FormData; + /** + * use `formElement` instead of `form` + * @deprecated + */ + form: HTMLFormElement; + formElement: HTMLFormElement; + action: URL; + result: ActionResult; + /** + * Call this to get the default behavior of a form submission response. + * @param options Set `reset: false` if you don't want the `` values to be reset after a successful submission. + */ + update(options?: { reset: boolean }): Promise; + }) => void) +>; + +/** + * The type of `export const snapshot` exported from a page or layout component. + */ +export interface Snapshot { + capture: () => T; + restore: (snapshot: T) => void; +} + +export * from './index.js'; diff --git a/node_modules/@sveltejs/kit/src/exports/vite/build/build_server.js b/node_modules/@sveltejs/kit/src/exports/vite/build/build_server.js new file mode 100644 index 0000000..cebe5f7 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/build/build_server.js @@ -0,0 +1,111 @@ +import fs from 'node:fs'; +import { mkdirp } from '../../../utils/filesystem.js'; +import { find_deps, resolve_symlinks } from './utils.js'; +import { s } from '../../../utils/misc.js'; +import { normalizePath } from 'vite'; + +/** + * @param {string} out + * @param {import('types').ValidatedKitConfig} kit + * @param {import('types').ManifestData} manifest_data + * @param {import('vite').Manifest} server_manifest + * @param {import('vite').Manifest | null} client_manifest + * @param {import('rollup').OutputAsset[] | null} css + */ +export function build_server_nodes(out, kit, manifest_data, server_manifest, client_manifest, css) { + mkdirp(`${out}/server/nodes`); + mkdirp(`${out}/server/stylesheets`); + + const stylesheet_lookup = new Map(); + + if (css) { + css.forEach((asset) => { + if (asset.source.length < kit.inlineStyleThreshold) { + const index = stylesheet_lookup.size; + const file = `${out}/server/stylesheets/${index}.js`; + + fs.writeFileSync(file, `// ${asset.fileName}\nexport default ${s(asset.source)};`); + stylesheet_lookup.set(asset.fileName, index); + } + }); + } + + manifest_data.nodes.forEach((node, i) => { + /** @type {string[]} */ + const imports = []; + + // String representation of + /** @type {import('types').SSRNode} */ + /** @type {string[]} */ + const exports = [`export const index = ${i};`]; + + /** @type {string[]} */ + const imported = []; + + /** @type {string[]} */ + const stylesheets = []; + + /** @type {string[]} */ + const fonts = []; + + if (node.component && client_manifest) { + exports.push( + 'let component_cache;', + `export const component = async () => component_cache ??= (await import('../${ + resolve_symlinks(server_manifest, node.component).chunk.file + }')).default;` + ); + } + + if (node.universal) { + imports.push(`import * as universal from '../${server_manifest[node.universal].file}';`); + exports.push('export { universal };'); + exports.push(`export const universal_id = ${s(node.universal)};`); + } + + if (node.server) { + imports.push(`import * as server from '../${server_manifest[node.server].file}';`); + exports.push('export { server };'); + exports.push(`export const server_id = ${s(node.server)};`); + } + + if (client_manifest && (node.universal || node.component)) { + const entry = find_deps( + client_manifest, + `${normalizePath(kit.outDir)}/generated/client-optimized/nodes/${i}.js`, + true + ); + + imported.push(...entry.imports); + stylesheets.push(...entry.stylesheets); + fonts.push(...entry.fonts); + } + + exports.push( + `export const imports = ${s(imported)};`, + `export const stylesheets = ${s(stylesheets)};`, + `export const fonts = ${s(fonts)};` + ); + + /** @type {string[]} */ + const styles = []; + + stylesheets.forEach((file) => { + if (stylesheet_lookup.has(file)) { + const index = stylesheet_lookup.get(file); + const name = `stylesheet_${index}`; + imports.push(`import ${name} from '../stylesheets/${index}.js';`); + styles.push(`\t${s(file)}: ${name}`); + } + }); + + if (styles.length > 0) { + exports.push(`export const inline_styles = () => ({\n${styles.join(',\n')}\n});`); + } + + fs.writeFileSync( + `${out}/server/nodes/${i}.js`, + `${imports.join('\n')}\n\n${exports.join('\n')}\n` + ); + }); +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/build/build_service_worker.js b/node_modules/@sveltejs/kit/src/exports/vite/build/build_service_worker.js new file mode 100644 index 0000000..89387ae --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/build/build_service_worker.js @@ -0,0 +1,89 @@ +import fs from 'node:fs'; +import * as vite from 'vite'; +import { dedent } from '../../../core/sync/utils.js'; +import { s } from '../../../utils/misc.js'; +import { get_config_aliases } from '../utils.js'; +import { assets_base } from './utils.js'; + +/** + * @param {string} out + * @param {import('types').ValidatedKitConfig} kit + * @param {import('vite').ResolvedConfig} vite_config + * @param {import('types').ManifestData} manifest_data + * @param {string} service_worker_entry_file + * @param {import('types').Prerendered} prerendered + * @param {import('vite').Manifest} client_manifest + */ +export async function build_service_worker( + out, + kit, + vite_config, + manifest_data, + service_worker_entry_file, + prerendered, + client_manifest +) { + const build = new Set(); + for (const key in client_manifest) { + const { file, css = [], assets = [] } = client_manifest[key]; + build.add(file); + css.forEach((file) => build.add(file)); + assets.forEach((file) => build.add(file)); + } + + const service_worker = `${kit.outDir}/generated/service-worker.js`; + + // in a service worker, `location` is the location of the service worker itself, + // which is guaranteed to be `/service-worker.js` + const base = "location.pathname.split('/').slice(0, -1).join('/')"; + + fs.writeFileSync( + service_worker, + dedent` + export const base = /*@__PURE__*/ ${base}; + + export const build = [ + ${Array.from(build) + .map((file) => `base + ${s(`/${file}`)}`) + .join(',\n')} + ]; + + export const files = [ + ${manifest_data.assets + .filter((asset) => kit.serviceWorker.files(asset.file)) + .map((asset) => `base + ${s(`/${asset.file}`)}`) + .join(',\n')} + ]; + + export const prerendered = [ + ${prerendered.paths.map((path) => `base + ${s(path.replace(kit.paths.base, ''))}`).join(',\n')} + ]; + + export const version = ${s(kit.version.name)}; + ` + ); + + await vite.build({ + base: assets_base(kit), + build: { + lib: { + entry: /** @type {string} */ (service_worker_entry_file), + name: 'app', + formats: ['es'] + }, + rollupOptions: { + output: { + entryFileNames: 'service-worker.js' + } + }, + outDir: `${out}/client`, + emptyOutDir: false + }, + configFile: false, + define: vite_config.define, + publicDir: false, + resolve: { + alias: [...get_config_aliases(kit), { find: '$service-worker', replacement: service_worker }] + } + }); +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/build/utils.js b/node_modules/@sveltejs/kit/src/exports/vite/build/utils.js new file mode 100644 index 0000000..7670a82 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/build/utils.js @@ -0,0 +1,92 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { normalizePath } from 'vite'; + +/** + * Adds transitive JS and CSS dependencies to the js and css inputs. + * @param {import('vite').Manifest} manifest + * @param {string} entry + * @param {boolean} add_dynamic_css + * @returns {import('types').AssetDependencies} + */ +export function find_deps(manifest, entry, add_dynamic_css) { + /** @type {Set} */ + const seen = new Set(); + + /** @type {Set} */ + const imports = new Set(); + + /** @type {Set} */ + const stylesheets = new Set(); + + /** @type {Set} */ + const fonts = new Set(); + + /** + * @param {string} current + * @param {boolean} add_js + */ + function traverse(current, add_js) { + if (seen.has(current)) return; + seen.add(current); + + const { chunk } = resolve_symlinks(manifest, current); + + if (add_js) imports.add(chunk.file); + + if (chunk.assets) { + for (const asset of chunk.assets) { + if (/\.(woff2?|ttf|otf)$/.test(asset)) { + fonts.add(asset); + } + } + } + + if (chunk.css) { + chunk.css.forEach((file) => stylesheets.add(file)); + } + + if (chunk.imports) { + chunk.imports.forEach((file) => traverse(file, add_js)); + } + + if (add_dynamic_css && chunk.dynamicImports) { + chunk.dynamicImports.forEach((file) => traverse(file, false)); + } + } + + const { chunk, file } = resolve_symlinks(manifest, entry); + + traverse(file, true); + + return { + file: chunk.file, + imports: Array.from(imports), + stylesheets: Array.from(stylesheets), + fonts: Array.from(fonts) + }; +} + +/** + * @param {import('vite').Manifest} manifest + * @param {string} file + */ +export function resolve_symlinks(manifest, file) { + while (!manifest[file]) { + const next = normalizePath(path.relative('.', fs.realpathSync(file))); + if (next === file) throw new Error(`Could not find file "${file}" in Vite manifest`); + file = next; + } + + const chunk = manifest[file]; + + return { chunk, file }; +} + +/** + * @param {import('types').ValidatedKitConfig} config + * @returns {string} + */ +export function assets_base(config) { + return (config.paths.assets || config.paths.base || '.') + '/'; +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js b/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js new file mode 100644 index 0000000..0c9ea37 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js @@ -0,0 +1,606 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { URL } from 'node:url'; +import colors from 'kleur'; +import sirv from 'sirv'; +import { isCSSRequest, loadEnv, buildErrorMessage } from 'vite'; +import { getRequest, setResponse } from '../../../exports/node/index.js'; +import { installPolyfills } from '../../../exports/node/polyfills.js'; +import { coalesce_to_error } from '../../../utils/error.js'; +import { posixify, resolve_entry, to_fs } from '../../../utils/filesystem.js'; +import { should_polyfill } from '../../../utils/platform.js'; +import { load_error_page } from '../../../core/config/index.js'; +import { SVELTE_KIT_ASSETS } from '../../../constants.js'; +import * as sync from '../../../core/sync/sync.js'; +import { get_mime_lookup, runtime_base } from '../../../core/utils.js'; +import { compact } from '../../../utils/array.js'; +import { not_found } from '../utils.js'; + +const cwd = process.cwd(); + +/** + * @param {import('vite').ViteDevServer} vite + * @param {import('vite').ResolvedConfig} vite_config + * @param {import('types').ValidatedConfig} svelte_config + * @return {Promise void>>} + */ +export async function dev(vite, vite_config, svelte_config) { + if (should_polyfill) { + installPolyfills(); + } + + const fetch = globalThis.fetch; + globalThis.fetch = (info, init) => { + if (typeof info === 'string' && !/^\w+:\/\//.test(info)) { + throw new Error( + `Cannot use relative URL (${info}) with global fetch — use \`event.fetch\` instead: https://kit.svelte.dev/docs/web-standards#fetch-apis` + ); + } + + return fetch(info, init); + }; + + sync.init(svelte_config, vite_config.mode); + + /** @type {import('types').ManifestData} */ + let manifest_data; + /** @type {import('@sveltejs/kit').SSRManifest} */ + let manifest; + + /** @type {Error | null} */ + let manifest_error = null; + + /** @param {string} url */ + async function loud_ssr_load_module(url) { + try { + return await vite.ssrLoadModule(url); + } catch (/** @type {any} */ err) { + const msg = buildErrorMessage(err, [colors.red(`Internal server error: ${err.message}`)]); + + vite.config.logger.error(msg, { error: err }); + vite.ws.send({ + type: 'error', + err: { + ...err, + // these properties are non-enumerable and will + // not be serialized unless we explicitly include them + message: err.message, + stack: err.stack + } + }); + + throw err; + } + } + + /** @param {string} id */ + async function resolve(id) { + const url = id.startsWith('..') ? `/@fs${path.posix.resolve(id)}` : `/${id}`; + + const module = await loud_ssr_load_module(url); + + const module_node = await vite.moduleGraph.getModuleByUrl(url); + if (!module_node) throw new Error(`Could not find node for ${url}`); + + return { module, module_node, url }; + } + + async function update_manifest() { + try { + ({ manifest_data } = await sync.create(svelte_config)); + + if (manifest_error) { + manifest_error = null; + vite.ws.send({ type: 'full-reload' }); + } + } catch (error) { + manifest_error = /** @type {Error} */ (error); + + console.error(colors.bold().red(manifest_error.message)); + vite.ws.send({ + type: 'error', + err: { + message: manifest_error.message ?? 'Invalid routes', + stack: '' + } + }); + + return; + } + + manifest = { + appDir: svelte_config.kit.appDir, + appPath: svelte_config.kit.appDir, + assets: new Set(manifest_data.assets.map((asset) => asset.file)), + mimeTypes: get_mime_lookup(manifest_data), + _: { + client: { + start: `${runtime_base}/client/start.js`, + app: `${to_fs(svelte_config.kit.outDir)}/generated/client/app.js`, + imports: [], + stylesheets: [], + fonts: [] + }, + nodes: manifest_data.nodes.map((node, index) => { + return async () => { + /** @type {import('types').SSRNode} */ + const result = {}; + + /** @type {import('vite').ModuleNode[]} */ + const module_nodes = []; + + result.index = index; + + // these are unused in dev, it's easier to include them + result.imports = []; + result.stylesheets = []; + result.fonts = []; + + if (node.component) { + result.component = async () => { + const { module_node, module } = await resolve( + /** @type {string} */ (node.component) + ); + + module_nodes.push(module_node); + + return module.default; + }; + } + + if (node.universal) { + const { module, module_node } = await resolve(node.universal); + + module_nodes.push(module_node); + + result.universal = module; + result.universal_id = node.universal; + } + + if (node.server) { + const { module } = await resolve(node.server); + result.server = module; + result.server_id = node.server; + } + + // in dev we inline all styles to avoid FOUC. this gets populated lazily so that + // components/stylesheets loaded via import() during `load` are included + result.inline_styles = async () => { + const deps = new Set(); + + for (const module_node of module_nodes) { + await find_deps(vite, module_node, deps); + } + + /** @type {Record} */ + const styles = {}; + + for (const dep of deps) { + const url = new URL(dep.url, 'dummy:/'); + const query = url.searchParams; + + if ( + (isCSSRequest(dep.file) || + (query.has('svelte') && query.get('type') === 'style')) && + !(query.has('raw') || query.has('url') || query.has('inline')) + ) { + try { + query.set('inline', ''); + const mod = await vite.ssrLoadModule( + `${decodeURI(url.pathname)}${url.search}${url.hash}` + ); + styles[dep.url] = mod.default; + } catch { + // this can happen with dynamically imported modules, I think + // because the Vite module graph doesn't distinguish between + // static and dynamic imports? TODO investigate, submit fix + } + } + } + + return styles; + }; + + return result; + }; + }), + routes: compact( + manifest_data.routes.map((route) => { + if (!route.page && !route.endpoint) return null; + + const endpoint = route.endpoint; + + return { + id: route.id, + pattern: route.pattern, + params: route.params, + page: route.page, + endpoint: endpoint + ? async () => { + const url = path.resolve(cwd, endpoint.file); + return await loud_ssr_load_module(url); + } + : null, + endpoint_id: endpoint?.file + }; + }) + ), + matchers: async () => { + /** @type {Record} */ + const matchers = {}; + + for (const key in manifest_data.matchers) { + const file = manifest_data.matchers[key]; + const url = path.resolve(cwd, file); + const module = await vite.ssrLoadModule(url); + + if (module.match) { + matchers[key] = module.match; + } else { + throw new Error(`${file} does not export a \`match\` function`); + } + } + + return matchers; + } + } + }; + } + + /** @param {string} stack */ + function fix_stack_trace(stack) { + return stack ? vite.ssrRewriteStacktrace(stack) : stack; + } + + await update_manifest(); + + /** + * @param {string} event + * @param {(file: string) => void} cb + */ + const watch = (event, cb) => { + vite.watcher.on(event, (file) => { + if ( + file.startsWith(svelte_config.kit.files.routes + path.sep) || + file.startsWith(svelte_config.kit.files.params + path.sep) || + // in contrast to server hooks, client hooks are written to the client manifest + // and therefore need rebuilding when they are added/removed + file.startsWith(svelte_config.kit.files.hooks.client) + ) { + cb(file); + } + }); + }; + /** @type {NodeJS.Timeout | null } */ + let timeout = null; + /** @param {() => void} to_run */ + const debounce = (to_run) => { + timeout && clearTimeout(timeout); + timeout = setTimeout(() => { + timeout = null; + to_run(); + }, 100); + }; + + // flag to skip watchers if server is already restarting + let restarting = false; + + // Debounce add/unlink events because in case of folder deletion or moves + // they fire in rapid succession, causing needless invocations. + watch('add', () => debounce(update_manifest)); + watch('unlink', () => debounce(update_manifest)); + watch('change', (file) => { + // Don't run for a single file if the whole manifest is about to get updated + if (timeout || restarting) return; + + sync.update(svelte_config, manifest_data, file); + }); + + const { appTemplate, errorTemplate, serviceWorker, hooks } = svelte_config.kit.files; + + // vite client only executes a full reload if the triggering html file path is index.html + // kit defaults to src/app.html, so unless user changed that to index.html + // send the vite client a full-reload event without path being set + if (appTemplate !== 'index.html') { + vite.watcher.on('change', (file) => { + if (file === appTemplate && !restarting) { + vite.ws.send({ type: 'full-reload' }); + } + }); + } + + vite.watcher.on('all', (_, file) => { + if ( + file === appTemplate || + file === errorTemplate || + file.startsWith(serviceWorker) || + file.startsWith(hooks.server) + ) { + sync.server(svelte_config); + } + }); + + // changing the svelte config requires restarting the dev server + // the config is only read on start and passed on to vite-plugin-svelte + // which needs up-to-date values to operate correctly + vite.watcher.on('change', (file) => { + if (path.basename(file) === 'svelte.config.js') { + console.log(`svelte config changed, restarting vite dev-server. changed file: ${file}`); + restarting = true; + vite.restart(); + } + }); + + const assets = svelte_config.kit.paths.assets ? SVELTE_KIT_ASSETS : svelte_config.kit.paths.base; + const asset_server = sirv(svelte_config.kit.files.assets, { + dev: true, + etag: true, + maxAge: 0, + extensions: [], + setHeaders: (res) => { + res.setHeader('access-control-allow-origin', '*'); + } + }); + + async function align_exports() { + // This shameful hack allows us to load runtime server code via Vite + // while apps load `HttpError` and `Redirect` in Node, without + // causing `instanceof` checks to fail + const control_module_node = await import('../../../runtime/control.js'); + const control_module_vite = await vite.ssrLoadModule(`${runtime_base}/control.js`); + + control_module_node.replace_implementations({ + ActionFailure: control_module_vite.ActionFailure, + HttpError: control_module_vite.HttpError, + Redirect: control_module_vite.Redirect + }); + } + align_exports(); + const ws_send = vite.ws.send; + /** @param {any} args */ + vite.ws.send = function (...args) { + // We need to reapply the patch after Vite did dependency optimizations + // because that clears the module resolutions + if (args[0]?.type === 'full-reload' && args[0].path === '*') { + align_exports(); + } + return ws_send.apply(vite.ws, args); + }; + + vite.middlewares.use(async (req, res, next) => { + try { + const base = `${vite.config.server.https ? 'https' : 'http'}://${ + req.headers[':authority'] || req.headers.host + }`; + + const decoded = decodeURI(new URL(base + req.url).pathname); + + if (decoded.startsWith(assets)) { + const pathname = decoded.slice(assets.length); + const file = svelte_config.kit.files.assets + pathname; + + if (fs.existsSync(file) && !fs.statSync(file).isDirectory()) { + if (has_correct_case(file, svelte_config.kit.files.assets)) { + req.url = encodeURI(pathname); // don't need query/hash + asset_server(req, res); + return; + } + } + } + + next(); + } catch (e) { + const error = coalesce_to_error(e); + res.statusCode = 500; + res.end(fix_stack_trace(/** @type {string} */ (error.stack))); + } + }); + + const env = loadEnv(vite_config.mode, svelte_config.kit.env.dir, ''); + + return () => { + const serve_static_middleware = vite.middlewares.stack.find( + (middleware) => + /** @type {function} */ (middleware.handle).name === 'viteServeStaticMiddleware' + ); + + // Vite will give a 403 on URLs like /test, /static, and /package.json preventing us from + // serving routes with those names. See https://github.com/vitejs/vite/issues/7363 + remove_static_middlewares(vite.middlewares); + + vite.middlewares.use(async (req, res) => { + // Vite's base middleware strips out the base path. Restore it + const original_url = req.url; + req.url = req.originalUrl; + try { + const base = `${vite.config.server.https ? 'https' : 'http'}://${ + req.headers[':authority'] || req.headers.host + }`; + + const decoded = decodeURI(new URL(base + req.url).pathname); + const file = posixify(path.resolve(decoded.slice(svelte_config.kit.paths.base.length + 1))); + const is_file = fs.existsSync(file) && !fs.statSync(file).isDirectory(); + const allowed = + !vite_config.server.fs.strict || + vite_config.server.fs.allow.some((dir) => file.startsWith(dir)); + + if (is_file && allowed) { + req.url = original_url; + // @ts-expect-error + serve_static_middleware.handle(req, res); + return; + } + + if (!decoded.startsWith(svelte_config.kit.paths.base)) { + return not_found(req, res, svelte_config.kit.paths.base); + } + + if (decoded === svelte_config.kit.paths.base + '/service-worker.js') { + const resolved = resolve_entry(svelte_config.kit.files.serviceWorker); + + if (resolved) { + res.writeHead(200, { + 'content-type': 'application/javascript' + }); + res.end(`import '${to_fs(resolved)}';`); + } else { + res.writeHead(404); + res.end('not found'); + } + + return; + } + + // we have to import `Server` before calling `set_assets` + const { Server } = /** @type {import('types').ServerModule} */ ( + await vite.ssrLoadModule(`${runtime_base}/server/index.js`) + ); + + const { set_fix_stack_trace } = await vite.ssrLoadModule( + `${runtime_base}/shared-server.js` + ); + set_fix_stack_trace(fix_stack_trace); + + const { set_assets } = await vite.ssrLoadModule('__sveltekit/paths'); + set_assets(assets); + + const server = new Server(manifest); + + await server.init({ env }); + + let request; + + try { + request = await getRequest({ + base, + request: req + }); + } catch (/** @type {any} */ err) { + res.statusCode = err.status || 400; + return res.end('Invalid request body'); + } + + if (manifest_error) { + console.error(colors.bold().red(manifest_error.message)); + + const error_page = load_error_page(svelte_config); + + /** @param {{ status: number; message: string }} opts */ + const error_template = ({ status, message }) => { + return error_page + .replace(/%sveltekit\.status%/g, String(status)) + .replace(/%sveltekit\.error\.message%/g, message); + }; + + res.writeHead(500, { + 'Content-Type': 'text/html; charset=utf-8' + }); + res.end( + error_template({ status: 500, message: manifest_error.message ?? 'Invalid routes' }) + ); + + return; + } + + const rendered = await server.respond(request, { + getClientAddress: () => { + const { remoteAddress } = req.socket; + if (remoteAddress) return remoteAddress; + throw new Error('Could not determine clientAddress'); + }, + read: (file) => fs.readFileSync(path.join(svelte_config.kit.files.assets, file)) + }); + + if (rendered.status === 404) { + // @ts-expect-error + serve_static_middleware.handle(req, res, () => { + setResponse(res, rendered); + }); + } else { + setResponse(res, rendered); + } + } catch (e) { + const error = coalesce_to_error(e); + res.statusCode = 500; + res.end(fix_stack_trace(/** @type {string} */ (error.stack))); + } + }); + }; +} + +/** + * @param {import('connect').Server} server + */ +function remove_static_middlewares(server) { + const static_middlewares = ['viteServeStaticMiddleware']; + for (let i = server.stack.length - 1; i > 0; i--) { + // @ts-expect-error using internals + if (static_middlewares.includes(server.stack[i].handle.name)) { + server.stack.splice(i, 1); + } + } +} + +/** + * @param {import('vite').ViteDevServer} vite + * @param {import('vite').ModuleNode} node + * @param {Set} deps + */ +async function find_deps(vite, node, deps) { + // since `ssrTransformResult.deps` contains URLs instead of `ModuleNode`s, this process is asynchronous. + // instead of using `await`, we resolve all branches in parallel. + /** @type {Promise[]} */ + const branches = []; + + /** @param {import('vite').ModuleNode} node */ + async function add(node) { + if (!deps.has(node)) { + deps.add(node); + await find_deps(vite, node, deps); + } + } + + /** @param {string} url */ + async function add_by_url(url) { + const node = await vite.moduleGraph.getModuleByUrl(url); + + if (node) { + await add(node); + } + } + + if (node.ssrTransformResult) { + if (node.ssrTransformResult.deps) { + node.ssrTransformResult.deps.forEach((url) => branches.push(add_by_url(url))); + } + + if (node.ssrTransformResult.dynamicDeps) { + node.ssrTransformResult.dynamicDeps.forEach((url) => branches.push(add_by_url(url))); + } + } else { + node.importedModules.forEach((node) => branches.push(add(node))); + } + + await Promise.all(branches); +} + +/** + * Determine if a file is being requested with the correct case, + * to ensure consistent behaviour between dev and prod and across + * operating systems. Note that we can't use realpath here, + * because we don't want to follow symlinks + * @param {string} file + * @param {string} assets + * @returns {boolean} + */ +function has_correct_case(file, assets) { + if (file === assets) return true; + + const parent = path.dirname(file); + + if (fs.readdirSync(parent).includes(path.basename(file))) { + return has_correct_case(parent, assets); + } + + return false; +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/index.js b/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/index.js new file mode 100644 index 0000000..fc683a0 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/index.js @@ -0,0 +1,99 @@ +import path from 'node:path'; +import { posixify } from '../../../utils/filesystem.js'; + +const ILLEGAL_IMPORTS = new Set(['\0$env/dynamic/private', '\0$env/static/private']); +const ILLEGAL_MODULE_NAME_PATTERN = /.*\.server\..+/; + +/** + * Checks if given id imports a module that is not allowed to be imported into client-side code. + * @param {string} id + * @param {{ + * cwd: string; + * node_modules: string; + * server: string; + * }} dirs + */ +export function is_illegal(id, dirs) { + if (ILLEGAL_IMPORTS.has(id)) return true; + if (!id.startsWith(dirs.cwd) || id.startsWith(dirs.node_modules)) return false; + return ILLEGAL_MODULE_NAME_PATTERN.test(path.basename(id)) || id.startsWith(dirs.server); +} + +/** + * Creates a guard that checks that no id imports a module that is not allowed to be imported into client-side code. + * @param {import('rollup').PluginContext} context + * @param {{ cwd: string; lib: string }} paths + */ +export function module_guard(context, { cwd, lib }) { + /** @type {Set} */ + const seen = new Set(); + + const dirs = { + // ids will be posixified, so we need to posixify these, too + cwd: posixify(cwd), + node_modules: posixify(path.join(cwd, 'node_modules')), + server: posixify(path.join(lib, 'server')) + }; + + /** + * @param {string} id + * @param {Array<{ id: string; dynamic: boolean }>} chain + */ + function follow(id, chain) { + if (seen.has(id)) return; + seen.add(id); + + if (is_illegal(id, dirs)) { + chain.shift(); // discard the entry point + id = normalize_id(id, lib, cwd); + + const pyramid = + chain.map(({ id, dynamic }, i) => { + id = normalize_id(id, lib, cwd); + + return `${' '.repeat(i * 2)}- ${id} ${dynamic ? 'dynamically imports' : 'imports'}\n`; + }) + `${' '.repeat(chain.length)}- ${id}`; + + const message = `Cannot import ${id} into client-side code:\n${pyramid}`; + + throw new Error(message); + } + + const module = context.getModuleInfo(id); + + if (module) { + for (const child of module.importedIds) { + follow(child, [...chain, { id, dynamic: false }]); + } + + for (const child of module.dynamicallyImportedIds) { + follow(child, [...chain, { id, dynamic: true }]); + } + } + } + + return { + /** @param {string} id should be posixified */ + check: (id) => { + follow(id, []); + } + }; +} + +/** + * Removes cwd/lib path from the start of the id + * @param {string} id + * @param {string} lib + * @param {string} cwd + */ +export function normalize_id(id, lib, cwd) { + if (id.startsWith(lib)) { + id = id.replace(lib, '$lib'); + } + + if (id.startsWith(cwd)) { + id = path.relative(cwd, id); + } + + return posixify(id); +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/types.d.ts b/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/types.d.ts new file mode 100644 index 0000000..1239fec --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/types.d.ts @@ -0,0 +1,5 @@ +export interface ImportGraph { + readonly id: string; + readonly dynamic: boolean; + readonly children: Generator; +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/utils.js b/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/utils.js new file mode 100644 index 0000000..bdfa7a4 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/graph_analysis/utils.js @@ -0,0 +1,6 @@ +const query_pattern = /\?.*$/s; + +/** @param {string} path */ +export function remove_query_from_id(path) { + return path.replace(query_pattern, ''); +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/index.js b/node_modules/@sveltejs/kit/src/exports/vite/index.js new file mode 100644 index 0000000..01625bd --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/index.js @@ -0,0 +1,899 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +import { svelte } from '@sveltejs/vite-plugin-svelte'; +import colors from 'kleur'; +import * as vite from 'vite'; + +import { mkdirp, posixify, read, resolve_entry, rimraf } from '../../utils/filesystem.js'; +import { create_static_module, create_dynamic_module } from '../../core/env.js'; +import * as sync from '../../core/sync/sync.js'; +import { create_assets } from '../../core/sync/create_manifest_data/index.js'; +import { runtime_directory, logger } from '../../core/utils.js'; +import { load_config } from '../../core/config/index.js'; +import { generate_manifest } from '../../core/generate_manifest/index.js'; +import { build_server_nodes } from './build/build_server.js'; +import { build_service_worker } from './build/build_service_worker.js'; +import { assets_base, find_deps } from './build/utils.js'; +import { dev } from './dev/index.js'; +import { is_illegal, module_guard, normalize_id } from './graph_analysis/index.js'; +import { preview } from './preview/index.js'; +import { get_config_aliases, get_env } from './utils.js'; +import { write_client_manifest } from '../../core/sync/write_client_manifest.js'; +import prerender from '../../core/postbuild/prerender.js'; +import analyse from '../../core/postbuild/analyse.js'; +import { s } from '../../utils/misc.js'; +import { hash } from '../../runtime/hash.js'; +import { dedent } from '../../core/sync/utils.js'; + +export { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; + +const cwd = process.cwd(); + +/** @type {import('./types').EnforcedConfig} */ +const enforced_config = { + appType: true, + base: true, + build: { + cssCodeSplit: true, + emptyOutDir: true, + lib: { + entry: true, + name: true, + formats: true + }, + manifest: true, + outDir: true, + rollupOptions: { + input: true, + output: { + format: true, + entryFileNames: true, + chunkFileNames: true, + assetFileNames: true + }, + preserveEntrySignatures: true + }, + ssr: true + }, + publicDir: true, + resolve: { + alias: { + $app: true, + $lib: true, + '$service-worker': true + } + }, + root: true +}; + +const options_regex = /(export\s+const\s+(prerender|csr|ssr|trailingSlash))\s*=/s; + +/** @type {Set} */ +const warned = new Set(); + +/** @type {import('@sveltejs/vite-plugin-svelte').PreprocessorGroup} */ +const warning_preprocessor = { + script: ({ content, filename }) => { + if (!filename) return; + + const basename = path.basename(filename); + if (basename.startsWith('+page.') || basename.startsWith('+layout.')) { + const match = content.match(options_regex); + if (match) { + const fixed = basename.replace('.svelte', '(.server).js/ts'); + + const message = + `\n${colors.bold().red(path.relative('.', filename))}\n` + + `\`${match[1]}\` will be ignored — move it to ${fixed} instead. See https://kit.svelte.dev/docs/page-options for more information.`; + + if (!warned.has(message)) { + console.log(message); + warned.add(message); + } + } + } + }, + markup: ({ content, filename }) => { + if (!filename) return; + + const basename = path.basename(filename); + if (basename.startsWith('+layout.') && !content.includes('` missing — inner content will not be rendered'; + + if (!warned.has(message)) { + console.log(message); + warned.add(message); + } + } + } +}; + +/** + * Returns the SvelteKit Vite plugins. + * @returns {Promise} + */ +export async function sveltekit() { + const svelte_config = await load_config(); + + /** @type {import('@sveltejs/vite-plugin-svelte').Options['preprocess']} */ + let preprocess = svelte_config.preprocess; + if (Array.isArray(preprocess)) { + preprocess = [...preprocess, warning_preprocessor]; + } else if (preprocess) { + preprocess = [preprocess, warning_preprocessor]; + } else { + preprocess = warning_preprocessor; + } + + /** @type {import('@sveltejs/vite-plugin-svelte').Options} */ + const vite_plugin_svelte_options = { + configFile: false, + extensions: svelte_config.extensions, + preprocess, + onwarn: svelte_config.onwarn, + compilerOptions: { + // @ts-expect-error SvelteKit requires hydratable true by default + hydratable: true, + ...svelte_config.compilerOptions + }, + ...svelte_config.vitePlugin + }; + + return [...svelte(vite_plugin_svelte_options), ...kit({ svelte_config })]; +} + +// These variables live outside the `kit()` function because it is re-invoked by each Vite build + +let secondary_build_started = false; + +/** @type {import('types').ManifestData} */ +let manifest_data; + +/** + * Returns the SvelteKit Vite plugin. Vite executes Rollup hooks as well as some of its own. + * Background reading is available at: + * - https://vitejs.dev/guide/api-plugin.html + * - https://rollupjs.org/guide/en/#plugin-development + * + * You can get an idea of the lifecycle by looking at the flow charts here: + * - https://rollupjs.org/guide/en/#build-hooks + * - https://rollupjs.org/guide/en/#output-generation-hooks + * + * @param {{ svelte_config: import('types').ValidatedConfig }} options + * @return {import('vite').Plugin[]} + */ +function kit({ svelte_config }) { + const { kit } = svelte_config; + const out = `${kit.outDir}/output`; + + const version_hash = hash(kit.version.name); + + /** @type {import('vite').ResolvedConfig} */ + let vite_config; + + /** @type {import('vite').ConfigEnv} */ + let vite_config_env; + + /** @type {boolean} */ + let is_build; + + /** @type {{ public: Record; private: Record }} */ + let env; + + /** @type {() => Promise} */ + let finalise; + + /** @type {import('vite').UserConfig} */ + let initial_config; + + const service_worker_entry_file = resolve_entry(kit.files.serviceWorker); + + const sourcemapIgnoreList = /** @param {string} relative_path */ (relative_path) => + relative_path.includes('node_modules') || relative_path.includes(kit.outDir); + + /** @type {import('vite').Plugin} */ + const plugin_setup = { + name: 'vite-plugin-sveltekit-setup', + + /** + * Build the SvelteKit-provided Vite config to be merged with the user's vite.config.js file. + * @see https://vitejs.dev/guide/api-plugin.html#config + */ + async config(config, config_env) { + initial_config = config; + vite_config_env = config_env; + is_build = config_env.command === 'build'; + + env = get_env(kit.env, vite_config_env.mode); + + const allow = new Set([ + kit.files.lib, + kit.files.routes, + kit.outDir, + path.resolve('src'), // TODO this isn't correct if user changed all his files to sth else than src (like in test/options) + path.resolve('node_modules'), + path.resolve(vite.searchForWorkspaceRoot(cwd), 'node_modules') + ]); + + // We can only add directories to the allow list, so we find out + // if there's a client hooks file and pass its directory + const client_hooks = resolve_entry(kit.files.hooks.client); + if (client_hooks) allow.add(path.dirname(client_hooks)); + + const generated = path.posix.join(kit.outDir, 'generated'); + + // dev and preview config can be shared + /** @type {import('vite').UserConfig} */ + const new_config = { + resolve: { + alias: [ + { find: '__SERVER__', replacement: `${generated}/server` }, + { find: '$app', replacement: `${runtime_directory}/app` }, + ...get_config_aliases(kit) + ] + }, + root: cwd, + server: { + cors: { preflightContinue: true }, + fs: { + allow: [...allow] + }, + sourcemapIgnoreList, + watch: { + ignored: [ + // Ignore all siblings of config.kit.outDir/generated + `${posixify(kit.outDir)}/!(generated)` + ] + } + }, + preview: { + cors: { preflightContinue: true } + }, + optimizeDeps: { + exclude: [ + '@sveltejs/kit', + // exclude kit features so that libraries using them work even when they are prebundled + // this does not affect app code, just handling of imported libraries that use $app or $env + '$app', + '$env' + ] + }, + ssr: { + noExternal: [ + // This ensures that esm-env is inlined into the server output with the + // export conditions resolved correctly through Vite. This prevents adapters + // that bundle later on from resolving the export conditions incorrectly + // and for example include browser-only code in the server output + // because they for example use esbuild.build with `platform: 'browser'` + 'esm-env', + // We need this for two reasons: + // 1. Without this, `@sveltejs/kit` imports are kept as-is in the server output, + // and that causes modules and therefore classes like `Redirect` to be imported twice + // under different IDs, which breaks a bunch of stuff because of failing instanceof checks. + // 2. Vitest bypasses Vite when loading external modules, so we bundle + // when it is detected to keep our virtual modules working. + // See https://github.com/sveltejs/kit/pull/9172 + // and https://vitest.dev/config/#deps-registernodeloader + '@sveltejs/kit' + ] + } + }; + + if (is_build) { + if (!new_config.build) new_config.build = {}; + new_config.build.ssr = !secondary_build_started; + + new_config.define = { + __SVELTEKIT_ADAPTER_NAME__: s(kit.adapter?.name), + __SVELTEKIT_APP_VERSION_FILE__: s(`${kit.appDir}/version.json`), + __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: s(kit.version.pollInterval), + __SVELTEKIT_DEV__: 'false', + __SVELTEKIT_EMBEDDED__: kit.embedded ? 'true' : 'false' + }; + + if (!secondary_build_started) { + manifest_data = (await sync.all(svelte_config, config_env.mode)).manifest_data; + } + } else { + new_config.define = { + __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: '0', + __SVELTEKIT_DEV__: 'true', + __SVELTEKIT_EMBEDDED__: kit.embedded ? 'true' : 'false' + }; + + // These Kit dependencies are packaged as CommonJS, which means they must always be externalized. + // Without this, the tests will still pass but `pnpm dev` will fail in projects that link `@sveltejs/kit`. + /** @type {NonNullable} */ (new_config.ssr).external = [ + 'cookie', + 'set-cookie-parser' + ]; + } + + warn_overridden_config(config, new_config); + + return new_config; + }, + + /** + * Stores the final config. + */ + configResolved(config) { + vite_config = config; + + // This is a hack to prevent Vite from nuking useful logs, + // pending https://github.com/vitejs/vite/issues/9378 + config.logger.warn(''); + } + }; + + /** @type {import('vite').Plugin} */ + const plugin_virtual_modules = { + name: 'vite-plugin-sveltekit-virtual-modules', + + async resolveId(id) { + // treat $env/static/[public|private] as virtual + if (id.startsWith('$env/') || id.startsWith('__sveltekit/') || id === '$service-worker') { + return `\0${id}`; + } + }, + + async load(id, options) { + const browser = !options?.ssr; + + const global = is_build + ? `globalThis.__sveltekit_${version_hash}` + : 'globalThis.__sveltekit_dev'; + + if (options?.ssr === false && process.env.TEST !== 'true') { + const normalized_cwd = vite.normalizePath(cwd); + const normalized_lib = vite.normalizePath(kit.files.lib); + if ( + is_illegal(id, { + cwd: normalized_cwd, + node_modules: vite.normalizePath(path.resolve('node_modules')), + server: vite.normalizePath(path.join(normalized_lib, 'server')) + }) + ) { + const relative = normalize_id(id, normalized_lib, normalized_cwd); + throw new Error(`Cannot import ${relative} into client-side code`); + } + } + + switch (id) { + case '\0$env/static/private': + return create_static_module('$env/static/private', env.private); + + case '\0$env/static/public': + return create_static_module('$env/static/public', env.public); + + case '\0$env/dynamic/private': + return create_dynamic_module( + 'private', + vite_config_env.command === 'serve' ? env.private : undefined + ); + + case '\0$env/dynamic/public': + // populate `$env/dynamic/public` from `window` + if (browser) { + return `export const env = ${global}.env;`; + } + + return create_dynamic_module( + 'public', + vite_config_env.command === 'serve' ? env.public : undefined + ); + + case '\0$service-worker': + return create_service_worker_module(svelte_config); + + // for internal use only. it's published as $app/paths externally + // we use this alias so that we won't collide with user aliases + case '\0__sveltekit/paths': { + const { assets, base } = svelte_config.kit.paths; + + // use the values defined in `global`, but fall back to hard-coded values + // for the sake of things like Vitest which may import this module + // outside the context of a page + if (browser) { + return dedent` + export const base = ${global}?.base ?? ${s(base)}; + export const assets = ${global}?.assets ?? ${assets ? s(assets) : 'base'}; + `; + } + + return dedent` + export let base = ${s(base)}; + export let assets = ${assets ? s(assets) : 'base'}; + + export const relative = ${svelte_config.kit.paths.relative}; + + const initial = { base, assets }; + + export function override(paths) { + base = paths.base; + assets = paths.assets; + } + + export function reset() { + base = initial.base; + assets = initial.assets; + } + + /** @param {string} path */ + export function set_assets(path) { + assets = initial.assets = path; + } + `; + } + + case '\0__sveltekit/environment': { + const { version } = svelte_config.kit; + + return dedent` + export const version = ${s(version.name)}; + export let building = false; + + export function set_building() { + building = true; + } + `; + } + } + } + }; + + /** + * Ensures that client-side code can't accidentally import server-side code, + * whether in `*.server.js` files, `$lib/server`, or `$env/[static|dynamic]/private` + * @type {import('vite').Plugin} + */ + const plugin_guard = { + name: 'vite-plugin-sveltekit-guard', + + writeBundle: { + sequential: true, + async handler(_options) { + if (vite_config.build.ssr) return; + + const guard = module_guard(this, { + cwd: vite.normalizePath(process.cwd()), + lib: vite.normalizePath(kit.files.lib) + }); + + manifest_data.nodes.forEach((_node, i) => { + const id = vite.normalizePath( + path.resolve(kit.outDir, `generated/client-optimized/nodes/${i}.js`) + ); + + guard.check(id); + }); + } + } + }; + + /** @type {import('vite').Plugin} */ + const plugin_compile = { + name: 'vite-plugin-sveltekit-compile', + + /** + * Build the SvelteKit-provided Vite config to be merged with the user's vite.config.js file. + * @see https://vitejs.dev/guide/api-plugin.html#config + */ + async config(config) { + /** @type {import('vite').UserConfig} */ + let new_config; + + if (is_build) { + const ssr = /** @type {boolean} */ (config.build?.ssr); + const prefix = `${kit.appDir}/immutable`; + + /** @type {Record} */ + const input = {}; + + if (ssr) { + input.index = `${runtime_directory}/server/index.js`; + input.internal = `${kit.outDir}/generated/server/internal.js`; + + // add entry points for every endpoint... + manifest_data.routes.forEach((route) => { + if (route.endpoint) { + const resolved = path.resolve(route.endpoint.file); + const relative = decodeURIComponent(path.relative(kit.files.routes, resolved)); + const name = posixify(path.join('entries/endpoints', relative.replace(/\.js$/, ''))); + input[name] = resolved; + } + }); + + // ...and every component used by pages... + manifest_data.nodes.forEach((node) => { + for (const file of [node.component, node.universal, node.server]) { + if (file) { + const resolved = path.resolve(file); + const relative = decodeURIComponent(path.relative(kit.files.routes, resolved)); + + const name = relative.startsWith('..') + ? posixify(path.join('entries/fallbacks', path.basename(file))) + : posixify(path.join('entries/pages', relative.replace(/\.js$/, ''))); + input[name] = resolved; + } + } + }); + + // ...and every matcher + Object.entries(manifest_data.matchers).forEach(([key, file]) => { + const name = posixify(path.join('entries/matchers', key)); + input[name] = path.resolve(file); + }); + } else { + input['entry/start'] = `${runtime_directory}/client/start.js`; + input['entry/app'] = `${kit.outDir}/generated/client-optimized/app.js`; + + manifest_data.nodes.forEach((node, i) => { + if (node.component || node.universal) { + input[`nodes/${i}`] = `${kit.outDir}/generated/client-optimized/nodes/${i}.js`; + } + }); + } + + // see the kit.output.preloadStrategy option for details on why we have multiple options here + const ext = kit.output.preloadStrategy === 'preload-mjs' ? 'mjs' : 'js'; + + // We could always use a relative asset base path here, but it's better for performance not to. + // E.g. Vite generates `new URL('/asset.png', import.meta).href` for a relative path vs just '/asset.png'. + // That's larger and takes longer to run and also causes an HTML diff between SSR and client + // causing us to do a more expensive hydration check. + const client_base = + kit.paths.relative !== false || kit.paths.assets ? './' : kit.paths.base || '/'; + + new_config = { + base: ssr ? assets_base(kit) : client_base, + build: { + copyPublicDir: !ssr, + cssCodeSplit: true, + cssMinify: initial_config.build?.minify == null ? true : !!initial_config.build.minify, + // don't use the default name to avoid collisions with 'static/manifest.json' + manifest: 'vite-manifest.json', + outDir: `${out}/${ssr ? 'server' : 'client'}`, + rollupOptions: { + input, + output: { + format: 'esm', + entryFileNames: ssr ? '[name].js' : `${prefix}/[name].[hash].${ext}`, + chunkFileNames: ssr ? 'chunks/[name].js' : `${prefix}/chunks/[name].[hash].${ext}`, + assetFileNames: `${prefix}/assets/[name].[hash][extname]`, + hoistTransitiveImports: false, + sourcemapIgnoreList + }, + preserveEntrySignatures: 'strict' + }, + ssrEmitAssets: true, + target: ssr ? 'node16.14' : undefined + }, + publicDir: kit.files.assets, + worker: { + rollupOptions: { + output: { + entryFileNames: `${prefix}/workers/[name]-[hash].js`, + chunkFileNames: `${prefix}/workers/chunks/[name]-[hash].js`, + assetFileNames: `${prefix}/workers/assets/[name]-[hash][extname]`, + hoistTransitiveImports: false + } + } + } + }; + } else { + new_config = { + appType: 'custom', + base: kit.paths.base, + build: { + rollupOptions: { + // Vite dependency crawler needs an explicit JS entry point + // eventhough server otherwise works without it + input: `${runtime_directory}/client/start.js` + } + }, + publicDir: kit.files.assets + }; + } + + warn_overridden_config(config, new_config); + + return new_config; + }, + + /** + * Adds the SvelteKit middleware to do SSR in dev mode. + * @see https://vitejs.dev/guide/api-plugin.html#configureserver + */ + async configureServer(vite) { + return await dev(vite, vite_config, svelte_config); + }, + + /** + * Adds the SvelteKit middleware to do SSR in preview mode. + * @see https://vitejs.dev/guide/api-plugin.html#configurepreviewserver + */ + configurePreviewServer(vite) { + return preview(vite, vite_config, svelte_config); + }, + + /** + * Clears the output directories. + */ + buildStart() { + if (secondary_build_started) return; + + if (is_build) { + if (!vite_config.build.watch) { + rimraf(out); + } + mkdirp(out); + } + }, + + generateBundle() { + if (vite_config.build.ssr) return; + + this.emitFile({ + type: 'asset', + fileName: `${kit.appDir}/version.json`, + source: s({ version: kit.version.name }) + }); + }, + + /** + * Vite builds a single bundle. We need three bundles: client, server, and service worker. + * The user's package.json scripts will invoke the Vite CLI to execute the server build. We + * then use this hook to kick off builds for the client and service worker. + */ + writeBundle: { + sequential: true, + async handler(_options) { + if (secondary_build_started) return; // only run this once + + const verbose = vite_config.logLevel === 'info'; + const log = logger({ verbose }); + + /** @type {import('vite').Manifest} */ + const server_manifest = JSON.parse(read(`${out}/server/${vite_config.build.manifest}`)); + + /** @type {import('types').BuildData} */ + const build_data = { + app_dir: kit.appDir, + app_path: `${kit.paths.base.slice(1)}${kit.paths.base ? '/' : ''}${kit.appDir}`, + manifest_data, + service_worker: service_worker_entry_file ? 'service-worker.js' : null, // TODO make file configurable? + client: null, + server_manifest + }; + + const manifest_path = `${out}/server/manifest-full.js`; + fs.writeFileSync( + manifest_path, + `export const manifest = ${generate_manifest({ + build_data, + relative_path: '.', + routes: manifest_data.routes + })};\n` + ); + + // first, build server nodes without the client manifest so we can analyse it + log.info('Analysing routes'); + + build_server_nodes(out, kit, manifest_data, server_manifest, null, null); + + const metadata = await analyse({ + manifest_path, + env: { ...env.private, ...env.public } + }); + + log.info('Building app'); + + // create client build + write_client_manifest( + kit, + manifest_data, + `${kit.outDir}/generated/client-optimized`, + metadata.nodes + ); + + secondary_build_started = true; + + const { output } = /** @type {import('rollup').RollupOutput} */ ( + await vite.build({ + configFile: vite_config.configFile, + // CLI args + mode: vite_config_env.mode, + logLevel: vite_config.logLevel, + clearScreen: vite_config.clearScreen, + build: { + minify: initial_config.build?.minify, + assetsInlineLimit: vite_config.build.assetsInlineLimit, + sourcemap: vite_config.build.sourcemap + }, + optimizeDeps: { + force: vite_config.optimizeDeps.force + } + }) + ); + + /** @type {import('vite').Manifest} */ + const client_manifest = JSON.parse(read(`${out}/client/${vite_config.build.manifest}`)); + + const deps_of = /** @param {string} f */ (f) => + find_deps(client_manifest, posixify(path.relative('.', f)), false); + const start = deps_of(`${runtime_directory}/client/start.js`); + const app = deps_of(`${kit.outDir}/generated/client-optimized/app.js`); + + build_data.client = { + start: start.file, + app: app.file, + imports: [...start.imports, ...app.imports], + stylesheets: [...start.stylesheets, ...app.stylesheets], + fonts: [...start.fonts, ...app.fonts] + }; + + const css = output.filter( + /** @type {(value: any) => value is import('rollup').OutputAsset} */ + (value) => value.type === 'asset' && value.fileName.endsWith('.css') + ); + + // regenerate manifest now that we have client entry... + fs.writeFileSync( + manifest_path, + `export const manifest = ${generate_manifest({ + build_data, + relative_path: '.', + routes: manifest_data.routes + })};\n` + ); + + // regenerate nodes with the client manifest... + build_server_nodes(out, kit, manifest_data, server_manifest, client_manifest, css); + + // ...and prerender + const { prerendered, prerender_map } = await prerender({ + out, + manifest_path, + metadata, + verbose, + env: { ...env.private, ...env.public } + }); + + // generate a new manifest that doesn't include prerendered pages + fs.writeFileSync( + `${out}/server/manifest.js`, + `export const manifest = ${generate_manifest({ + build_data, + relative_path: '.', + routes: manifest_data.routes.filter((route) => prerender_map.get(route.id) !== true) + })};\n` + ); + + if (service_worker_entry_file) { + if (kit.paths.assets) { + throw new Error('Cannot use service worker alongside config.kit.paths.assets'); + } + + log.info('Building service worker'); + + await build_service_worker( + out, + kit, + vite_config, + manifest_data, + service_worker_entry_file, + prerendered, + client_manifest + ); + } + + // we need to defer this to closeBundle, so that adapters copy files + // created by other Vite plugins + finalise = async () => { + console.log( + `\nRun ${colors + .bold() + .cyan('npm run preview')} to preview your production build locally.` + ); + + // avoid making the manifest available to users + fs.unlinkSync(`${out}/client/${vite_config.build.manifest}`); + fs.unlinkSync(`${out}/server/${vite_config.build.manifest}`); + + if (kit.adapter) { + const { adapt } = await import('../../core/adapt/index.js'); + await adapt(svelte_config, build_data, metadata, prerendered, prerender_map, log); + } else { + console.log(colors.bold().yellow('\nNo adapter specified')); + + const link = colors.bold().cyan('https://kit.svelte.dev/docs/adapters'); + console.log( + `See ${link} to learn how to configure your app to run on the platform of your choosing` + ); + } + + secondary_build_started = false; + }; + } + }, + + /** + * Runs the adapter. + */ + closeBundle: { + sequential: true, + async handler() { + if (!vite_config.build.ssr) return; + await finalise?.(); + } + } + }; + + return [plugin_setup, plugin_virtual_modules, plugin_guard, plugin_compile]; +} + +/** + * @param {Record} config + * @param {Record} resolved_config + */ +function warn_overridden_config(config, resolved_config) { + const overridden = find_overridden_config(config, resolved_config, enforced_config, '', []); + + if (overridden.length > 0) { + console.error( + colors.bold().red('The following Vite config options will be overridden by SvelteKit:') + + overridden.map((key) => `\n - ${key}`).join('') + ); + } +} + +/** + * @param {Record} config + * @param {Record} resolved_config + * @param {import('./types').EnforcedConfig} enforced_config + * @param {string} path + * @param {string[]} out used locally to compute the return value + */ +function find_overridden_config(config, resolved_config, enforced_config, path, out) { + if (config == null || resolved_config == null) { + return out; + } + + for (const key in enforced_config) { + if (typeof config === 'object' && key in config && key in resolved_config) { + const enforced = enforced_config[key]; + + if (enforced === true) { + if (config[key] !== resolved_config[key]) { + out.push(path + key); + } + } else { + find_overridden_config(config[key], resolved_config[key], enforced, path + key + '.', out); + } + } + } + return out; +} + +/** + * @param {import('types').ValidatedConfig} config + */ +const create_service_worker_module = (config) => dedent` + if (typeof self === 'undefined' || self instanceof ServiceWorkerGlobalScope === false) { + throw new Error('This module can only be imported inside a service worker'); + } + + export const build = []; + export const files = [ + ${create_assets(config) + .filter((asset) => config.kit.serviceWorker.files(asset.file)) + .map((asset) => `${s(`${config.kit.paths.base}/${asset.file}`)}`) + .join(',\n')} + ]; + export const prerendered = []; + export const version = ${s(config.kit.version.name)}; +`; diff --git a/node_modules/@sveltejs/kit/src/exports/vite/preview/index.js b/node_modules/@sveltejs/kit/src/exports/vite/preview/index.js new file mode 100644 index 0000000..1e5045d --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/preview/index.js @@ -0,0 +1,223 @@ +import fs from 'node:fs'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import sirv from 'sirv'; +import { loadEnv, normalizePath } from 'vite'; +import { getRequest, setResponse } from '../../../exports/node/index.js'; +import { installPolyfills } from '../../../exports/node/polyfills.js'; +import { SVELTE_KIT_ASSETS } from '../../../constants.js'; +import { should_polyfill } from '../../../utils/platform.js'; +import { not_found } from '../utils.js'; + +/** @typedef {import('http').IncomingMessage} Req */ +/** @typedef {import('http').ServerResponse} Res */ +/** @typedef {(req: Req, res: Res, next: () => void) => void} Handler */ + +/** + * @param {{ + * middlewares: import('connect').Server; + * httpServer: import('http').Server; + * }} vite + * @param {import('vite').ResolvedConfig} vite_config + * @param {import('types').ValidatedConfig} svelte_config + */ +export async function preview(vite, vite_config, svelte_config) { + if (should_polyfill) { + installPolyfills(); + } + + const { paths } = svelte_config.kit; + const base = paths.base; + const assets = paths.assets ? SVELTE_KIT_ASSETS : paths.base; + + const protocol = vite_config.preview.https ? 'https' : 'http'; + + const etag = `"${Date.now()}"`; + + const dir = join(svelte_config.kit.outDir, 'output/server'); + + if (!fs.existsSync(dir)) { + throw new Error(`Server files not found at ${dir}, did you run \`build\` first?`); + } + + /** @type {import('types').ServerInternalModule} */ + const { set_assets } = await import(pathToFileURL(join(dir, 'internal.js')).href); + + /** @type {import('types').ServerModule} */ + const { Server } = await import(pathToFileURL(join(dir, 'index.js')).href); + + const { manifest } = await import(pathToFileURL(join(dir, 'manifest.js')).href); + + set_assets(assets); + + const server = new Server(manifest); + await server.init({ + env: loadEnv(vite_config.mode, svelte_config.kit.env.dir, '') + }); + + return () => { + // generated client assets and the contents of `static` + vite.middlewares.use( + scoped( + assets, + sirv(join(svelte_config.kit.outDir, 'output/client'), { + setHeaders: (res, pathname) => { + // only apply to immutable directory, not e.g. version.json + if (pathname.startsWith(`/${svelte_config.kit.appDir}/immutable`)) { + res.setHeader('cache-control', 'public,max-age=31536000,immutable'); + } + } + }) + ) + ); + + vite.middlewares.use((req, res, next) => { + const original_url = /** @type {string} */ (req.url); + const { pathname } = new URL(original_url, 'http://dummy'); + + if (pathname.startsWith(base)) { + next(); + } else { + res.statusCode = 404; + not_found(req, res, base); + } + }); + + // prerendered dependencies + vite.middlewares.use( + scoped(base, mutable(join(svelte_config.kit.outDir, 'output/prerendered/dependencies'))) + ); + + // prerendered pages (we can't just use sirv because we need to + // preserve the correct trailingSlash behaviour) + vite.middlewares.use( + scoped(base, (req, res, next) => { + let if_none_match_value = req.headers['if-none-match']; + + if (if_none_match_value?.startsWith('W/"')) { + if_none_match_value = if_none_match_value.substring(2); + } + + if (if_none_match_value === etag) { + res.statusCode = 304; + res.end(); + return; + } + + const { pathname } = new URL(/** @type {string} */ (req.url), 'http://dummy'); + + let filename = normalizePath( + join(svelte_config.kit.outDir, 'output/prerendered/pages' + pathname) + ); + let prerendered = is_file(filename); + + if (!prerendered) { + const has_trailing_slash = pathname.endsWith('/'); + const html_filename = `${filename}${has_trailing_slash ? 'index.html' : '.html'}`; + + let redirect; + + if (is_file(html_filename)) { + filename = html_filename; + prerendered = true; + } else if (has_trailing_slash) { + if (is_file(filename.slice(0, -1) + '.html')) { + redirect = pathname.slice(0, -1); + } + } else if (is_file(filename + '/index.html')) { + redirect = pathname + '/'; + } + + if (redirect) { + res.writeHead(307, { + location: redirect + }); + + res.end(); + + return; + } + } + + if (prerendered) { + res.writeHead(200, { + 'content-type': 'text/html', + etag + }); + + fs.createReadStream(filename).pipe(res); + } else { + next(); + } + }) + ); + + // SSR + vite.middlewares.use(async (req, res) => { + const host = req.headers['host']; + + let request; + + try { + request = await getRequest({ + base: `${protocol}://${host}`, + request: req + }); + } catch (/** @type {any} */ err) { + res.statusCode = err.status || 400; + return res.end('Invalid request body'); + } + + setResponse( + res, + await server.respond(request, { + getClientAddress: () => { + const { remoteAddress } = req.socket; + if (remoteAddress) return remoteAddress; + throw new Error('Could not determine clientAddress'); + }, + read: (file) => fs.readFileSync(join(svelte_config.kit.files.assets, file)) + }) + ); + }); + }; +} + +/** + * @param {string} dir + * @returns {Handler} + */ +const mutable = (dir) => + fs.existsSync(dir) + ? sirv(dir, { + etag: true, + maxAge: 0 + }) + : (_req, _res, next) => next(); + +/** + * @param {string} scope + * @param {Handler} handler + * @returns {Handler} + */ +function scoped(scope, handler) { + if (scope === '') return handler; + + return (req, res, next) => { + if (req.url?.startsWith(scope)) { + const original_url = req.url; + req.url = req.url.slice(scope.length); + handler(req, res, () => { + req.url = original_url; + next(); + }); + } else { + next(); + } + }; +} + +/** @param {string} path */ +function is_file(path) { + return fs.existsSync(path) && !fs.statSync(path).isDirectory(); +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/types.d.ts b/node_modules/@sveltejs/kit/src/exports/vite/types.d.ts new file mode 100644 index 0000000..900aa43 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/types.d.ts @@ -0,0 +1,3 @@ +export interface EnforcedConfig { + [key: string]: EnforcedConfig | true; +} diff --git a/node_modules/@sveltejs/kit/src/exports/vite/utils.js b/node_modules/@sveltejs/kit/src/exports/vite/utils.js new file mode 100644 index 0000000..7640868 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/exports/vite/utils.js @@ -0,0 +1,99 @@ +import path from 'node:path'; +import { loadEnv } from 'vite'; +import { posixify } from '../../utils/filesystem.js'; +import { negotiate } from '../../utils/http.js'; +import { filter_private_env, filter_public_env } from '../../utils/env.js'; + +/** + * Transforms kit.alias to a valid vite.resolve.alias array. + * + * Related to tsconfig path alias creation. + * + * @param {import('types').ValidatedKitConfig} config + * */ +export function get_config_aliases(config) { + /** @type {import('vite').Alias[]} */ + const alias = [ + // For now, we handle `$lib` specially here rather than make it a default value for + // `config.kit.alias` since it has special meaning for packaging, etc. + { find: '$lib', replacement: config.files.lib } + ]; + + for (let [key, value] of Object.entries(config.alias)) { + value = posixify(value); + if (value.endsWith('/*')) { + value = value.slice(0, -2); + } + if (key.endsWith('/*')) { + // Doing just `{ find: key.slice(0, -2) ,..}` would mean `import .. from "key"` would also be matched, which we don't want + alias.push({ + find: new RegExp(`^${escape_for_regexp(key.slice(0, -2))}\\/(.+)$`), + replacement: `${path.resolve(value)}/$1` + }); + } else if (key + '/*' in config.alias) { + // key and key/* both exist -> the replacement for key needs to happen _only_ on import .. from "key" + alias.push({ + find: new RegExp(`^${escape_for_regexp(key)}$`), + replacement: path.resolve(value) + }); + } else { + alias.push({ find: key, replacement: path.resolve(value) }); + } + } + + return alias; +} + +/** + * @param {string} str + */ +function escape_for_regexp(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, (match) => '\\' + match); +} + +/** + * Load environment variables from process.env and .env files + * @param {import('types').ValidatedKitConfig['env']} env_config + * @param {string} mode + */ +export function get_env(env_config, mode) { + const { publicPrefix: public_prefix, privatePrefix: private_prefix } = env_config; + const env = loadEnv(mode, env_config.dir, ''); + + return { + public: filter_public_env(env, { public_prefix, private_prefix }), + private: filter_private_env(env, { public_prefix, private_prefix }) + }; +} + +/** + * @param {import('http').IncomingMessage} req + * @param {import('http').ServerResponse} res + * @param {string} base + */ +export function not_found(req, res, base) { + const type = negotiate(req.headers.accept ?? '*', ['text/plain', 'text/html']); + + // special case — handle `/` request automatically + if (req.url === '/' && type === 'text/html') { + res.statusCode = 307; + res.setHeader('location', base); + res.end(); + return; + } + + res.statusCode = 404; + + const prefixed = base + req.url; + + if (type === 'text/html') { + res.setHeader('Content-Type', 'text/html'); + res.end( + `The server is configured with a public base URL of ${base} - did you mean to visit ${prefixed} instead?` + ); + } else { + res.end( + `The server is configured with a public base URL of ${base} - did you mean to visit ${prefixed} instead?` + ); + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/app/env.js b/node_modules/@sveltejs/kit/src/runtime/app/env.js new file mode 100644 index 0000000..927c4af --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/app/env.js @@ -0,0 +1 @@ +throw new Error('$app/env has been renamed to $app/environment'); diff --git a/node_modules/@sveltejs/kit/src/runtime/app/environment.js b/node_modules/@sveltejs/kit/src/runtime/app/environment.js new file mode 100644 index 0000000..8393ee6 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/app/environment.js @@ -0,0 +1,12 @@ +import { BROWSER, DEV } from 'esm-env'; +export { building, version } from '__sveltekit/environment'; + +/** + * `true` if the app is running in the browser. + */ +export const browser = BROWSER; + +/** + * Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`. + */ +export const dev = DEV; diff --git a/node_modules/@sveltejs/kit/src/runtime/app/forms.js b/node_modules/@sveltejs/kit/src/runtime/app/forms.js new file mode 100644 index 0000000..4b34f93 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/app/forms.js @@ -0,0 +1,240 @@ +import * as devalue from 'devalue'; +import { BROWSER, DEV } from 'esm-env'; +import { client } from '../client/singletons.js'; +import { invalidateAll } from './navigation.js'; + +/** + * This action updates the `form` property of the current page with the given data and updates `$page.status`. + * In case of an error, it redirects to the nearest error page. + * @template {Record | undefined} Success + * @template {Record | undefined} Failure + * @param {import('@sveltejs/kit').ActionResult} result + * @returns {Promise} + */ +export function applyAction(result) { + if (BROWSER) { + return client.apply_action(result); + } else { + throw new Error('Cannot call applyAction(...) on the server'); + } +} + +/** + * Use this function to deserialize the response from a form submission. + * Usage: + * + * ```js + * import { deserialize } from '$app/forms'; + * + * async function handleSubmit(event) { + * const response = await fetch('/form?/action', { + * method: 'POST', + * body: new FormData(event.target) + * }); + * + * const result = deserialize(await response.text()); + * // ... + * } + * ``` + * @template {Record | undefined} Success + * @template {Record | undefined} Failure + * @param {string} result + * @returns {import('@sveltejs/kit').ActionResult} + */ +export function deserialize(result) { + const parsed = JSON.parse(result); + if (parsed.data) { + parsed.data = devalue.parse(parsed.data); + } + return parsed; +} + +/** + * @param {string} old_name + * @param {string} new_name + * @param {string} call_location + * @returns void + */ +function warn_on_access(old_name, new_name, call_location) { + if (!DEV) return; + // TODO 2.0: Remove this code + console.warn( + `\`${old_name}\` has been deprecated in favor of \`${new_name}\`. \`${old_name}\` will be removed in a future version. (Called from ${call_location})` + ); +} + +/** + * Shallow clone an element, so that we can access e.g. `form.action` without worrying + * that someone has added an `` (https://github.com/sveltejs/kit/issues/7593) + * @template {HTMLElement} T + * @param {T} element + * @returns {T} + */ +function clone(element) { + return /** @type {T} */ (HTMLElement.prototype.cloneNode.call(element)); +} + +/** + * This action enhances a `` element that otherwise would work without JavaScript. + * + * The `submit` function is called upon submission with the given FormData and the `action` that should be triggered. + * If `cancel` is called, the form will not be submitted. + * You can use the abort `controller` to cancel the submission in case another one starts. + * If a function is returned, that function is called with the response from the server. + * If nothing is returned, the fallback will be used. + * + * If this function or its return value isn't set, it + * - falls back to updating the `form` prop with the returned data if the action is one same page as the form + * - updates `$page.status` + * - resets the `` element and invalidates all data in case of successful submission with no redirect response + * - redirects in case of a redirect response + * - redirects to the nearest error page in case of an unexpected error + * + * If you provide a custom function with a callback and want to use the default behavior, invoke `update` in your callback. + * @template {Record | undefined} Success + * @template {Record | undefined} Failure + * @param {HTMLFormElement} form_element The form element + * @param {import('@sveltejs/kit').SubmitFunction} submit Submit callback + */ +export function enhance(form_element, submit = () => {}) { + if (DEV && clone(form_element).method !== 'post') { + throw new Error('use:enhance can only be used on fields with method="POST"'); + } + + /** + * @param {{ + * action: URL; + * result: import('@sveltejs/kit').ActionResult; + * reset?: boolean + * }} opts + */ + const fallback_callback = async ({ action, result, reset }) => { + if (result.type === 'success') { + if (reset !== false) { + // We call reset from the prototype to avoid DOM clobbering + HTMLFormElement.prototype.reset.call(form_element); + } + await invalidateAll(); + } + + // For success/failure results, only apply action if it belongs to the + // current page, otherwise `form` will be updated erroneously + if ( + location.origin + location.pathname === action.origin + action.pathname || + result.type === 'redirect' || + result.type === 'error' + ) { + applyAction(result); + } + }; + + /** @param {SubmitEvent} event */ + async function handle_submit(event) { + const method = event.submitter?.hasAttribute('formmethod') + ? /** @type {HTMLButtonElement | HTMLInputElement} */ (event.submitter).formMethod + : clone(form_element).method; + if (method !== 'post') return; + + event.preventDefault(); + + const action = new URL( + // We can't do submitter.formAction directly because that property is always set + event.submitter?.hasAttribute('formaction') + ? /** @type {HTMLButtonElement | HTMLInputElement} */ (event.submitter).formAction + : clone(form_element).action + ); + + const form_data = new FormData(form_element); + + if (DEV && clone(form_element).enctype !== 'multipart/form-data') { + for (const value of form_data.values()) { + if (value instanceof File) { + // TODO 2.0: Upgrade to `throw Error` + console.warn( + 'Your form contains fields, but is missing the `enctype="multipart/form-data"` attribute. This will lead to inconsistent behavior between enhanced and native forms. For more details, see https://github.com/sveltejs/kit/issues/9819. This will be upgraded to an error in v2.0.' + ); + break; + } + } + } + + const submitter_name = event.submitter?.getAttribute('name'); + if (submitter_name) { + form_data.append(submitter_name, event.submitter?.getAttribute('value') ?? ''); + } + + const controller = new AbortController(); + + let cancelled = false; + const cancel = () => (cancelled = true); + + // TODO 2.0: Remove `data` and `form` + const callback = + (await submit({ + action, + cancel, + controller, + get data() { + warn_on_access('data', 'formData', 'use:enhance submit function'); + return form_data; + }, + formData: form_data, + get form() { + warn_on_access('form', 'formElement', 'use:enhance submit function'); + return form_element; + }, + formElement: form_element, + submitter: event.submitter + })) ?? fallback_callback; + if (cancelled) return; + + /** @type {import('@sveltejs/kit').ActionResult} */ + let result; + + try { + const response = await fetch(action, { + method: 'POST', + headers: { + accept: 'application/json', + 'x-sveltekit-action': 'true' + }, + cache: 'no-store', + body: form_data, + signal: controller.signal + }); + + result = deserialize(await response.text()); + if (result.type === 'error') result.status = response.status; + } catch (error) { + if (/** @type {any} */ (error)?.name === 'AbortError') return; + result = { type: 'error', error }; + } + + callback({ + action, + get data() { + warn_on_access('data', 'formData', 'callback returned from use:enhance submit function'); + return form_data; + }, + formData: form_data, + get form() { + warn_on_access('form', 'formElement', 'callback returned from use:enhance submit function'); + return form_element; + }, + formElement: form_element, + update: (opts) => fallback_callback({ action, result, reset: opts?.reset }), + // @ts-expect-error generic constraints stuff we don't care about + result + }); + } + + // @ts-expect-error + HTMLFormElement.prototype.addEventListener.call(form_element, 'submit', handle_submit); + + return { + destroy() { + // @ts-expect-error + HTMLFormElement.prototype.removeEventListener.call(form_element, 'submit', handle_submit); + } + }; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/app/navigation.js b/node_modules/@sveltejs/kit/src/runtime/app/navigation.js new file mode 100644 index 0000000..bea51d1 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/app/navigation.js @@ -0,0 +1,112 @@ +import { client_method } from '../client/singletons.js'; + +/** + * If called when the page is being updated following a navigation (in `onMount` or `afterNavigate` or an action, for example), this disables SvelteKit's built-in scroll handling. + * This is generally discouraged, since it breaks user expectations. + * @returns {void} + */ +export const disableScrollHandling = /* @__PURE__ */ client_method('disable_scroll_handling'); + +/** + * Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified `url`. + * For external URLs, use `window.location = url` instead of calling `goto(url)`. + * + * @type {(url: string | URL, opts?: { + * replaceState?: boolean; + * noScroll?: boolean; + * keepFocus?: boolean; + * invalidateAll?: boolean; + * state?: any + * }) => Promise} + * @param {string | URL} url Where to navigate to. Note that if you've set [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths) and the URL is root-relative, you need to prepend the base path if you want to navigate within the app. + * @param {Object} [opts] Options related to the navigation + * @param {boolean} [opts.replaceState] If `true`, will replace the current `history` entry rather than creating a new one with `pushState` + * @param {boolean} [opts.noScroll] If `true`, the browser will maintain its scroll position rather than scrolling to the top of the page after navigation + * @param {boolean} [opts.keepFocus] If `true`, the currently focused element will retain focus after navigation. Otherwise, focus will be reset to the body + * @param {boolean} [invalidateAll] If `true`, all `load` functions of the page will be rerun. See https://kit.svelte.dev/docs/load#rerunning-load-functions for more info on invalidation. + * @param {any} [opts.state] The state of the new/updated history entry + * @returns {Promise} + */ +export const goto = /* @__PURE__ */ client_method('goto'); + +/** + * Causes any `load` functions belonging to the currently active page to re-run if they depend on the `url` in question, via `fetch` or `depends`. Returns a `Promise` that resolves when the page is subsequently updated. + * + * If the argument is given as a `string` or `URL`, it must resolve to the same URL that was passed to `fetch` or `depends` (including query parameters). + * To create a custom identifier, use a string beginning with `[a-z]+:` (e.g. `custom:state`) — this is a valid URL. + * + * The `function` argument can be used define a custom predicate. It receives the full `URL` and causes `load` to rerun if `true` is returned. + * This can be useful if you want to invalidate based on a pattern instead of a exact match. + * + * ```ts + * // Example: Match '/path' regardless of the query parameters + * import { invalidate } from '$app/navigation'; + * + * invalidate((url) => url.pathname === '/path'); + * ``` + * @type {(url: string | URL | ((url: URL) => boolean)) => Promise} + * @param {string | URL | ((url: URL) => boolean)} url The invalidated URL + * @returns {Promise} + */ +export const invalidate = /* @__PURE__ */ client_method('invalidate'); + +/** + * Causes all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated. + * @type {() => Promise} + * @returns {Promise} + */ +export const invalidateAll = /* @__PURE__ */ client_method('invalidate_all'); + +/** + * Programmatically preloads the given page, which means + * 1. ensuring that the code for the page is loaded, and + * 2. calling the page's load function with the appropriate options. + * + * This is the same behaviour that SvelteKit triggers when the user taps or mouses over an `` element with `data-sveltekit-preload-data`. + * If the next navigation is to `href`, the values returned from load will be used, making navigation instantaneous. + * Returns a Promise that resolves when the preload is complete. + * + * @type {(href: string) => Promise} + * @param {string} href Page to preload + * @returns {Promise} + */ +export const preloadData = /* @__PURE__ */ client_method('preload_data'); + +/** + * Programmatically imports the code for routes that haven't yet been fetched. + * Typically, you might call this to speed up subsequent navigation. + * + * You can specify routes by any matching pathname such as `/about` (to match `src/routes/about/+page.svelte`) or `/blog/*` (to match `src/routes/blog/[slug]/+page.svelte`). + * + * Unlike `preloadData`, this won't call `load` functions. + * Returns a Promise that resolves when the modules have been imported. + * + * @type {(...urls: string[]) => Promise} + * @param {...string[]} urls + * @returns {Promise} + */ +export const preloadCode = /* @__PURE__ */ client_method('preload_code'); + +/** + * A navigation interceptor that triggers before we navigate to a new URL, whether by clicking a link, calling `goto(...)`, or using the browser back/forward controls. + * Calling `cancel()` will prevent the navigation from completing. If the navigation would have directly unloaded the current page, calling `cancel` will trigger the native + * browser unload confirmation dialog. In these cases, `navigation.willUnload` is `true`. + * + * When a navigation isn't client side, `navigation.to.route.id` will be `null`. + * + * `beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + * @type {(callback: (navigation: import('@sveltejs/kit').BeforeNavigate) => void) => void} + * @param {(navigation: import('@sveltejs/kit').BeforeNavigate) => void} callback + * @returns {void} + */ +export const beforeNavigate = /* @__PURE__ */ client_method('before_navigate'); + +/** + * A lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a new URL. + * + * `afterNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + * @type {(callback: (navigation: import('@sveltejs/kit').AfterNavigate) => void) => void} + * @param {(navigation: import('@sveltejs/kit').AfterNavigate) => void} callback + * @returns {void} + */ +export const afterNavigate = /* @__PURE__ */ client_method('after_navigate'); diff --git a/node_modules/@sveltejs/kit/src/runtime/app/paths.js b/node_modules/@sveltejs/kit/src/runtime/app/paths.js new file mode 100644 index 0000000..20c6b1c --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/app/paths.js @@ -0,0 +1 @@ +export { base, assets } from '__sveltekit/paths'; diff --git a/node_modules/@sveltejs/kit/src/runtime/app/stores.js b/node_modules/@sveltejs/kit/src/runtime/app/stores.js new file mode 100644 index 0000000..23ee5cd --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/app/stores.js @@ -0,0 +1,94 @@ +import { getContext } from 'svelte'; +import { browser } from './environment.js'; +import { stores as browser_stores } from '../client/singletons.js'; + +/** + * A function that returns all of the contextual stores. On the server, this must be called during component initialization. + * Only use this if you need to defer store subscription until after the component has mounted, for some reason. + */ +export const getStores = () => { + const stores = browser ? browser_stores : getContext('__svelte__'); + + return { + /** @type {typeof page} */ + page: { + subscribe: stores.page.subscribe + }, + /** @type {typeof navigating} */ + navigating: { + subscribe: stores.navigating.subscribe + }, + /** @type {typeof updated} */ + updated: stores.updated + }; +}; + +/** + * A readable store whose value contains page data. + * + * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + * + * @type {import('svelte/store').Readable} + */ +export const page = { + subscribe(fn) { + const store = __SVELTEKIT_DEV__ ? get_store('page') : getStores().page; + return store.subscribe(fn); + } +}; + +/** + * A readable store. + * When navigating starts, its value is a `Navigation` object with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties. + * When navigating finishes, its value reverts to `null`. + * + * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + * @type {import('svelte/store').Readable} + */ +export const navigating = { + subscribe(fn) { + const store = __SVELTEKIT_DEV__ ? get_store('navigating') : getStores().navigating; + return store.subscribe(fn); + } +}; + +/** + * A readable store whose initial value is `false`. If [`version.pollInterval`](https://kit.svelte.dev/docs/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update the store value to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling. + * + * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + * @type {import('svelte/store').Readable & { check(): Promise }} + */ +export const updated = { + subscribe(fn) { + const store = __SVELTEKIT_DEV__ ? get_store('updated') : getStores().updated; + + if (browser) { + updated.check = store.check; + } + + return store.subscribe(fn); + }, + check: () => { + throw new Error( + browser + ? 'Cannot check updated store before subscribing' + : 'Can only check updated store in browser' + ); + } +}; + +/** + * @template {keyof ReturnType} Name + * @param {Name} name + * @returns {ReturnType[Name]} + */ +function get_store(name) { + try { + return getStores()[name]; + } catch (e) { + throw new Error( + `Cannot subscribe to '${name}' store on the server outside of a Svelte component, as it is bound to the current request via component context. This prevents state from leaking between users.` + + 'For more information, see https://kit.svelte.dev/docs/state-management#avoid-shared-state-on-the-server' + ); + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/client/client.js b/node_modules/@sveltejs/kit/src/runtime/client/client.js new file mode 100644 index 0000000..84726b1 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/client.js @@ -0,0 +1,2012 @@ +import { DEV } from 'esm-env'; +import { onMount, tick } from 'svelte'; +import { + add_data_suffix, + decode_params, + decode_pathname, + make_trackable, + normalize_path +} from '../../utils/url.js'; +import { + initial_fetch, + lock_fetch, + native_fetch, + subsequent_fetch, + unlock_fetch +} from './fetcher.js'; +import { parse } from './parse.js'; +import * as storage from './session-storage.js'; +import { + find_anchor, + get_base_uri, + get_link_info, + get_router_options, + is_external_url, + scroll_state +} from './utils.js'; + +import { base } from '__sveltekit/paths'; +import * as devalue from 'devalue'; +import { compact } from '../../utils/array.js'; +import { validate_page_exports } from '../../utils/exports.js'; +import { unwrap_promises } from '../../utils/promises.js'; +import { HttpError, Redirect } from '../control.js'; +import { INVALIDATED_PARAM, validate_depends } from '../shared.js'; +import { INDEX_KEY, PRELOAD_PRIORITIES, SCROLL_KEY, SNAPSHOT_KEY } from './constants.js'; +import { stores } from './singletons.js'; + +let errored = false; + +// We track the scroll position associated with each history entry in sessionStorage, +// rather than on history.state itself, because when navigation is driven by +// popstate it's too late to update the scroll position associated with the +// state we're navigating from + +/** @typedef {{ x: number, y: number }} ScrollPosition */ +/** @type {Record} */ +const scroll_positions = storage.get(SCROLL_KEY) ?? {}; + +/** @type {Record} */ +const snapshots = storage.get(SNAPSHOT_KEY) ?? {}; + +/** @param {number} index */ +function update_scroll_positions(index) { + scroll_positions[index] = scroll_state(); +} + +/** + * @param {import('./types').SvelteKitApp} app + * @param {HTMLElement} target + * @returns {import('./types').Client} + */ +export function create_client(app, target) { + const routes = parse(app); + + const default_layout_loader = app.nodes[0]; + const default_error_loader = app.nodes[1]; + + // we import the root layout/error nodes eagerly, so that + // connectivity errors after initialisation don't nuke the app + default_layout_loader(); + default_error_loader(); + + const container = __SVELTEKIT_EMBEDDED__ ? target : document.documentElement; + /** @type {Array<((url: URL) => boolean)>} */ + const invalidated = []; + + /** + * An array of the `+layout.svelte` and `+page.svelte` component instances + * that currently live on the page — used for capturing and restoring snapshots. + * It's updated/manipulated through `bind:this` in `Root.svelte`. + * @type {import('svelte').SvelteComponent[]} + */ + const components = []; + + /** @type {{id: string, promise: Promise} | null} */ + let load_cache = null; + + const callbacks = { + /** @type {Array<(navigation: import('@sveltejs/kit').BeforeNavigate) => void>} */ + before_navigate: [], + + /** @type {Array<(navigation: import('@sveltejs/kit').AfterNavigate) => void>} */ + after_navigate: [] + }; + + /** @type {import('./types').NavigationState} */ + let current = { + branch: [], + error: null, + // @ts-ignore - we need the initial value to be null + url: null + }; + + /** this being true means we SSR'd */ + let hydrated = false; + let started = false; + let autoscroll = true; + let updating = false; + let navigating = false; + let hash_navigating = false; + + let force_invalidation = false; + + /** @type {import('svelte').SvelteComponent} */ + let root; + + // keeping track of the history index in order to prevent popstate navigation events if needed + let current_history_index = history.state?.[INDEX_KEY]; + + if (!current_history_index) { + // we use Date.now() as an offset so that cross-document navigations + // within the app don't result in data loss + current_history_index = Date.now(); + + // create initial history entry, so we can return here + history.replaceState( + { ...history.state, [INDEX_KEY]: current_history_index }, + '', + location.href + ); + } + + // if we reload the page, or Cmd-Shift-T back to it, + // recover scroll position + const scroll = scroll_positions[current_history_index]; + if (scroll) { + history.scrollRestoration = 'manual'; + scrollTo(scroll.x, scroll.y); + } + + /** @type {import('@sveltejs/kit').Page} */ + let page; + + /** @type {{}} */ + let token; + + /** @type {Promise | null} */ + let pending_invalidate; + + async function invalidate() { + // Accept all invalidations as they come, don't swallow any while another invalidation + // is running because subsequent invalidations may make earlier ones outdated, + // but batch multiple synchronous invalidations. + pending_invalidate = pending_invalidate || Promise.resolve(); + await pending_invalidate; + if (!pending_invalidate) return; + pending_invalidate = null; + + const url = new URL(location.href); + const intent = get_navigation_intent(url, true); + // Clear preload, it might be affected by the invalidation. + // Also solves an edge case where a preload is triggered, the navigation for it + // was then triggered and is still running while the invalidation kicks in, + // at which point the invalidation should take over and "win". + load_cache = null; + + const nav_token = (token = {}); + const navigation_result = intent && (await load_route(intent)); + if (nav_token !== token) return; + + if (navigation_result) { + if (navigation_result.type === 'redirect') { + return goto(new URL(navigation_result.location, url).href, {}, [url.pathname], nav_token); + } else { + if (navigation_result.props.page !== undefined) { + page = navigation_result.props.page; + } + root.$set(navigation_result.props); + } + } + } + + /** @param {number} index */ + function capture_snapshot(index) { + if (components.some((c) => c?.snapshot)) { + snapshots[index] = components.map((c) => c?.snapshot?.capture()); + } + } + + /** @param {number} index */ + function restore_snapshot(index) { + snapshots[index]?.forEach((value, i) => { + components[i]?.snapshot?.restore(value); + }); + } + + function persist_state() { + update_scroll_positions(current_history_index); + storage.set(SCROLL_KEY, scroll_positions); + + capture_snapshot(current_history_index); + storage.set(SNAPSHOT_KEY, snapshots); + } + + /** + * @param {string | URL} url + * @param {{ noScroll?: boolean; replaceState?: boolean; keepFocus?: boolean; state?: any; invalidateAll?: boolean }} opts + * @param {string[]} redirect_chain + * @param {{}} [nav_token] + */ + async function goto( + url, + { + noScroll = false, + replaceState = false, + keepFocus = false, + state = {}, + invalidateAll = false + }, + redirect_chain, + nav_token + ) { + if (typeof url === 'string') { + url = new URL(url, get_base_uri(document)); + } + + return navigate({ + url, + scroll: noScroll ? scroll_state() : null, + keepfocus: keepFocus, + redirect_chain, + details: { + state, + replaceState + }, + nav_token, + accepted: () => { + if (invalidateAll) { + force_invalidation = true; + } + }, + blocked: () => {}, + type: 'goto' + }); + } + + /** @param {import('./types').NavigationIntent} intent */ + async function preload_data(intent) { + load_cache = { + id: intent.id, + promise: load_route(intent).then((result) => { + if (result.type === 'loaded' && result.state.error) { + // Don't cache errors, because they might be transient + load_cache = null; + } + return result; + }) + }; + + return load_cache.promise; + } + + /** @param {...string} pathnames */ + async function preload_code(...pathnames) { + const matching = routes.filter((route) => pathnames.some((pathname) => route.exec(pathname))); + + const promises = matching.map((r) => { + return Promise.all([...r.layouts, r.leaf].map((load) => load?.[1]())); + }); + + await Promise.all(promises); + } + + /** @param {import('./types').NavigationFinished} result */ + function initialize(result) { + if (DEV && result.state.error && document.querySelector('vite-error-overlay')) return; + + current = result.state; + + const style = document.querySelector('style[data-sveltekit]'); + if (style) style.remove(); + + page = /** @type {import('@sveltejs/kit').Page} */ (result.props.page); + + root = new app.root({ + target, + props: { ...result.props, stores, components }, + hydrate: true + }); + + restore_snapshot(current_history_index); + + /** @type {import('@sveltejs/kit').AfterNavigate} */ + const navigation = { + from: null, + to: { + params: current.params, + route: { id: current.route?.id ?? null }, + url: new URL(location.href) + }, + willUnload: false, + type: 'enter' + }; + callbacks.after_navigate.forEach((fn) => fn(navigation)); + + started = true; + } + + /** + * + * @param {{ + * url: URL; + * params: Record; + * branch: Array; + * status: number; + * error: App.Error | null; + * route: import('types').CSRRoute | null; + * form?: Record | null; + * }} opts + */ + async function get_navigation_result_from_branch({ + url, + params, + branch, + status, + error, + route, + form + }) { + /** @type {import('types').TrailingSlash} */ + let slash = 'never'; + for (const node of branch) { + if (node?.slash !== undefined) slash = node.slash; + } + url.pathname = normalize_path(url.pathname, slash); + // eslint-disable-next-line + url.search = url.search; // turn `/?` into `/` + + /** @type {import('./types').NavigationFinished} */ + const result = { + type: 'loaded', + state: { + url, + params, + branch, + error, + route + }, + props: { + // @ts-ignore Somehow it's getting SvelteComponent and SvelteComponentDev mixed up + constructors: compact(branch).map((branch_node) => branch_node.node.component) + } + }; + + if (form !== undefined) { + result.props.form = form; + } + + let data = {}; + let data_changed = !page; + + let p = 0; + + for (let i = 0; i < Math.max(branch.length, current.branch.length); i += 1) { + const node = branch[i]; + const prev = current.branch[i]; + + if (node?.data !== prev?.data) data_changed = true; + if (!node) continue; + + data = { ...data, ...node.data }; + + // Only set props if the node actually updated. This prevents needless rerenders. + if (data_changed) { + result.props[`data_${p}`] = data; + } + + p += 1; + } + + const page_changed = + !current.url || + url.href !== current.url.href || + current.error !== error || + (form !== undefined && form !== page.form) || + data_changed; + + if (page_changed) { + result.props.page = { + error, + params, + route: { + id: route?.id ?? null + }, + status, + url: new URL(url), + form: form ?? null, + // The whole page store is updated, but this way the object reference stays the same + data: data_changed ? data : page.data + }; + } + + return result; + } + + /** + * Call the load function of the given node, if it exists. + * If `server_data` is passed, this is treated as the initial run and the page endpoint is not requested. + * + * @param {{ + * loader: import('types').CSRPageNodeLoader; + * parent: () => Promise>; + * url: URL; + * params: Record; + * route: { id: string | null }; + * server_data_node: import('./types').DataNode | null; + * }} options + * @returns {Promise} + */ + async function load_node({ loader, parent, url, params, route, server_data_node }) { + /** @type {Record | null} */ + let data = null; + + /** @type {import('types').Uses} */ + const uses = { + dependencies: new Set(), + params: new Set(), + parent: false, + route: false, + url: false + }; + + const node = await loader(); + + if (DEV) { + validate_page_exports(node.universal); + } + + if (node.universal?.load) { + /** @param {string[]} deps */ + function depends(...deps) { + for (const dep of deps) { + if (DEV) validate_depends(/** @type {string} */ (route.id), dep); + + const { href } = new URL(dep, url); + uses.dependencies.add(href); + } + } + + /** @type {import('@sveltejs/kit').LoadEvent} */ + const load_input = { + route: { + get id() { + uses.route = true; + return route.id; + } + }, + params: new Proxy(params, { + get: (target, key) => { + uses.params.add(/** @type {string} */ (key)); + return target[/** @type {string} */ (key)]; + } + }), + data: server_data_node?.data ?? null, + url: make_trackable(url, () => { + uses.url = true; + }), + async fetch(resource, init) { + /** @type {URL | string} */ + let requested; + + if (resource instanceof Request) { + requested = resource.url; + + // we're not allowed to modify the received `Request` object, so in order + // to fixup relative urls we create a new equivalent `init` object instead + init = { + // the request body must be consumed in memory until browsers + // implement streaming request bodies and/or the body getter + body: + resource.method === 'GET' || resource.method === 'HEAD' + ? undefined + : await resource.blob(), + cache: resource.cache, + credentials: resource.credentials, + headers: resource.headers, + integrity: resource.integrity, + keepalive: resource.keepalive, + method: resource.method, + mode: resource.mode, + redirect: resource.redirect, + referrer: resource.referrer, + referrerPolicy: resource.referrerPolicy, + signal: resource.signal, + ...init + }; + } else { + requested = resource; + } + + // we must fixup relative urls so they are resolved from the target page + const resolved = new URL(requested, url); + depends(resolved.href); + + // match ssr serialized data url, which is important to find cached responses + if (resolved.origin === url.origin) { + requested = resolved.href.slice(url.origin.length); + } + + // prerendered pages may be served from any origin, so `initial_fetch` urls shouldn't be resolved + return started + ? subsequent_fetch(requested, resolved.href, init) + : initial_fetch(requested, init); + }, + setHeaders: () => {}, // noop + depends, + parent() { + uses.parent = true; + return parent(); + } + }; + + if (DEV) { + try { + lock_fetch(); + data = (await node.universal.load.call(null, load_input)) ?? null; + if (data != null && Object.getPrototypeOf(data) !== Object.prototype) { + throw new Error( + `a load function related to route '${route.id}' returned ${ + typeof data !== 'object' + ? `a ${typeof data}` + : data instanceof Response + ? 'a Response object' + : Array.isArray(data) + ? 'an array' + : 'a non-plain object' + }, but must return a plain object at the top level (i.e. \`return {...}\`)` + ); + } + } finally { + unlock_fetch(); + } + } else { + data = (await node.universal.load.call(null, load_input)) ?? null; + } + data = data ? await unwrap_promises(data) : null; + } + + return { + node, + loader, + server: server_data_node, + universal: node.universal?.load ? { type: 'data', data, uses } : null, + data: data ?? server_data_node?.data ?? null, + slash: node.universal?.trailingSlash ?? server_data_node?.slash + }; + } + + /** + * @param {boolean} parent_changed + * @param {boolean} route_changed + * @param {boolean} url_changed + * @param {import('types').Uses | undefined} uses + * @param {Record} params + */ + function has_changed(parent_changed, route_changed, url_changed, uses, params) { + if (force_invalidation) return true; + + if (!uses) return false; + + if (uses.parent && parent_changed) return true; + if (uses.route && route_changed) return true; + if (uses.url && url_changed) return true; + + for (const param of uses.params) { + if (params[param] !== current.params[param]) return true; + } + + for (const href of uses.dependencies) { + if (invalidated.some((fn) => fn(new URL(href)))) return true; + } + + return false; + } + + /** + * @param {import('types').ServerDataNode | import('types').ServerDataSkippedNode | null} node + * @param {import('./types').DataNode | null} [previous] + * @returns {import('./types').DataNode | null} + */ + function create_data_node(node, previous) { + if (node?.type === 'data') return node; + if (node?.type === 'skip') return previous ?? null; + return null; + } + + /** + * @param {import('./types').NavigationIntent} intent + * @returns {Promise} + */ + async function load_route({ id, invalidating, url, params, route }) { + if (load_cache?.id === id) { + return load_cache.promise; + } + + const { errors, layouts, leaf } = route; + + const loaders = [...layouts, leaf]; + + // preload modules to avoid waterfall, but handle rejections + // so they don't get reported to Sentry et al (we don't need + // to act on the failures at this point) + errors.forEach((loader) => loader?.().catch(() => {})); + loaders.forEach((loader) => loader?.[1]().catch(() => {})); + + /** @type {import('types').ServerNodesResponse | import('types').ServerRedirectNode | null} */ + let server_data = null; + + const url_changed = current.url ? id !== current.url.pathname + current.url.search : false; + const route_changed = current.route ? route.id !== current.route.id : false; + + let parent_invalid = false; + const invalid_server_nodes = loaders.map((loader, i) => { + const previous = current.branch[i]; + + const invalid = + !!loader?.[0] && + (previous?.loader !== loader[1] || + has_changed(parent_invalid, route_changed, url_changed, previous.server?.uses, params)); + + if (invalid) { + // For the next one + parent_invalid = true; + } + + return invalid; + }); + + if (invalid_server_nodes.some(Boolean)) { + try { + server_data = await load_data(url, invalid_server_nodes); + } catch (error) { + return load_root_error_page({ + status: error instanceof HttpError ? error.status : 500, + error: await handle_error(error, { url, params, route: { id: route.id } }), + url, + route + }); + } + + if (server_data.type === 'redirect') { + return server_data; + } + } + + const server_data_nodes = server_data?.nodes; + + let parent_changed = false; + + const branch_promises = loaders.map(async (loader, i) => { + if (!loader) return; + + /** @type {import('./types').BranchNode | undefined} */ + const previous = current.branch[i]; + + const server_data_node = server_data_nodes?.[i]; + + // re-use data from previous load if it's still valid + const valid = + (!server_data_node || server_data_node.type === 'skip') && + loader[1] === previous?.loader && + !has_changed(parent_changed, route_changed, url_changed, previous.universal?.uses, params); + if (valid) return previous; + + parent_changed = true; + + if (server_data_node?.type === 'error') { + // rethrow and catch below + throw server_data_node; + } + + return load_node({ + loader: loader[1], + url, + params, + route, + parent: async () => { + const data = {}; + for (let j = 0; j < i; j += 1) { + Object.assign(data, (await branch_promises[j])?.data); + } + return data; + }, + server_data_node: create_data_node( + // server_data_node is undefined if it wasn't reloaded from the server; + // and if current loader uses server data, we want to reuse previous data. + server_data_node === undefined && loader[0] ? { type: 'skip' } : server_data_node ?? null, + loader[0] ? previous?.server : undefined + ) + }); + }); + + // if we don't do this, rejections will be unhandled + for (const p of branch_promises) p.catch(() => {}); + + /** @type {Array} */ + const branch = []; + + for (let i = 0; i < loaders.length; i += 1) { + if (loaders[i]) { + try { + branch.push(await branch_promises[i]); + } catch (err) { + if (err instanceof Redirect) { + return { + type: 'redirect', + location: err.location + }; + } + + let status = 500; + /** @type {App.Error} */ + let error; + + if (server_data_nodes?.includes(/** @type {import('types').ServerErrorNode} */ (err))) { + // this is the server error rethrown above, reconstruct but don't invoke + // the client error handler; it should've already been handled on the server + status = /** @type {import('types').ServerErrorNode} */ (err).status ?? status; + error = /** @type {import('types').ServerErrorNode} */ (err).error; + } else if (err instanceof HttpError) { + status = err.status; + error = err.body; + } else { + // Referenced node could have been removed due to redeploy, check + const updated = await stores.updated.check(); + if (updated) { + return await native_navigation(url); + } + + error = await handle_error(err, { params, url, route: { id: route.id } }); + } + + const error_load = await load_nearest_error_page(i, branch, errors); + if (error_load) { + return await get_navigation_result_from_branch({ + url, + params, + branch: branch.slice(0, error_load.idx).concat(error_load.node), + status, + error, + route + }); + } else { + // if we get here, it's because the root `load` function failed, + // and we need to fall back to the server + return await server_fallback(url, { id: route.id }, error, status); + } + } + } else { + // push an empty slot so we can rewind past gaps to the + // layout that corresponds with an +error.svelte page + branch.push(undefined); + } + } + + return await get_navigation_result_from_branch({ + url, + params, + branch, + status: 200, + error: null, + route, + // Reset `form` on navigation, but not invalidation + form: invalidating ? undefined : null + }); + } + + /** + * @param {number} i Start index to backtrack from + * @param {Array} branch Branch to backtrack + * @param {Array} errors All error pages for this branch + * @returns {Promise<{idx: number; node: import('./types').BranchNode} | undefined>} + */ + async function load_nearest_error_page(i, branch, errors) { + while (i--) { + if (errors[i]) { + let j = i; + while (!branch[j]) j -= 1; + try { + return { + idx: j + 1, + node: { + node: await /** @type {import('types').CSRPageNodeLoader } */ (errors[i])(), + loader: /** @type {import('types').CSRPageNodeLoader } */ (errors[i]), + data: {}, + server: null, + universal: null + } + }; + } catch (e) { + continue; + } + } + } + } + + /** + * @param {{ + * status: number; + * error: App.Error; + * url: URL; + * route: { id: string | null } + * }} opts + * @returns {Promise} + */ + async function load_root_error_page({ status, error, url, route }) { + /** @type {Record} */ + const params = {}; // error page does not have params + + /** @type {import('types').ServerDataNode | null} */ + let server_data_node = null; + + const default_layout_has_server_load = app.server_loads[0] === 0; + + if (default_layout_has_server_load) { + // TODO post-https://github.com/sveltejs/kit/discussions/6124 we can use + // existing root layout data + try { + const server_data = await load_data(url, [true]); + + if ( + server_data.type !== 'data' || + (server_data.nodes[0] && server_data.nodes[0].type !== 'data') + ) { + throw 0; + } + + server_data_node = server_data.nodes[0] ?? null; + } catch { + // at this point we have no choice but to fall back to the server, if it wouldn't + // bring us right back here, turning this into an endless loop + if (url.origin !== location.origin || url.pathname !== location.pathname || hydrated) { + await native_navigation(url); + } + } + } + + const root_layout = await load_node({ + loader: default_layout_loader, + url, + params, + route, + parent: () => Promise.resolve({}), + server_data_node: create_data_node(server_data_node) + }); + + /** @type {import('./types').BranchNode} */ + const root_error = { + node: await default_error_loader(), + loader: default_error_loader, + universal: null, + server: null, + data: null + }; + + return await get_navigation_result_from_branch({ + url, + params, + branch: [root_layout, root_error], + status, + error, + route: null + }); + } + + /** + * @param {URL} url + * @param {boolean} invalidating + */ + function get_navigation_intent(url, invalidating) { + if (is_external_url(url, base)) return; + + const path = get_url_path(url); + + for (const route of routes) { + const params = route.exec(path); + + if (params) { + const id = url.pathname + url.search; + /** @type {import('./types').NavigationIntent} */ + const intent = { id, invalidating, route, params: decode_params(params), url }; + return intent; + } + } + } + + /** @param {URL} url */ + function get_url_path(url) { + return decode_pathname(url.pathname.slice(base.length) || '/'); + } + + /** + * @param {{ + * url: URL; + * type: import('@sveltejs/kit').NavigationType; + * intent?: import('./types').NavigationIntent; + * delta?: number; + * }} opts + */ + function before_navigate({ url, type, intent, delta }) { + let should_block = false; + + /** @type {import('@sveltejs/kit').Navigation} */ + const navigation = { + from: { + params: current.params, + route: { id: current.route?.id ?? null }, + url: current.url + }, + to: { + params: intent?.params ?? null, + route: { id: intent?.route?.id ?? null }, + url + }, + willUnload: !intent, + type + }; + + if (delta !== undefined) { + navigation.delta = delta; + } + + const cancellable = { + ...navigation, + cancel: () => { + should_block = true; + } + }; + + if (!navigating) { + // Don't run the event during redirects + callbacks.before_navigate.forEach((fn) => fn(cancellable)); + } + + return should_block ? null : navigation; + } + + /** + * @param {{ + * url: URL; + * scroll: { x: number, y: number } | null; + * keepfocus: boolean; + * redirect_chain: string[]; + * details: { + * replaceState: boolean; + * state: any; + * } | null; + * type: import('@sveltejs/kit').NavigationType; + * delta?: number; + * nav_token?: {}; + * accepted: () => void; + * blocked: () => void; + * }} opts + */ + async function navigate({ + url, + scroll, + keepfocus, + redirect_chain, + details, + type, + delta, + nav_token = {}, + accepted, + blocked + }) { + const intent = get_navigation_intent(url, false); + const navigation = before_navigate({ url, type, delta, intent }); + + if (!navigation) { + blocked(); + return; + } + + // store this before calling `accepted()`, which may change the index + const previous_history_index = current_history_index; + + accepted(); + + navigating = true; + + if (started) { + stores.navigating.set(navigation); + } + + token = nav_token; + let navigation_result = intent && (await load_route(intent)); + + if (!navigation_result) { + if (is_external_url(url, base)) { + return await native_navigation(url); + } + navigation_result = await server_fallback( + url, + { id: null }, + await handle_error(new Error(`Not found: ${url.pathname}`), { + url, + params: {}, + route: { id: null } + }), + 404 + ); + } + + // if this is an internal navigation intent, use the normalized + // URL for the rest of the function + url = intent?.url || url; + + // abort if user navigated during update + if (token !== nav_token) return false; + + if (navigation_result.type === 'redirect') { + if (redirect_chain.length > 10 || redirect_chain.includes(url.pathname)) { + navigation_result = await load_root_error_page({ + status: 500, + error: await handle_error(new Error('Redirect loop'), { + url, + params: {}, + route: { id: null } + }), + url, + route: { id: null } + }); + } else { + goto( + new URL(navigation_result.location, url).href, + {}, + [...redirect_chain, url.pathname], + nav_token + ); + return false; + } + } else if (/** @type {number} */ (navigation_result.props.page?.status) >= 400) { + const updated = await stores.updated.check(); + if (updated) { + await native_navigation(url); + } + } + + // reset invalidation only after a finished navigation. If there are redirects or + // additional invalidations, they should get the same invalidation treatment + invalidated.length = 0; + force_invalidation = false; + + updating = true; + + update_scroll_positions(previous_history_index); + capture_snapshot(previous_history_index); + + // ensure the url pathname matches the page's trailing slash option + if ( + navigation_result.props.page?.url && + navigation_result.props.page.url.pathname !== url.pathname + ) { + url.pathname = navigation_result.props.page?.url.pathname; + } + + if (details) { + const change = details.replaceState ? 0 : 1; + details.state[INDEX_KEY] = current_history_index += change; + history[details.replaceState ? 'replaceState' : 'pushState'](details.state, '', url); + + if (!details.replaceState) { + // if we navigated back, then pushed a new state, we can + // release memory by pruning the scroll/snapshot lookup + let i = current_history_index + 1; + while (snapshots[i] || scroll_positions[i]) { + delete snapshots[i]; + delete scroll_positions[i]; + i += 1; + } + } + } + + // reset preload synchronously after the history state has been set to avoid race conditions + load_cache = null; + + if (started) { + current = navigation_result.state; + + // reset url before updating page store + if (navigation_result.props.page) { + navigation_result.props.page.url = url; + } + + root.$set(navigation_result.props); + } else { + initialize(navigation_result); + } + + const { activeElement } = document; + + // need to render the DOM before we can scroll to the rendered elements and do focus management + await tick(); + + // we reset scroll before dealing with focus, to avoid a flash of unscrolled content + if (autoscroll) { + const deep_linked = + url.hash && document.getElementById(decodeURIComponent(url.hash.slice(1))); + if (scroll) { + scrollTo(scroll.x, scroll.y); + } else if (deep_linked) { + // Here we use `scrollIntoView` on the element instead of `scrollTo` + // because it natively supports the `scroll-margin` and `scroll-behavior` + // CSS properties. + deep_linked.scrollIntoView(); + } else { + scrollTo(0, 0); + } + } + + const changed_focus = + // reset focus only if any manual focus management didn't override it + document.activeElement !== activeElement && + // also refocus when activeElement is body already because the + // focus event might not have been fired on it yet + document.activeElement !== document.body; + + if (!keepfocus && !changed_focus) { + reset_focus(); + } + + autoscroll = true; + + if (navigation_result.props.page) { + page = navigation_result.props.page; + } + + navigating = false; + + if (type === 'popstate') { + restore_snapshot(current_history_index); + } + + callbacks.after_navigate.forEach((fn) => + fn(/** @type {import('@sveltejs/kit').AfterNavigate} */ (navigation)) + ); + stores.navigating.set(null); + + updating = false; + } + + /** + * Does a full page reload if it wouldn't result in an endless loop in the SPA case + * @param {URL} url + * @param {{ id: string | null }} route + * @param {App.Error} error + * @param {number} status + * @returns {Promise} + */ + async function server_fallback(url, route, error, status) { + if (url.origin === location.origin && url.pathname === location.pathname && !hydrated) { + // We would reload the same page we're currently on, which isn't hydrated, + // which means no SSR, which means we would end up in an endless loop + return await load_root_error_page({ + status, + error, + url, + route + }); + } + + if (DEV && status !== 404) { + console.error( + 'An error occurred while loading the page. This will cause a full page reload. (This message will only appear during development.)' + ); + + debugger; // eslint-disable-line + } + + return await native_navigation(url); + } + + /** + * Loads `href` the old-fashioned way, with a full page reload. + * Returns a `Promise` that never resolves (to prevent any + * subsequent work, e.g. history manipulation, from happening) + * @param {URL} url + */ + function native_navigation(url) { + location.href = url.href; + return new Promise(() => {}); + } + + if (import.meta.hot) { + import.meta.hot.on('vite:beforeUpdate', () => { + if (current.error) location.reload(); + }); + } + + function setup_preload() { + /** @type {NodeJS.Timeout} */ + let mousemove_timeout; + + container.addEventListener('mousemove', (event) => { + const target = /** @type {Element} */ (event.target); + + clearTimeout(mousemove_timeout); + mousemove_timeout = setTimeout(() => { + preload(target, 2); + }, 20); + }); + + /** @param {Event} event */ + function tap(event) { + preload(/** @type {Element} */ (event.composedPath()[0]), 1); + } + + container.addEventListener('mousedown', tap); + container.addEventListener('touchstart', tap, { passive: true }); + + const observer = new IntersectionObserver( + (entries) => { + for (const entry of entries) { + if (entry.isIntersecting) { + preload_code( + get_url_path(new URL(/** @type {HTMLAnchorElement} */ (entry.target).href)) + ); + observer.unobserve(entry.target); + } + } + }, + { threshold: 0 } + ); + + /** + * @param {Element} element + * @param {number} priority + */ + function preload(element, priority) { + const a = find_anchor(element, container); + if (!a) return; + + const { url, external, download } = get_link_info(a, base); + if (external || download) return; + + const options = get_router_options(a); + + if (!options.reload) { + if (priority <= options.preload_data) { + const intent = get_navigation_intent(/** @type {URL} */ (url), false); + if (intent) { + if (DEV) { + preload_data(intent).then((result) => { + if (result.type === 'loaded' && result.state.error) { + console.warn( + `Preloading data for ${intent.url.pathname} failed with the following error: ${result.state.error.message}\n` + + 'If this error is transient, you can ignore it. Otherwise, consider disabling preloading for this route. ' + + 'This route was preloaded due to a data-sveltekit-preload-data attribute. ' + + 'See https://kit.svelte.dev/docs/link-options for more info' + ); + } + }); + } else { + preload_data(intent); + } + } + } else if (priority <= options.preload_code) { + preload_code(get_url_path(/** @type {URL} */ (url))); + } + } + } + + function after_navigate() { + observer.disconnect(); + + for (const a of container.querySelectorAll('a')) { + const { url, external, download } = get_link_info(a, base); + if (external || download) continue; + + const options = get_router_options(a); + if (options.reload) continue; + + if (options.preload_code === PRELOAD_PRIORITIES.viewport) { + observer.observe(a); + } + + if (options.preload_code === PRELOAD_PRIORITIES.eager) { + preload_code(get_url_path(/** @type {URL} */ (url))); + } + } + } + + callbacks.after_navigate.push(after_navigate); + after_navigate(); + } + + /** + * @param {unknown} error + * @param {import('@sveltejs/kit').NavigationEvent} event + * @returns {import('types').MaybePromise} + */ + function handle_error(error, event) { + if (error instanceof HttpError) { + return error.body; + } + + if (DEV) { + errored = true; + console.warn('The next HMR update will cause the page to reload'); + } + + return ( + app.hooks.handleError({ error, event }) ?? + /** @type {any} */ ({ message: event.route.id != null ? 'Internal Error' : 'Not Found' }) + ); + } + + return { + after_navigate: (fn) => { + onMount(() => { + callbacks.after_navigate.push(fn); + + return () => { + const i = callbacks.after_navigate.indexOf(fn); + callbacks.after_navigate.splice(i, 1); + }; + }); + }, + + before_navigate: (fn) => { + onMount(() => { + callbacks.before_navigate.push(fn); + + return () => { + const i = callbacks.before_navigate.indexOf(fn); + callbacks.before_navigate.splice(i, 1); + }; + }); + }, + + disable_scroll_handling: () => { + if (DEV && started && !updating) { + throw new Error('Can only disable scroll handling during navigation'); + } + + if (updating || !started) { + autoscroll = false; + } + }, + + goto: (href, opts = {}) => { + return goto(href, opts, []); + }, + + invalidate: (resource) => { + if (typeof resource === 'function') { + invalidated.push(resource); + } else { + const { href } = new URL(resource, location.href); + invalidated.push((url) => url.href === href); + } + + return invalidate(); + }, + + invalidate_all: () => { + force_invalidation = true; + return invalidate(); + }, + + preload_data: async (href) => { + const url = new URL(href, get_base_uri(document)); + const intent = get_navigation_intent(url, false); + + if (!intent) { + throw new Error(`Attempted to preload a URL that does not belong to this app: ${url}`); + } + + await preload_data(intent); + }, + + preload_code, + + apply_action: async (result) => { + if (result.type === 'error') { + const url = new URL(location.href); + + const { branch, route } = current; + if (!route) return; + + const error_load = await load_nearest_error_page( + current.branch.length, + branch, + route.errors + ); + if (error_load) { + const navigation_result = await get_navigation_result_from_branch({ + url, + params: current.params, + branch: branch.slice(0, error_load.idx).concat(error_load.node), + status: result.status ?? 500, + error: result.error, + route + }); + + current = navigation_result.state; + + root.$set(navigation_result.props); + + tick().then(reset_focus); + } + } else if (result.type === 'redirect') { + goto(result.location, { invalidateAll: true }, []); + } else { + /** @type {Record} */ + root.$set({ + // this brings Svelte's view of the world in line with SvelteKit's + // after use:enhance reset the form.... + form: null, + page: { ...page, form: result.data, status: result.status } + }); + + // ...so that setting the `form` prop takes effect and isn't ignored + await tick(); + root.$set({ form: result.data }); + + if (result.type === 'success') { + reset_focus(); + } + } + }, + + _start_router: () => { + history.scrollRestoration = 'manual'; + + // Adopted from Nuxt.js + // Reset scrollRestoration to auto when leaving page, allowing page reload + // and back-navigation from other pages to use the browser to restore the + // scrolling position. + addEventListener('beforeunload', (e) => { + let should_block = false; + + persist_state(); + + if (!navigating) { + // If we're navigating, beforeNavigate was already called. If we end up in here during navigation, + // it's due to an external or full-page-reload link, for which we don't want to call the hook again. + /** @type {import('@sveltejs/kit').BeforeNavigate} */ + const navigation = { + from: { + params: current.params, + route: { id: current.route?.id ?? null }, + url: current.url + }, + to: null, + willUnload: true, + type: 'leave', + cancel: () => (should_block = true) + }; + + callbacks.before_navigate.forEach((fn) => fn(navigation)); + } + + if (should_block) { + e.preventDefault(); + e.returnValue = ''; + } else { + history.scrollRestoration = 'auto'; + } + }); + + addEventListener('visibilitychange', () => { + if (document.visibilityState === 'hidden') { + persist_state(); + } + }); + + // @ts-expect-error this isn't supported everywhere yet + if (!navigator.connection?.saveData) { + setup_preload(); + } + + /** @param {MouseEvent} event */ + container.addEventListener('click', (event) => { + // Adapted from https://github.com/visionmedia/page.js + // MIT license https://github.com/visionmedia/page.js#license + if (event.button || event.which !== 1) return; + if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + if (event.defaultPrevented) return; + + const a = find_anchor(/** @type {Element} */ (event.composedPath()[0]), container); + if (!a) return; + + const { url, external, target, download } = get_link_info(a, base); + if (!url) return; + + // bail out before `beforeNavigate` if link opens in a different tab + if (target === '_parent' || target === '_top') { + if (window.parent !== window) return; + } else if (target && target !== '_self') { + return; + } + + const options = get_router_options(a); + const is_svg_a_element = a instanceof SVGAElement; + + // Ignore URL protocols that differ to the current one and are not http(s) (e.g. `mailto:`, `tel:`, `myapp:`, etc.) + // This may be wrong when the protocol is x: and the link goes to y:.. which should be treated as an external + // navigation, but it's not clear how to handle that case and it's not likely to come up in practice. + // MEMO: Without this condition, firefox will open mailer twice. + // See: + // - https://github.com/sveltejs/kit/issues/4045 + // - https://github.com/sveltejs/kit/issues/5725 + // - https://github.com/sveltejs/kit/issues/6496 + if ( + !is_svg_a_element && + url.protocol !== location.protocol && + !(url.protocol === 'https:' || url.protocol === 'http:') + ) + return; + + if (download) return; + + // Ignore the following but fire beforeNavigate + if (external || options.reload) { + if (before_navigate({ url, type: 'link' })) { + // set `navigating` to `true` to prevent `beforeNavigate` callbacks + // being called when the page unloads + navigating = true; + } else { + event.preventDefault(); + } + + return; + } + + // Check if new url only differs by hash and use the browser default behavior in that case + // This will ensure the `hashchange` event is fired + // Removing the hash does a full page navigation in the browser, so make sure a hash is present + const [nonhash, hash] = url.href.split('#'); + if (hash !== undefined && nonhash === location.href.split('#')[0]) { + // If we are trying to navigate to the same hash, we should only + // attempt to scroll to that element and avoid any history changes. + // Otherwise, this can cause Firefox to incorrectly assign a null + // history state value without any signal that we can detect. + if (current.url.hash === url.hash) { + event.preventDefault(); + a.ownerDocument.getElementById(hash)?.scrollIntoView(); + return; + } + // set this flag to distinguish between navigations triggered by + // clicking a hash link and those triggered by popstate + hash_navigating = true; + + update_scroll_positions(current_history_index); + + update_url(url); + + if (!options.replace_state) return; + + // hashchange event shouldn't occur if the router is replacing state. + hash_navigating = false; + event.preventDefault(); + } + + navigate({ + url, + scroll: options.noscroll ? scroll_state() : null, + keepfocus: options.keep_focus ?? false, + redirect_chain: [], + details: { + state: {}, + replaceState: options.replace_state ?? url.href === location.href + }, + accepted: () => event.preventDefault(), + blocked: () => event.preventDefault(), + type: 'link' + }); + }); + + container.addEventListener('submit', (event) => { + if (event.defaultPrevented) return; + + const form = /** @type {HTMLFormElement} */ ( + HTMLFormElement.prototype.cloneNode.call(event.target) + ); + + const submitter = /** @type {HTMLButtonElement | HTMLInputElement | null} */ ( + event.submitter + ); + + const method = submitter?.formMethod || form.method; + + if (method !== 'get') return; + + const url = new URL( + (submitter?.hasAttribute('formaction') && submitter?.formAction) || form.action + ); + + if (is_external_url(url, base)) return; + + const event_form = /** @type {HTMLFormElement} */ (event.target); + + const { keep_focus, noscroll, reload, replace_state } = get_router_options(event_form); + if (reload) return; + + event.preventDefault(); + event.stopPropagation(); + + const data = new FormData(event_form); + + const submitter_name = submitter?.getAttribute('name'); + if (submitter_name) { + data.append(submitter_name, submitter?.getAttribute('value') ?? ''); + } + + // @ts-expect-error `URLSearchParams(fd)` is kosher, but typescript doesn't know that + url.search = new URLSearchParams(data).toString(); + + navigate({ + url, + scroll: noscroll ? scroll_state() : null, + keepfocus: keep_focus ?? false, + redirect_chain: [], + details: { + state: {}, + replaceState: replace_state ?? url.href === location.href + }, + nav_token: {}, + accepted: () => {}, + blocked: () => {}, + type: 'form' + }); + }); + + addEventListener('popstate', async (event) => { + if (event.state?.[INDEX_KEY]) { + // if a popstate-driven navigation is cancelled, we need to counteract it + // with history.go, which means we end up back here, hence this check + if (event.state[INDEX_KEY] === current_history_index) return; + + const scroll = scroll_positions[event.state[INDEX_KEY]]; + + // if the only change is the hash, we don't need to do anything... + if (current.url.href.split('#')[0] === location.href.split('#')[0]) { + // ...except handle scroll + scroll_positions[current_history_index] = scroll_state(); + current_history_index = event.state[INDEX_KEY]; + scrollTo(scroll.x, scroll.y); + return; + } + + const delta = event.state[INDEX_KEY] - current_history_index; + + await navigate({ + url: new URL(location.href), + scroll, + keepfocus: false, + redirect_chain: [], + details: null, + accepted: () => { + current_history_index = event.state[INDEX_KEY]; + }, + blocked: () => { + history.go(-delta); + }, + type: 'popstate', + delta + }); + } else { + // since popstate event is also emitted when an anchor referencing the same + // document is clicked, we have to check that the router isn't already handling + // the navigation. otherwise we would be updating the page store twice. + if (!hash_navigating) { + const url = new URL(location.href); + update_url(url); + } + } + }); + + addEventListener('hashchange', () => { + // if the hashchange happened as a result of clicking on a link, + // we need to update history, otherwise we have to leave it alone + if (hash_navigating) { + hash_navigating = false; + history.replaceState( + { ...history.state, [INDEX_KEY]: ++current_history_index }, + '', + location.href + ); + } + }); + + // fix link[rel=icon], because browsers will occasionally try to load relative + // URLs after a pushState/replaceState, resulting in a 404 — see + // https://github.com/sveltejs/kit/issues/3748#issuecomment-1125980897 + for (const link of document.querySelectorAll('link')) { + if (link.rel === 'icon') link.href = link.href; // eslint-disable-line + } + + addEventListener('pageshow', (event) => { + // If the user navigates to another site and then uses the back button and + // bfcache hits, we need to set navigating to null, the site doesn't know + // the navigation away from it was successful. + // Info about bfcache here: https://web.dev/bfcache + if (event.persisted) { + stores.navigating.set(null); + } + }); + + /** + * @param {URL} url + */ + function update_url(url) { + current.url = url; + stores.page.set({ ...page, url }); + stores.page.notify(); + } + }, + + _hydrate: async ({ + status = 200, + error, + node_ids, + params, + route, + data: server_data_nodes, + form + }) => { + hydrated = true; + + const url = new URL(location.href); + + if (!__SVELTEKIT_EMBEDDED__) { + // See https://github.com/sveltejs/kit/pull/4935#issuecomment-1328093358 for one motivation + // of determining the params on the client side. + ({ params = {}, route = { id: null } } = get_navigation_intent(url, false) || {}); + } + + /** @type {import('./types').NavigationFinished | undefined} */ + let result; + + try { + const branch_promises = node_ids.map(async (n, i) => { + const server_data_node = server_data_nodes[i]; + // Type isn't completely accurate, we still need to deserialize uses + if (server_data_node?.uses) { + server_data_node.uses = deserialize_uses(server_data_node.uses); + } + + return load_node({ + loader: app.nodes[n], + url, + params, + route, + parent: async () => { + const data = {}; + for (let j = 0; j < i; j += 1) { + Object.assign(data, (await branch_promises[j]).data); + } + return data; + }, + server_data_node: create_data_node(server_data_node) + }); + }); + + /** @type {Array} */ + const branch = await Promise.all(branch_promises); + + const parsed_route = routes.find(({ id }) => id === route.id); + + // server-side will have compacted the branch, reinstate empty slots + // so that error boundaries can be lined up correctly + if (parsed_route) { + const layouts = parsed_route.layouts; + for (let i = 0; i < layouts.length; i++) { + if (!layouts[i]) { + branch.splice(i, 0, undefined); + } + } + } + + result = await get_navigation_result_from_branch({ + url, + params, + branch, + status, + error, + form, + route: parsed_route ?? null + }); + } catch (error) { + if (error instanceof Redirect) { + // this is a real edge case — `load` would need to return + // a redirect but only in the browser + await native_navigation(new URL(error.location, location.href)); + return; + } + + result = await load_root_error_page({ + status: error instanceof HttpError ? error.status : 500, + error: await handle_error(error, { url, params, route }), + url, + route + }); + } + + initialize(result); + } + }; +} + +/** + * @param {URL} url + * @param {boolean[]} invalid + * @returns {Promise} + */ +async function load_data(url, invalid) { + const data_url = new URL(url); + data_url.pathname = add_data_suffix(url.pathname); + if (DEV && url.searchParams.has(INVALIDATED_PARAM)) { + throw new Error(`Cannot used reserved query parameter "${INVALIDATED_PARAM}"`); + } + data_url.searchParams.append(INVALIDATED_PARAM, invalid.map((i) => (i ? '1' : '0')).join('')); + + const res = await native_fetch(data_url.href); + + if (!res.ok) { + // error message is a JSON-stringified string which devalue can't handle at the top level + // turn it into a HttpError to not call handleError on the client again (was already handled on the server) + throw new HttpError(res.status, await res.json()); + } + + // TODO: fix eslint error + // eslint-disable-next-line + return new Promise(async (resolve) => { + /** + * Map of deferred promises that will be resolved by a subsequent chunk of data + * @type {Map} + */ + const deferreds = new Map(); + const reader = /** @type {ReadableStream} */ (res.body).getReader(); + const decoder = new TextDecoder(); + + /** + * @param {any} data + */ + function deserialize(data) { + return devalue.unflatten(data, { + Promise: (id) => { + return new Promise((fulfil, reject) => { + deferreds.set(id, { fulfil, reject }); + }); + } + }); + } + + let text = ''; + + while (true) { + // Format follows ndjson (each line is a JSON object) or regular JSON spec + const { done, value } = await reader.read(); + if (done && !text) break; + + text += !value && text ? '\n' : decoder.decode(value); // no value -> final chunk -> add a new line to trigger the last parse + + while (true) { + const split = text.indexOf('\n'); + if (split === -1) { + break; + } + + const node = JSON.parse(text.slice(0, split)); + text = text.slice(split + 1); + + if (node.type === 'redirect') { + return resolve(node); + } + + if (node.type === 'data') { + // This is the first (and possibly only, if no pending promises) chunk + node.nodes?.forEach((/** @type {any} */ node) => { + if (node?.type === 'data') { + node.uses = deserialize_uses(node.uses); + node.data = deserialize(node.data); + } + }); + + resolve(node); + } else if (node.type === 'chunk') { + // This is a subsequent chunk containing deferred data + const { id, data, error } = node; + const deferred = /** @type {import('types').Deferred} */ (deferreds.get(id)); + deferreds.delete(id); + + if (error) { + deferred.reject(deserialize(error)); + } else { + deferred.fulfil(deserialize(data)); + } + } + } + } + }); + + // TODO edge case handling necessary? stream() read fails? +} + +/** + * @param {any} uses + * @return {import('types').Uses} + */ +function deserialize_uses(uses) { + return { + dependencies: new Set(uses?.dependencies ?? []), + params: new Set(uses?.params ?? []), + parent: !!uses?.parent, + route: !!uses?.route, + url: !!uses?.url + }; +} + +function reset_focus() { + const autofocus = document.querySelector('[autofocus]'); + if (autofocus) { + // @ts-ignore + autofocus.focus(); + } else { + // Reset page selection and focus + // We try to mimic browsers' behaviour as closely as possible by targeting the + // first scrollable region, but unfortunately it's not a perfect match — e.g. + // shift-tabbing won't immediately cycle up from the end of the page on Chromium + // See https://html.spec.whatwg.org/multipage/interaction.html#get-the-focusable-area + const root = document.body; + const tabindex = root.getAttribute('tabindex'); + + root.tabIndex = -1; + // @ts-expect-error + root.focus({ preventScroll: true, focusVisible: false }); + + // restore `tabindex` as to prevent `root` from stealing input from elements + if (tabindex !== null) { + root.setAttribute('tabindex', tabindex); + } else { + root.removeAttribute('tabindex'); + } + + // capture current selection, so we can compare the state after + // snapshot restoration and afterNavigate callbacks have run + const selection = getSelection(); + + if (selection && selection.type !== 'None') { + /** @type {Range[]} */ + const ranges = []; + + for (let i = 0; i < selection.rangeCount; i += 1) { + ranges.push(selection.getRangeAt(i)); + } + + setTimeout(() => { + if (selection.rangeCount !== ranges.length) return; + + for (let i = 0; i < selection.rangeCount; i += 1) { + const a = ranges[i]; + const b = selection.getRangeAt(i); + + // we need to do a deep comparison rather than just `a !== b` because + // Safari behaves differently to other browsers + if ( + a.commonAncestorContainer !== b.commonAncestorContainer || + a.startContainer !== b.startContainer || + a.endContainer !== b.endContainer || + a.startOffset !== b.startOffset || + a.endOffset !== b.endOffset + ) { + return; + } + } + + // if the selection hasn't changed (as a result of an element being (auto)focused, + // or a programmatic selection, we reset everything as part of the navigation) + // fixes https://github.com/sveltejs/kit/issues/8439 + selection.removeAllRanges(); + }); + } + } +} + +if (DEV) { + // Nasty hack to silence harmless warnings the user can do nothing about + const console_warn = console.warn; + console.warn = function warn(...args) { + if ( + args.length === 1 && + /<(Layout|Page|Error)(_[\w$]+)?> was created (with unknown|without expected) prop '(data|form)'/.test( + args[0] + ) + ) { + return; + } + console_warn(...args); + }; + + if (import.meta.hot) { + import.meta.hot.on('vite:beforeUpdate', () => { + if (errored) { + location.reload(); + } + }); + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/client/constants.js b/node_modules/@sveltejs/kit/src/runtime/client/constants.js new file mode 100644 index 0000000..cbb2353 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/constants.js @@ -0,0 +1,11 @@ +export const SNAPSHOT_KEY = 'sveltekit:snapshot'; +export const SCROLL_KEY = 'sveltekit:scroll'; +export const INDEX_KEY = 'sveltekit:index'; + +export const PRELOAD_PRIORITIES = /** @type {const} */ ({ + tap: 1, + hover: 2, + viewport: 3, + eager: 4, + off: -1 +}); diff --git a/node_modules/@sveltejs/kit/src/runtime/client/fetcher.js b/node_modules/@sveltejs/kit/src/runtime/client/fetcher.js new file mode 100644 index 0000000..df709d1 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/fetcher.js @@ -0,0 +1,144 @@ +import { DEV } from 'esm-env'; +import { hash } from '../hash.js'; + +let loading = 0; + +export const native_fetch = window.fetch; + +export function lock_fetch() { + loading += 1; +} + +export function unlock_fetch() { + loading -= 1; +} + +if (DEV) { + let can_inspect_stack_trace = false; + + const check_stack_trace = async () => { + const stack = /** @type {string} */ (new Error().stack); + can_inspect_stack_trace = stack.includes('check_stack_trace'); + }; + + check_stack_trace(); + + window.fetch = (input, init) => { + // Check if fetch was called via load_node. the lock method only checks if it was called at the + // same time, but not necessarily if it was called from `load`. + // We use just the filename as the method name sometimes does not appear on the CI. + const url = input instanceof Request ? input.url : input.toString(); + const stack_array = /** @type {string} */ (new Error().stack).split('\n'); + // We need to do a cutoff because Safari and Firefox maintain the stack + // across events and for example traces a `fetch` call triggered from a button + // back to the creation of the event listener and the element creation itself, + // where at some point client.js will show up, leading to false positives. + const cutoff = stack_array.findIndex((a) => a.includes('load@') || a.includes('at load')); + const stack = stack_array.slice(0, cutoff + 2).join('\n'); + + const heuristic = can_inspect_stack_trace + ? stack.includes('src/runtime/client/client.js') + : loading; + if (heuristic) { + console.warn( + `Loading ${url} using \`window.fetch\`. For best results, use the \`fetch\` that is passed to your \`load\` function: https://kit.svelte.dev/docs/load#making-fetch-requests` + ); + } + + const method = input instanceof Request ? input.method : init?.method || 'GET'; + + if (method !== 'GET') { + cache.delete(build_selector(input)); + } + + return native_fetch(input, init); + }; +} else { + window.fetch = (input, init) => { + const method = input instanceof Request ? input.method : init?.method || 'GET'; + + if (method !== 'GET') { + cache.delete(build_selector(input)); + } + + return native_fetch(input, init); + }; +} + +const cache = new Map(); + +/** + * Should be called on the initial run of load functions that hydrate the page. + * Saves any requests with cache-control max-age to the cache. + * @param {URL | string} resource + * @param {RequestInit} [opts] + */ +export function initial_fetch(resource, opts) { + const selector = build_selector(resource, opts); + + const script = document.querySelector(selector); + if (script?.textContent) { + const { body, ...init } = JSON.parse(script.textContent); + + const ttl = script.getAttribute('data-ttl'); + if (ttl) cache.set(selector, { body, init, ttl: 1000 * Number(ttl) }); + + return Promise.resolve(new Response(body, init)); + } + + return native_fetch(resource, opts); +} + +/** + * Tries to get the response from the cache, if max-age allows it, else does a fetch. + * @param {URL | string} resource + * @param {string} resolved + * @param {RequestInit} [opts] + */ +export function subsequent_fetch(resource, resolved, opts) { + if (cache.size > 0) { + const selector = build_selector(resource, opts); + const cached = cache.get(selector); + if (cached) { + // https://developer.mozilla.org/en-US/docs/Web/API/Request/cache#value + if ( + performance.now() < cached.ttl && + ['default', 'force-cache', 'only-if-cached', undefined].includes(opts?.cache) + ) { + return new Response(cached.body, cached.init); + } + + cache.delete(selector); + } + } + + return native_fetch(resolved, opts); +} + +/** + * Build the cache key for a given request + * @param {URL | RequestInfo} resource + * @param {RequestInit} [opts] + */ +function build_selector(resource, opts) { + const url = JSON.stringify(resource instanceof Request ? resource.url : resource); + + let selector = `script[data-sveltekit-fetched][data-url=${url}]`; + + if (opts?.headers || opts?.body) { + /** @type {import('types').StrictBody[]} */ + const values = []; + + if (opts.headers) { + values.push([...new Headers(opts.headers)].join(',')); + } + + if (opts.body && (typeof opts.body === 'string' || ArrayBuffer.isView(opts.body))) { + values.push(opts.body); + } + + selector += `[data-hash="${hash(...values)}"]`; + } + + return selector; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/client/parse.js b/node_modules/@sveltejs/kit/src/runtime/client/parse.js new file mode 100644 index 0000000..d148b28 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/parse.js @@ -0,0 +1,57 @@ +import { exec, parse_route_id } from '../../utils/routing.js'; + +/** + * @param {import('./types').SvelteKitApp} app + * @returns {import('types').CSRRoute[]} + */ +export function parse({ nodes, server_loads, dictionary, matchers }) { + const layouts_with_server_load = new Set(server_loads); + + return Object.entries(dictionary).map(([id, [leaf, layouts, errors]]) => { + const { pattern, params } = parse_route_id(id); + + const route = { + id, + /** @param {string} path */ + exec: (path) => { + const match = pattern.exec(path); + if (match) return exec(match, params, matchers); + }, + errors: [1, ...(errors || [])].map((n) => nodes[n]), + layouts: [0, ...(layouts || [])].map(create_layout_loader), + leaf: create_leaf_loader(leaf) + }; + + // bit of a hack, but ensures that layout/error node lists are the same + // length, without which the wrong data will be applied if the route + // manifest looks like `[[a, b], [c,], d]` + route.errors.length = route.layouts.length = Math.max( + route.errors.length, + route.layouts.length + ); + + return route; + }); + + /** + * @param {number} id + * @returns {[boolean, import('types').CSRPageNodeLoader]} + */ + function create_leaf_loader(id) { + // whether or not the route uses the server data is + // encoded using the ones' complement, to save space + const uses_server_data = id < 0; + if (uses_server_data) id = ~id; + return [uses_server_data, nodes[id]]; + } + + /** + * @param {number | undefined} id + * @returns {[boolean, import('types').CSRPageNodeLoader] | undefined} + */ + function create_layout_loader(id) { + // whether or not the layout uses the server data is + // encoded in the layouts array, to save space + return id === undefined ? id : [layouts_with_server_load.has(id), nodes[id]]; + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/client/session-storage.js b/node_modules/@sveltejs/kit/src/runtime/client/session-storage.js new file mode 100644 index 0000000..dc2639e --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/session-storage.js @@ -0,0 +1,25 @@ +/** + * Read a value from `sessionStorage` + * @param {string} key + */ +export function get(key) { + try { + return JSON.parse(sessionStorage[key]); + } catch { + // do nothing + } +} + +/** + * Write a value to `sessionStorage` + * @param {string} key + * @param {any} value + */ +export function set(key, value) { + const json = JSON.stringify(value); + try { + sessionStorage[key] = json; + } catch { + // do nothing + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/client/singletons.js b/node_modules/@sveltejs/kit/src/runtime/client/singletons.js new file mode 100644 index 0000000..9e1e7c1 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/singletons.js @@ -0,0 +1,53 @@ +import { writable } from 'svelte/store'; +import { create_updated_store, notifiable_store } from './utils.js'; +import { BROWSER } from 'esm-env'; + +/** @type {import('./types').Client} */ +export let client; + +/** + * @param {{ + * client: import('./types').Client; + * }} opts + */ +export function init(opts) { + client = opts.client; +} + +/** + * @template {keyof typeof client} T + * @param {T} key + * @returns {typeof client[T]} + */ +export function client_method(key) { + if (!BROWSER) { + if (key === 'before_navigate' || key === 'after_navigate') { + // @ts-expect-error doesn't recognize that both keys here return void so expects a async function + return () => {}; + } else { + /** @type {Record} */ + const name_lookup = { + disable_scroll_handling: 'disableScrollHandling', + preload_data: 'preloadData', + preload_code: 'preloadCode', + invalidate_all: 'invalidateAll' + }; + + return () => { + throw new Error(`Cannot call ${name_lookup[key] ?? key}(...) on the server`); + }; + } + } else { + // @ts-expect-error + return (...args) => client[key](...args); + } +} + +export const stores = { + url: /* @__PURE__ */ notifiable_store({}), + page: /* @__PURE__ */ notifiable_store({}), + navigating: /* @__PURE__ */ writable( + /** @type {import('@sveltejs/kit').Navigation | null} */ (null) + ), + updated: /* @__PURE__ */ create_updated_store() +}; diff --git a/node_modules/@sveltejs/kit/src/runtime/client/start.js b/node_modules/@sveltejs/kit/src/runtime/client/start.js new file mode 100644 index 0000000..70e0d73 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/start.js @@ -0,0 +1,28 @@ +import { DEV } from 'esm-env'; +import { create_client } from './client.js'; +import { init } from './singletons.js'; + +/** + * @param {import('./types').SvelteKitApp} app + * @param {HTMLElement} target + * @param {Parameters[0]} [hydrate] + */ +export async function start(app, target, hydrate) { + if (DEV && target === document.body) { + console.warn( + 'Placing %sveltekit.body% directly inside is not recommended, as your app may break for users who have certain browser extensions installed.\n\nConsider wrapping it in an element:\n\n

' + ); + } + + const client = create_client(app, target); + + init({ client }); + + if (hydrate) { + await client._hydrate(hydrate); + } else { + client.goto(location.href, { replaceState: true }); + } + + client._start_router(); +} diff --git a/node_modules/@sveltejs/kit/src/runtime/client/types.d.ts b/node_modules/@sveltejs/kit/src/runtime/client/types.d.ts new file mode 100644 index 0000000..8fba78e --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/types.d.ts @@ -0,0 +1,120 @@ +import { applyAction } from '../app/forms'; +import { + afterNavigate, + beforeNavigate, + goto, + invalidate, + invalidateAll, + preloadCode, + preloadData +} from '../app/navigation'; +import { SvelteComponent } from 'svelte'; +import { ClientHooks, CSRPageNode, CSRPageNodeLoader, CSRRoute, TrailingSlash, Uses } from 'types'; +import { Page, ParamMatcher } from '@sveltejs/kit'; + +export interface SvelteKitApp { + /** + * A list of all the error/layout/page nodes used in the app + */ + nodes: CSRPageNodeLoader[]; + + /** + * A list of all layout node ids that have a server load function. + * Pages are not present because it's shorter to encode it on the leaf itself. + */ + server_loads: number[]; + + /** + * A map of `[routeId: string]: [leaf, layouts, errors]` tuples, which + * is parsed into an array of routes on startup. The numbers refer to the indices in `nodes`. + * If the leaf number is negative, it means it does use a server load function and the complement is the node index. + * The route layout and error nodes are not referenced, they are always number 0 and 1 and always apply. + */ + dictionary: Record; + + matchers: Record; + + hooks: ClientHooks; + + root: typeof SvelteComponent; +} + +export interface Client { + // public API, exposed via $app/navigation + after_navigate: typeof afterNavigate; + before_navigate: typeof beforeNavigate; + disable_scroll_handling(): void; + goto: typeof goto; + invalidate: typeof invalidate; + invalidate_all: typeof invalidateAll; + preload_code: typeof preloadCode; + preload_data: typeof preloadData; + apply_action: typeof applyAction; + + // private API + _hydrate(opts: { + status: number; + error: App.Error | null; + node_ids: number[]; + params: Record; + route: { id: string | null }; + data: Array; + form: Record | null; + }): Promise; + _start_router(): void; +} + +export type NavigationIntent = { + /** `url.pathname + url.search` */ + id: string; + /** Whether we are invalidating or navigating */ + invalidating: boolean; + /** The route parameters */ + params: Record; + /** The route that matches `path` */ + route: CSRRoute; + /** The destination URL */ + url: URL; +}; + +export type NavigationResult = NavigationRedirect | NavigationFinished; + +export type NavigationRedirect = { + type: 'redirect'; + location: string; +}; + +export type NavigationFinished = { + type: 'loaded'; + state: NavigationState; + props: { + components: Array; + page?: Page; + form?: Record | null; + [key: `data_${number}`]: Record; + }; +}; + +export type BranchNode = { + node: CSRPageNode; + loader: CSRPageNodeLoader; + server: DataNode | null; + universal: DataNode | null; + data: Record | null; + slash?: TrailingSlash; +}; + +export interface DataNode { + type: 'data'; + data: Record | null; + uses: Uses; + slash?: TrailingSlash; +} + +export interface NavigationState { + branch: Array; + error: App.Error | null; + params: Record; + route: CSRRoute | null; + url: URL; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/client/utils.js b/node_modules/@sveltejs/kit/src/runtime/client/utils.js new file mode 100644 index 0000000..8af6102 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/client/utils.js @@ -0,0 +1,294 @@ +import { BROWSER, DEV } from 'esm-env'; +import { writable } from 'svelte/store'; +import { assets } from '__sveltekit/paths'; +import { version } from '__sveltekit/environment'; +import { PRELOAD_PRIORITIES } from './constants.js'; + +/* global __SVELTEKIT_APP_VERSION_FILE__, __SVELTEKIT_APP_VERSION_POLL_INTERVAL__ */ + +/** @param {HTMLDocument} doc */ +export function get_base_uri(doc) { + let baseURI = doc.baseURI; + + if (!baseURI) { + const baseTags = doc.getElementsByTagName('base'); + baseURI = baseTags.length ? baseTags[0].href : doc.URL; + } + + return baseURI; +} + +export function scroll_state() { + return { + x: pageXOffset, + y: pageYOffset + }; +} + +const warned = new WeakSet(); + +/** @typedef {keyof typeof valid_link_options} LinkOptionName */ + +const valid_link_options = /** @type {const} */ ({ + 'preload-code': ['', 'off', 'tap', 'hover', 'viewport', 'eager'], + 'preload-data': ['', 'off', 'tap', 'hover'], + keepfocus: ['', 'true', 'off', 'false'], + noscroll: ['', 'true', 'off', 'false'], + reload: ['', 'true', 'off', 'false'], + replacestate: ['', 'true', 'off', 'false'] +}); + +/** + * @template {LinkOptionName} T + * @typedef {typeof valid_link_options[T][number]} ValidLinkOptions + */ + +/** + * @template {LinkOptionName} T + * @param {Element} element + * @param {T} name + */ +function link_option(element, name) { + const value = /** @type {ValidLinkOptions | null} */ ( + element.getAttribute(`data-sveltekit-${name}`) + ); + + if (DEV) { + validate_link_option(element, name, value); + } + + return value; +} + +/** + * @template {LinkOptionName} T + * @template {ValidLinkOptions | null} U + * @param {Element} element + * @param {T} name + * @param {U} value + */ +function validate_link_option(element, name, value) { + if (value === null) return; + + // @ts-expect-error - includes is dumb + if (!warned.has(element) && !valid_link_options[name].includes(value)) { + console.error( + `Unexpected value for ${name} — should be one of ${valid_link_options[name] + .map((option) => JSON.stringify(option)) + .join(', ')}`, + element + ); + + warned.add(element); + } +} + +const levels = { + ...PRELOAD_PRIORITIES, + '': PRELOAD_PRIORITIES.hover +}; + +/** + * @param {Element} element + * @returns {Element | null} + */ +function parent_element(element) { + let parent = element.assignedSlot ?? element.parentNode; + + // @ts-expect-error handle shadow roots + if (parent?.nodeType === 11) parent = parent.host; + + return /** @type {Element} */ (parent); +} + +/** + * @param {Element} element + * @param {Element} target + */ +export function find_anchor(element, target) { + while (element && element !== target) { + if (element.nodeName.toUpperCase() === 'A' && element.hasAttribute('href')) { + return /** @type {HTMLAnchorElement | SVGAElement} */ (element); + } + + element = /** @type {Element} */ (parent_element(element)); + } +} + +/** + * @param {HTMLAnchorElement | SVGAElement} a + * @param {string} base + */ +export function get_link_info(a, base) { + /** @type {URL | undefined} */ + let url; + + try { + url = new URL(a instanceof SVGAElement ? a.href.baseVal : a.href, document.baseURI); + } catch {} + + const target = a instanceof SVGAElement ? a.target.baseVal : a.target; + + const external = + !url || + !!target || + is_external_url(url, base) || + (a.getAttribute('rel') || '').split(/\s+/).includes('external'); + + const download = url?.origin === location.origin && a.hasAttribute('download'); + + return { url, external, target, download }; +} + +/** + * @param {HTMLFormElement | HTMLAnchorElement | SVGAElement} element + */ +export function get_router_options(element) { + /** @type {ValidLinkOptions<'keepfocus'> | null} */ + let keep_focus = null; + + /** @type {ValidLinkOptions<'noscroll'> | null} */ + let noscroll = null; + + /** @type {ValidLinkOptions<'preload-code'> | null} */ + let preload_code = null; + + /** @type {ValidLinkOptions<'preload-data'> | null} */ + let preload_data = null; + + /** @type {ValidLinkOptions<'reload'> | null} */ + let reload = null; + + /** @type {ValidLinkOptions<'replacestate'> | null} */ + let replace_state = null; + + /** @type {Element} */ + let el = element; + + while (el && el !== document.documentElement) { + if (preload_code === null) preload_code = link_option(el, 'preload-code'); + if (preload_data === null) preload_data = link_option(el, 'preload-data'); + if (keep_focus === null) keep_focus = link_option(el, 'keepfocus'); + if (noscroll === null) noscroll = link_option(el, 'noscroll'); + if (reload === null) reload = link_option(el, 'reload'); + if (replace_state === null) replace_state = link_option(el, 'replacestate'); + + el = /** @type {Element} */ (parent_element(el)); + } + + /** @param {string | null} value */ + function get_option_state(value) { + switch (value) { + case '': + case 'true': + return true; + case 'off': + case 'false': + return false; + default: + return null; + } + } + + return { + preload_code: levels[preload_code ?? 'off'], + preload_data: levels[preload_data ?? 'off'], + keep_focus: get_option_state(keep_focus), + noscroll: get_option_state(noscroll), + reload: get_option_state(reload), + replace_state: get_option_state(replace_state) + }; +} + +/** @param {any} value */ +export function notifiable_store(value) { + const store = writable(value); + let ready = true; + + function notify() { + ready = true; + store.update((val) => val); + } + + /** @param {any} new_value */ + function set(new_value) { + ready = false; + store.set(new_value); + } + + /** @param {(value: any) => void} run */ + function subscribe(run) { + /** @type {any} */ + let old_value; + return store.subscribe((new_value) => { + if (old_value === undefined || (ready && new_value !== old_value)) { + run((old_value = new_value)); + } + }); + } + + return { notify, set, subscribe }; +} + +export function create_updated_store() { + const { set, subscribe } = writable(false); + + if (DEV || !BROWSER) { + return { + subscribe, + check: async () => false + }; + } + + const interval = __SVELTEKIT_APP_VERSION_POLL_INTERVAL__; + + /** @type {NodeJS.Timeout} */ + let timeout; + + /** @type {() => Promise} */ + async function check() { + clearTimeout(timeout); + + if (interval) timeout = setTimeout(check, interval); + + try { + const res = await fetch(`${assets}/${__SVELTEKIT_APP_VERSION_FILE__}`, { + headers: { + pragma: 'no-cache', + 'cache-control': 'no-cache' + } + }); + + if (!res.ok) { + return false; + } + + const data = await res.json(); + const updated = data.version !== version; + + if (updated) { + set(true); + clearTimeout(timeout); + } + + return updated; + } catch { + return false; + } + } + + if (interval) timeout = setTimeout(check, interval); + + return { + subscribe, + check + }; +} + +/** + * @param {URL} url + * @param {string} base + */ +export function is_external_url(url, base) { + return url.origin !== location.origin || !url.pathname.startsWith(base); +} diff --git a/node_modules/@sveltejs/kit/src/runtime/components/error.svelte b/node_modules/@sveltejs/kit/src/runtime/components/error.svelte new file mode 100644 index 0000000..b82ddfa --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/components/error.svelte @@ -0,0 +1,6 @@ + + +

{$page.status}

+

{$page.error?.message}

diff --git a/node_modules/@sveltejs/kit/src/runtime/components/layout.svelte b/node_modules/@sveltejs/kit/src/runtime/components/layout.svelte new file mode 100644 index 0000000..49aeb95 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/components/layout.svelte @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/node_modules/@sveltejs/kit/src/runtime/control.js b/node_modules/@sveltejs/kit/src/runtime/control.js new file mode 100644 index 0000000..d277254 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/control.js @@ -0,0 +1,66 @@ +export class HttpError { + /** + * @param {number} status + * @param {{message: string} extends App.Error ? (App.Error | string | undefined) : App.Error} body + */ + constructor(status, body) { + this.status = status; + if (typeof body === 'string') { + this.body = { message: body }; + } else if (body) { + this.body = body; + } else { + this.body = { message: `Error: ${status}` }; + } + } + + toString() { + return JSON.stringify(this.body); + } +} + +export class Redirect { + /** + * @param {300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308} status + * @param {string} location + */ + constructor(status, location) { + this.status = status; + this.location = location; + } +} + +/** + * @template {Record | undefined} [T=undefined] + */ +export class ActionFailure { + /** + * @param {number} status + * @param {T} [data] + */ + constructor(status, data) { + this.status = status; + this.data = data; + } +} + +/** + * This is a grotesque hack that, in dev, allows us to replace the implementations + * of these classes that you'd get by importing them from `@sveltejs/kit` with the + * ones that are imported via Vite and loaded internally, so that instanceof + * checks work even though SvelteKit imports this module via Vite and consumers + * import it via Node + * @param {{ + * ActionFailure: typeof ActionFailure; + * HttpError: typeof HttpError; + * Redirect: typeof Redirect; + * }} implementations + */ +export function replace_implementations(implementations) { + // @ts-expect-error + ActionFailure = implementations.ActionFailure; // eslint-disable-line no-class-assign + // @ts-expect-error + HttpError = implementations.HttpError; // eslint-disable-line no-class-assign + // @ts-expect-error + Redirect = implementations.Redirect; // eslint-disable-line no-class-assign +} diff --git a/node_modules/@sveltejs/kit/src/runtime/env/dynamic/private.js b/node_modules/@sveltejs/kit/src/runtime/env/dynamic/private.js new file mode 100644 index 0000000..1965ee8 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/env/dynamic/private.js @@ -0,0 +1 @@ +export { private_env as env } from '../../shared-server.js'; diff --git a/node_modules/@sveltejs/kit/src/runtime/env/dynamic/public.js b/node_modules/@sveltejs/kit/src/runtime/env/dynamic/public.js new file mode 100644 index 0000000..919d034 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/env/dynamic/public.js @@ -0,0 +1 @@ +export { public_env as env } from '../../shared-server.js'; diff --git a/node_modules/@sveltejs/kit/src/runtime/hash.js b/node_modules/@sveltejs/kit/src/runtime/hash.js new file mode 100644 index 0000000..cfebacb --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/hash.js @@ -0,0 +1,22 @@ +/** + * Hash using djb2 + * @param {import('types').StrictBody[]} values + */ +export function hash(...values) { + let hash = 5381; + + for (const value of values) { + if (typeof value === 'string') { + let i = value.length; + while (i) hash = (hash * 33) ^ value.charCodeAt(--i); + } else if (ArrayBuffer.isView(value)) { + const buffer = new Uint8Array(value.buffer, value.byteOffset, value.byteLength); + let i = buffer.length; + while (i) hash = (hash * 33) ^ buffer[--i]; + } else { + throw new TypeError('value must be a string or TypedArray'); + } + } + + return (hash >>> 0).toString(36); +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/ambient.d.ts b/node_modules/@sveltejs/kit/src/runtime/server/ambient.d.ts new file mode 100644 index 0000000..c893c94 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/ambient.d.ts @@ -0,0 +1,8 @@ +declare module '__SERVER__/internal.js' { + export const options: import('types').SSROptions; + export const get_hooks: () => Promise<{ + handle?: import('@sveltejs/kit').Handle; + handleError?: import('@sveltejs/kit').HandleServerError; + handleFetch?: import('@sveltejs/kit').HandleFetch; + }>; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/cookie.js b/node_modules/@sveltejs/kit/src/runtime/server/cookie.js new file mode 100644 index 0000000..644e41b --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/cookie.js @@ -0,0 +1,250 @@ +import { parse, serialize } from 'cookie'; +import { normalize_path } from '../../utils/url.js'; + +/** + * Tracks all cookies set during dev mode so we can emit warnings + * when we detect that there's likely cookie misusage due to wrong paths + * + * @type {Record>} */ +const cookie_paths = {}; + +/** + * Cookies that are larger than this size (including the name and other + * attributes) are discarded by browsers + */ +const MAX_COOKIE_SIZE = 4129; + +/** + * @param {Request} request + * @param {URL} url + * @param {import('types').TrailingSlash} trailing_slash + */ +export function get_cookies(request, url, trailing_slash) { + const header = request.headers.get('cookie') ?? ''; + const initial_cookies = parse(header, { decode: (value) => value }); + + const normalized_url = normalize_path(url.pathname, trailing_slash); + // Emulate browser-behavior: if the cookie is set at '/foo/bar', its path is '/foo' + const default_path = normalized_url.split('/').slice(0, -1).join('/') || '/'; + + /** @type {Record} */ + const new_cookies = {}; + + /** @type {import('cookie').CookieSerializeOptions} */ + const defaults = { + httpOnly: true, + sameSite: 'lax', + secure: url.hostname === 'localhost' && url.protocol === 'http:' ? false : true + }; + + /** @type {import('@sveltejs/kit').Cookies} */ + const cookies = { + // The JSDoc param annotations appearing below for get, set and delete + // are necessary to expose the `cookie` library types to + // typescript users. `@type {import('@sveltejs/kit').Cookies}` above is not + // sufficient to do so. + + /** + * @param {string} name + * @param {import('cookie').CookieParseOptions} opts + */ + get(name, opts) { + const c = new_cookies[name]; + if ( + c && + domain_matches(url.hostname, c.options.domain) && + path_matches(url.pathname, c.options.path) + ) { + return c.value; + } + + const decoder = opts?.decode || decodeURIComponent; + const req_cookies = parse(header, { decode: decoder }); + const cookie = req_cookies[name]; // the decoded string or undefined + + // in development, if the cookie was set during this session with `cookies.set`, + // but at a different path, warn the user. (ignore cookies from request headers, + // since we don't know which path they were set at) + if (__SVELTEKIT_DEV__ && !cookie) { + const paths = Array.from(cookie_paths[name] ?? []).filter((path) => { + // we only care about paths that are _more_ specific than the current path + return path_matches(path, url.pathname) && path !== url.pathname; + }); + + if (paths.length > 0) { + console.warn( + // prettier-ignore + `'${name}' cookie does not exist for ${url.pathname}, but was previously set at ${conjoin([...paths])}. Did you mean to set its 'path' to '/' instead?` + ); + } + } + + return cookie; + }, + + /** + * @param {import('cookie').CookieParseOptions} opts + */ + getAll(opts) { + const decoder = opts?.decode || decodeURIComponent; + const cookies = parse(header, { decode: decoder }); + + for (const c of Object.values(new_cookies)) { + if ( + domain_matches(url.hostname, c.options.domain) && + path_matches(url.pathname, c.options.path) + ) { + cookies[c.name] = c.value; + } + } + + return Object.entries(cookies).map(([name, value]) => ({ name, value })); + }, + + /** + * @param {string} name + * @param {string} value + * @param {import('cookie').CookieSerializeOptions} opts + */ + set(name, value, opts = {}) { + set_internal(name, value, { ...defaults, ...opts }); + }, + + /** + * @param {string} name + * @param {import('cookie').CookieSerializeOptions} opts + */ + delete(name, opts = {}) { + cookies.set(name, '', { + ...opts, + maxAge: 0 + }); + }, + + /** + * @param {string} name + * @param {string} value + * @param {import('cookie').CookieSerializeOptions} opts + */ + serialize(name, value, opts) { + return serialize(name, value, { + ...defaults, + ...opts + }); + } + }; + + /** + * @param {URL} destination + * @param {string | null} header + */ + function get_cookie_header(destination, header) { + /** @type {Record} */ + const combined_cookies = { + // cookies sent by the user agent have lowest precedence + ...initial_cookies + }; + + // cookies previous set during this event with cookies.set have higher precedence + for (const key in new_cookies) { + const cookie = new_cookies[key]; + if (!domain_matches(destination.hostname, cookie.options.domain)) continue; + if (!path_matches(destination.pathname, cookie.options.path)) continue; + + const encoder = cookie.options.encode || encodeURIComponent; + combined_cookies[cookie.name] = encoder(cookie.value); + } + + // explicit header has highest precedence + if (header) { + const parsed = parse(header, { decode: (value) => value }); + for (const name in parsed) { + combined_cookies[name] = parsed[name]; + } + } + + return Object.entries(combined_cookies) + .map(([name, value]) => `${name}=${value}`) + .join('; '); + } + + /** + * @param {string} name + * @param {string} value + * @param {import('cookie').CookieSerializeOptions} opts + */ + function set_internal(name, value, opts) { + const path = opts.path ?? default_path; + + new_cookies[name] = { + name, + value, + options: { + ...opts, + path + } + }; + + if (__SVELTEKIT_DEV__) { + const serialized = serialize(name, value, new_cookies[name].options); + if (new TextEncoder().encode(serialized).byteLength > MAX_COOKIE_SIZE) { + throw new Error(`Cookie "${name}" is too large, and will be discarded by the browser`); + } + + cookie_paths[name] ??= new Set(); + + if (!value) { + cookie_paths[name].delete(path); + } else { + cookie_paths[name].add(path); + } + } + } + + return { cookies, new_cookies, get_cookie_header, set_internal }; +} + +/** + * @param {string} hostname + * @param {string} [constraint] + */ +export function domain_matches(hostname, constraint) { + if (!constraint) return true; + + const normalized = constraint[0] === '.' ? constraint.slice(1) : constraint; + + if (hostname === normalized) return true; + return hostname.endsWith('.' + normalized); +} + +/** + * @param {string} path + * @param {string} [constraint] + */ +export function path_matches(path, constraint) { + if (!constraint) return true; + + const normalized = constraint.endsWith('/') ? constraint.slice(0, -1) : constraint; + + if (path === normalized) return true; + return path.startsWith(normalized + '/'); +} + +/** + * @param {Headers} headers + * @param {import('./page/types').Cookie[]} cookies + */ +export function add_cookies_to_headers(headers, cookies) { + for (const new_cookie of cookies) { + const { name, value, options } = new_cookie; + headers.append('set-cookie', serialize(name, value, options)); + } +} + +/** + * @param {string[]} array + */ +function conjoin(array) { + if (array.length <= 2) return array.join(' and '); + return `${array.slice(0, -1).join(', ')} and ${array.at(-1)}`; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/data/index.js b/node_modules/@sveltejs/kit/src/runtime/server/data/index.js new file mode 100644 index 0000000..472c2c1 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/data/index.js @@ -0,0 +1,263 @@ +import { HttpError, Redirect } from '../../control.js'; +import { normalize_error } from '../../../utils/error.js'; +import { once } from '../../../utils/functions.js'; +import { load_server_data } from '../page/load_data.js'; +import { clarify_devalue_error, handle_error_and_jsonify, stringify_uses } from '../utils.js'; +import { normalize_path } from '../../../utils/url.js'; +import { text } from '../../../exports/index.js'; +import * as devalue from 'devalue'; +import { create_async_iterator } from '../../../utils/streaming.js'; + +const encoder = new TextEncoder(); + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('types').SSRRoute} route + * @param {import('types').SSROptions} options + * @param {import('@sveltejs/kit').SSRManifest} manifest + * @param {import('types').SSRState} state + * @param {boolean[] | undefined} invalidated_data_nodes + * @param {import('types').TrailingSlash} trailing_slash + * @returns {Promise} + */ +export async function render_data( + event, + route, + options, + manifest, + state, + invalidated_data_nodes, + trailing_slash +) { + if (!route.page) { + // requesting /__data.json should fail for a +server.js + return new Response(undefined, { + status: 404 + }); + } + + try { + const node_ids = [...route.page.layouts, route.page.leaf]; + const invalidated = invalidated_data_nodes ?? node_ids.map(() => true); + + let aborted = false; + + const url = new URL(event.url); + url.pathname = normalize_path(url.pathname, trailing_slash); + + const new_event = { ...event, url }; + + const functions = node_ids.map((n, i) => { + return once(async () => { + try { + if (aborted) { + return /** @type {import('types').ServerDataSkippedNode} */ ({ + type: 'skip' + }); + } + + // == because it could be undefined (in dev) or null (in build, because of JSON.stringify) + const node = n == undefined ? n : await manifest._.nodes[n](); + // load this. for the child, return as is. for the final result, stream things + return load_server_data({ + event: new_event, + state, + node, + parent: async () => { + /** @type {Record} */ + const data = {}; + for (let j = 0; j < i; j += 1) { + const parent = /** @type {import('types').ServerDataNode | null} */ ( + await functions[j]() + ); + + if (parent) { + Object.assign(data, parent.data); + } + } + return data; + }, + track_server_fetches: options.track_server_fetches + }); + } catch (e) { + aborted = true; + throw e; + } + }); + }); + + const promises = functions.map(async (fn, i) => { + if (!invalidated[i]) { + return /** @type {import('types').ServerDataSkippedNode} */ ({ + type: 'skip' + }); + } + + return fn(); + }); + + let length = promises.length; + const nodes = await Promise.all( + promises.map((p, i) => + p.catch(async (error) => { + if (error instanceof Redirect) { + throw error; + } + + // Math.min because array isn't guaranteed to resolve in order + length = Math.min(length, i + 1); + + return /** @type {import('types').ServerErrorNode} */ ({ + type: 'error', + error: await handle_error_and_jsonify(event, options, error), + status: error instanceof HttpError ? error.status : undefined + }); + }) + ) + ); + + const { data, chunks } = get_data_json(event, options, nodes); + + if (!chunks) { + // use a normal JSON response where possible, so we get `content-length` + // and can use browser JSON devtools for easier inspecting + return json_response(data); + } + + return new Response( + new ReadableStream({ + async start(controller) { + controller.enqueue(encoder.encode(data)); + for await (const chunk of chunks) { + controller.enqueue(encoder.encode(chunk)); + } + controller.close(); + }, + + type: 'bytes' + }), + { + headers: { + // we use a proprietary content type to prevent buffering. + // the `text` prefix makes it inspectable + 'content-type': 'text/sveltekit-data', + 'cache-control': 'private, no-store' + } + } + ); + } catch (e) { + const error = normalize_error(e); + + if (error instanceof Redirect) { + return redirect_json_response(error); + } else { + return json_response(await handle_error_and_jsonify(event, options, error), 500); + } + } +} + +/** + * @param {Record | string} json + * @param {number} [status] + */ +function json_response(json, status = 200) { + return text(typeof json === 'string' ? json : JSON.stringify(json), { + status, + headers: { + 'content-type': 'application/json', + 'cache-control': 'private, no-store' + } + }); +} + +/** + * @param {Redirect} redirect + */ +export function redirect_json_response(redirect) { + return json_response({ + type: 'redirect', + location: redirect.location + }); +} + +/** + * If the serialized data contains promises, `chunks` will be an + * async iterable containing their resolutions + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('types').SSROptions} options + * @param {Array} nodes + * @returns {{ data: string, chunks: AsyncIterable | null }} + */ +export function get_data_json(event, options, nodes) { + let promise_id = 1; + let count = 0; + + const { iterator, push, done } = create_async_iterator(); + + const reducers = { + /** @param {any} thing */ + Promise: (thing) => { + if (typeof thing?.then === 'function') { + const id = promise_id++; + count += 1; + + /** @type {'data' | 'error'} */ + let key = 'data'; + + thing + .catch( + /** @param {any} e */ async (e) => { + key = 'error'; + return handle_error_and_jsonify(event, options, /** @type {any} */ (e)); + } + ) + .then( + /** @param {any} value */ + async (value) => { + let str; + try { + str = devalue.stringify(value, reducers); + } catch (e) { + const error = await handle_error_and_jsonify( + event, + options, + new Error(`Failed to serialize promise while rendering ${event.route.id}`) + ); + + key = 'error'; + str = devalue.stringify(error, reducers); + } + + count -= 1; + + push(`{"type":"chunk","id":${id},"${key}":${str}}\n`); + if (count === 0) done(); + } + ); + + return id; + } + } + }; + + try { + const strings = nodes.map((node) => { + if (!node) return 'null'; + + if (node.type === 'error' || node.type === 'skip') { + return JSON.stringify(node); + } + + return `{"type":"data","data":${devalue.stringify(node.data, reducers)},${stringify_uses( + node + )}${node.slash ? `,"slash":${JSON.stringify(node.slash)}` : ''}}`; + }); + + return { + data: `{"type":"data","nodes":[${strings.join(',')}]}\n`, + chunks: count > 0 ? iterator : null + }; + } catch (e) { + throw new Error(clarify_devalue_error(event, /** @type {any} */ (e))); + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/endpoint.js b/node_modules/@sveltejs/kit/src/runtime/server/endpoint.js new file mode 100644 index 0000000..8676358 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/endpoint.js @@ -0,0 +1,94 @@ +import { ENDPOINT_METHODS, PAGE_METHODS } from '../../constants.js'; +import { negotiate } from '../../utils/http.js'; +import { Redirect } from '../control.js'; +import { method_not_allowed } from './utils.js'; + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('types').SSREndpoint} mod + * @param {import('types').SSRState} state + * @returns {Promise} + */ +export async function render_endpoint(event, mod, state) { + const method = /** @type {import('types').HttpMethod} */ (event.request.method); + + let handler = mod[method]; + + if (!handler && method === 'HEAD') { + handler = mod.GET; + } + + if (!handler) { + return method_not_allowed(mod, method); + } + + const prerender = mod.prerender ?? state.prerender_default; + + if (prerender && (mod.POST || mod.PATCH || mod.PUT || mod.DELETE)) { + throw new Error('Cannot prerender endpoints that have mutative methods'); + } + + if (state.prerendering && !prerender) { + if (state.depth > 0) { + // if request came from a prerendered page, bail + throw new Error(`${event.route.id} is not prerenderable`); + } else { + // if request came direct from the crawler, signal that + // this route cannot be prerendered, but don't bail + return new Response(undefined, { status: 204 }); + } + } + + try { + let response = await handler( + /** @type {import('@sveltejs/kit').RequestEvent>} */ (event) + ); + + if (!(response instanceof Response)) { + throw new Error( + `Invalid response from route ${event.url.pathname}: handler should return a Response object` + ); + } + + if (state.prerendering) { + // the returned Response might have immutable Headers + // so we should clone them before trying to mutate them + response = new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers: new Headers(response.headers) + }); + response.headers.set('x-sveltekit-prerender', String(prerender)); + } + + return response; + } catch (e) { + if (e instanceof Redirect) { + return new Response(undefined, { + status: e.status, + headers: { location: e.location } + }); + } + + throw e; + } +} + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + */ +export function is_endpoint_request(event) { + const { method, headers } = event.request; + + // These methods exist exclusively for endpoints + if (ENDPOINT_METHODS.has(method) && !PAGE_METHODS.has(method)) { + return true; + } + + // use:enhance uses a custom header to disambiguate + if (method === 'POST' && headers.get('x-sveltekit-action') === 'true') return false; + + // GET/POST requests may be for endpoints or pages. We prefer endpoints if this isn't a text/html request + const accept = event.request.headers.get('accept') ?? '*/*'; + return negotiate(accept, ['*', 'text/html']) !== 'text/html'; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/fetch.js b/node_modules/@sveltejs/kit/src/runtime/server/fetch.js new file mode 100644 index 0000000..8431e06 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/fetch.js @@ -0,0 +1,160 @@ +import * as set_cookie_parser from 'set-cookie-parser'; +import { respond } from './respond.js'; +import * as paths from '__sveltekit/paths'; + +/** + * @param {{ + * event: import('@sveltejs/kit').RequestEvent; + * options: import('types').SSROptions; + * manifest: import('@sveltejs/kit').SSRManifest; + * state: import('types').SSRState; + * get_cookie_header: (url: URL, header: string | null) => string; + * set_internal: (name: string, value: string, opts: import('cookie').CookieSerializeOptions) => void; + * }} opts + * @returns {typeof fetch} + */ +export function create_fetch({ event, options, manifest, state, get_cookie_header, set_internal }) { + return async (info, init) => { + const original_request = normalize_fetch_input(info, init, event.url); + + // some runtimes (e.g. Cloudflare) error if you access `request.mode`, + // annoyingly, so we need to read the value from the `init` object instead + let mode = (info instanceof Request ? info.mode : init?.mode) ?? 'cors'; + let credentials = + (info instanceof Request ? info.credentials : init?.credentials) ?? 'same-origin'; + + return await options.hooks.handleFetch({ + event, + request: original_request, + fetch: async (info, init) => { + const request = normalize_fetch_input(info, init, event.url); + + const url = new URL(request.url); + + if (!request.headers.has('origin')) { + request.headers.set('origin', event.url.origin); + } + + if (info !== original_request) { + mode = (info instanceof Request ? info.mode : init?.mode) ?? 'cors'; + credentials = + (info instanceof Request ? info.credentials : init?.credentials) ?? 'same-origin'; + } + + // Remove Origin, according to https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin#description + if ( + (request.method === 'GET' || request.method === 'HEAD') && + ((mode === 'no-cors' && url.origin !== event.url.origin) || + url.origin === event.url.origin) + ) { + request.headers.delete('origin'); + } + + if (url.origin !== event.url.origin) { + // Allow cookie passthrough for "credentials: same-origin" and "credentials: include" + // if SvelteKit is serving my.domain.com: + // - domain.com WILL NOT receive cookies + // - my.domain.com WILL receive cookies + // - api.domain.dom WILL NOT receive cookies + // - sub.my.domain.com WILL receive cookies + // ports do not affect the resolution + // leading dot prevents mydomain.com matching domain.com + // Do not forward other cookies for "credentials: include" because we don't know + // which cookie belongs to which domain (browser does not pass this info) + if (`.${url.hostname}`.endsWith(`.${event.url.hostname}`) && credentials !== 'omit') { + const cookie = get_cookie_header(url, request.headers.get('cookie')); + if (cookie) request.headers.set('cookie', cookie); + } + + return fetch(request); + } + + // handle fetch requests for static assets. e.g. prebaked data, etc. + // we need to support everything the browser's fetch supports + const prefix = paths.assets || paths.base; + const decoded = decodeURIComponent(url.pathname); + const filename = ( + decoded.startsWith(prefix) ? decoded.slice(prefix.length) : decoded + ).slice(1); + const filename_html = `${filename}/index.html`; // path may also match path/index.html + + const is_asset = manifest.assets.has(filename); + const is_asset_html = manifest.assets.has(filename_html); + + if (is_asset || is_asset_html) { + const file = is_asset ? filename : filename_html; + + if (state.read) { + const type = is_asset + ? manifest.mimeTypes[filename.slice(filename.lastIndexOf('.'))] + : 'text/html'; + + return new Response(state.read(file), { + headers: type ? { 'content-type': type } : {} + }); + } + + return await fetch(request); + } + + if (credentials !== 'omit') { + const cookie = get_cookie_header(url, request.headers.get('cookie')); + if (cookie) { + request.headers.set('cookie', cookie); + } + + const authorization = event.request.headers.get('authorization'); + if (authorization && !request.headers.has('authorization')) { + request.headers.set('authorization', authorization); + } + } + + if (!request.headers.has('accept')) { + request.headers.set('accept', '*/*'); + } + + if (!request.headers.has('accept-language')) { + request.headers.set( + 'accept-language', + /** @type {string} */ (event.request.headers.get('accept-language')) + ); + } + + /** @type {Response} */ + const response = await respond(request, options, manifest, { + ...state, + depth: state.depth + 1 + }); + + const set_cookie = response.headers.get('set-cookie'); + if (set_cookie) { + for (const str of set_cookie_parser.splitCookiesString(set_cookie)) { + const { name, value, ...options } = set_cookie_parser.parseString(str); + + // options.sameSite is string, something more specific is required - type cast is safe + set_internal( + name, + value, + /** @type {import('cookie').CookieSerializeOptions} */ (options) + ); + } + } + + return response; + } + }); + }; +} + +/** + * @param {RequestInfo | URL} info + * @param {RequestInit | undefined} init + * @param {URL} url + */ +function normalize_fetch_input(info, init, url) { + if (info instanceof Request) { + return info; + } + + return new Request(typeof info === 'string' ? new URL(info, url) : info, init); +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/index.js b/node_modules/@sveltejs/kit/src/runtime/server/index.js new file mode 100644 index 0000000..607f161 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/index.js @@ -0,0 +1,87 @@ +import { respond } from './respond.js'; +import { set_private_env, set_public_env } from '../shared-server.js'; +import { options, get_hooks } from '__SERVER__/internal.js'; +import { DEV } from 'esm-env'; +import { filter_private_env, filter_public_env } from '../../utils/env.js'; + +export class Server { + /** @type {import('types').SSROptions} */ + #options; + + /** @type {import('@sveltejs/kit').SSRManifest} */ + #manifest; + + /** @param {import('@sveltejs/kit').SSRManifest} manifest */ + constructor(manifest) { + /** @type {import('types').SSROptions} */ + this.#options = options; + this.#manifest = manifest; + } + + /** + * @param {{ + * env: Record + * }} opts + */ + async init({ env }) { + // Take care: Some adapters may have to call `Server.init` per-request to set env vars, + // so anything that shouldn't be rerun should be wrapped in an `if` block to make sure it hasn't + // been done already. + // set env, in case it's used in initialisation + set_private_env( + filter_private_env(env, { + public_prefix: this.#options.env_public_prefix, + private_prefix: this.#options.env_private_prefix + }) + ); + set_public_env( + filter_public_env(env, { + public_prefix: this.#options.env_public_prefix, + private_prefix: this.#options.env_private_prefix + }) + ); + + if (!this.#options.hooks) { + try { + const module = await get_hooks(); + + this.#options.hooks = { + handle: module.handle || (({ event, resolve }) => resolve(event)), + handleError: module.handleError || (({ error }) => console.error(error)), + handleFetch: module.handleFetch || (({ request, fetch }) => fetch(request)) + }; + } catch (error) { + if (DEV) { + this.#options.hooks = { + handle: () => { + throw error; + }, + handleError: ({ error }) => console.error(error), + handleFetch: ({ request, fetch }) => fetch(request) + }; + } else { + throw error; + } + } + } + } + + /** + * @param {Request} request + * @param {import('types').RequestOptions} options + */ + async respond(request, options) { + // TODO this should probably have been removed for 1.0 — i think we can get rid of it? + if (!(request instanceof Request)) { + throw new Error( + 'The first argument to server.respond must be a Request object. See https://github.com/sveltejs/kit/pull/3384 for details' + ); + } + + return respond(request, this.#options, this.#manifest, { + ...options, + error: false, + depth: 0 + }); + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/page/actions.js b/node_modules/@sveltejs/kit/src/runtime/server/page/actions.js new file mode 100644 index 0000000..0d65681 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/page/actions.js @@ -0,0 +1,282 @@ +import * as devalue from 'devalue'; +import { error, json } from '../../../exports/index.js'; +import { normalize_error } from '../../../utils/error.js'; +import { is_form_content_type, negotiate } from '../../../utils/http.js'; +import { HttpError, Redirect, ActionFailure } from '../../control.js'; +import { handle_error_and_jsonify } from '../utils.js'; + +/** @param {import('@sveltejs/kit').RequestEvent} event */ +export function is_action_json_request(event) { + const accept = negotiate(event.request.headers.get('accept') ?? '*/*', [ + 'application/json', + 'text/html' + ]); + + return accept === 'application/json' && event.request.method === 'POST'; +} + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('types').SSROptions} options + * @param {import('types').SSRNode['server'] | undefined} server + */ +export async function handle_action_json_request(event, options, server) { + const actions = server?.actions; + + if (!actions) { + // TODO should this be a different error altogether? + const no_actions_error = error(405, 'POST method not allowed. No actions exist for this page'); + return action_json( + { + type: 'error', + error: await handle_error_and_jsonify(event, options, no_actions_error) + }, + { + status: no_actions_error.status, + headers: { + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 + // "The server must generate an Allow header field in a 405 status code response" + allow: 'GET' + } + } + ); + } + + check_named_default_separate(actions); + + try { + const data = await call_action(event, actions); + + if (__SVELTEKIT_DEV__) { + validate_action_return(data); + } + + if (data instanceof ActionFailure) { + return action_json({ + type: 'failure', + status: data.status, + // @ts-expect-error we assign a string to what is supposed to be an object. That's ok + // because we don't use the object outside, and this way we have better code navigation + // through knowing where the related interface is used. + data: stringify_action_response(data.data, /** @type {string} */ (event.route.id)) + }); + } else { + return action_json({ + type: 'success', + status: data ? 200 : 204, + // @ts-expect-error see comment above + data: stringify_action_response(data, /** @type {string} */ (event.route.id)) + }); + } + } catch (e) { + const err = normalize_error(e); + + if (err instanceof Redirect) { + return action_json_redirect(err); + } + + return action_json( + { + type: 'error', + error: await handle_error_and_jsonify(event, options, check_incorrect_fail_use(err)) + }, + { + status: err instanceof HttpError ? err.status : 500 + } + ); + } +} + +/** + * @param {HttpError | Error} error + */ +function check_incorrect_fail_use(error) { + return error instanceof ActionFailure + ? new Error('Cannot "throw fail()". Use "return fail()"') + : error; +} + +/** + * @param {import('@sveltejs/kit').Redirect} redirect + */ +export function action_json_redirect(redirect) { + return action_json({ + type: 'redirect', + status: redirect.status, + location: redirect.location + }); +} + +/** + * @param {import('@sveltejs/kit').ActionResult} data + * @param {ResponseInit} [init] + */ +function action_json(data, init) { + return json(data, init); +} + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + */ +export function is_action_request(event) { + return event.request.method === 'POST'; +} + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('types').SSRNode['server'] | undefined} server + * @returns {Promise} + */ +export async function handle_action_request(event, server) { + const actions = server?.actions; + + if (!actions) { + // TODO should this be a different error altogether? + event.setHeaders({ + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 + // "The server must generate an Allow header field in a 405 status code response" + allow: 'GET' + }); + return { + type: 'error', + error: error(405, 'POST method not allowed. No actions exist for this page') + }; + } + + check_named_default_separate(actions); + + try { + const data = await call_action(event, actions); + + if (__SVELTEKIT_DEV__) { + validate_action_return(data); + } + + if (data instanceof ActionFailure) { + return { + type: 'failure', + status: data.status, + data: data.data + }; + } else { + return { + type: 'success', + status: 200, + // @ts-expect-error this will be removed upon serialization, so `undefined` is the same as omission + data + }; + } + } catch (e) { + const err = normalize_error(e); + + if (err instanceof Redirect) { + return { + type: 'redirect', + status: err.status, + location: err.location + }; + } + + return { + type: 'error', + error: check_incorrect_fail_use(err) + }; + } +} + +/** + * @param {import('@sveltejs/kit').Actions} actions + */ +function check_named_default_separate(actions) { + if (actions.default && Object.keys(actions).length > 1) { + throw new Error( + 'When using named actions, the default action cannot be used. See the docs for more info: https://kit.svelte.dev/docs/form-actions#named-actions' + ); + } +} + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {NonNullable} actions + * @throws {Redirect | ActionFailure | HttpError | Error} + */ +async function call_action(event, actions) { + const url = new URL(event.request.url); + + let name = 'default'; + for (const param of url.searchParams) { + if (param[0].startsWith('/')) { + name = param[0].slice(1); + if (name === 'default') { + throw new Error('Cannot use reserved action name "default"'); + } + break; + } + } + + const action = actions[name]; + if (!action) { + throw new Error(`No action with name '${name}' found`); + } + + if (!is_form_content_type(event.request)) { + throw new Error( + `Actions expect form-encoded data (received ${event.request.headers.get('content-type')})` + ); + } + + return action(event); +} + +/** @param {any} data */ +function validate_action_return(data) { + if (data instanceof Redirect) { + throw new Error('Cannot `return redirect(...)` — use `throw redirect(...)` instead'); + } + + if (data instanceof HttpError) { + throw new Error( + 'Cannot `return error(...)` — use `throw error(...)` or `return fail(...)` instead' + ); + } +} + +/** + * Try to `devalue.uneval` the data object, and if it fails, return a proper Error with context + * @param {any} data + * @param {string} route_id + */ +export function uneval_action_response(data, route_id) { + return try_deserialize(data, devalue.uneval, route_id); +} + +/** + * Try to `devalue.stringify` the data object, and if it fails, return a proper Error with context + * @param {any} data + * @param {string} route_id + */ +function stringify_action_response(data, route_id) { + return try_deserialize(data, devalue.stringify, route_id); +} + +/** + * @param {any} data + * @param {(data: any) => string} fn + * @param {string} route_id + */ +function try_deserialize(data, fn, route_id) { + try { + return fn(data); + } catch (e) { + // If we're here, the data could not be serialized with devalue + const error = /** @type {any} */ (e); + + if ('path' in error) { + let message = `Data returned from action inside ${route_id} is not serializable: ${error.message}`; + if (error.path !== '') message += ` (data.${error.path})`; + throw new Error(message); + } + + throw error; + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/page/crypto.js b/node_modules/@sveltejs/kit/src/runtime/server/page/crypto.js new file mode 100644 index 0000000..9af02da --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/page/crypto.js @@ -0,0 +1,239 @@ +const encoder = new TextEncoder(); + +/** + * SHA-256 hashing function adapted from https://bitwiseshiftleft.github.io/sjcl + * modified and redistributed under BSD license + * @param {string} data + */ +export function sha256(data) { + if (!key[0]) precompute(); + + const out = init.slice(0); + const array = encode(data); + + for (let i = 0; i < array.length; i += 16) { + const w = array.subarray(i, i + 16); + + let tmp; + let a; + let b; + + let out0 = out[0]; + let out1 = out[1]; + let out2 = out[2]; + let out3 = out[3]; + let out4 = out[4]; + let out5 = out[5]; + let out6 = out[6]; + let out7 = out[7]; + + /* Rationale for placement of |0 : + * If a value can overflow is original 32 bits by a factor of more than a few + * million (2^23 ish), there is a possibility that it might overflow the + * 53-bit mantissa and lose precision. + * + * To avoid this, we clamp back to 32 bits by |'ing with 0 on any value that + * propagates around the loop, and on the hash state out[]. I don't believe + * that the clamps on out4 and on out0 are strictly necessary, but it's close + * (for out4 anyway), and better safe than sorry. + * + * The clamps on out[] are necessary for the output to be correct even in the + * common case and for short inputs. + */ + + for (let i = 0; i < 64; i++) { + // load up the input word for this round + + if (i < 16) { + tmp = w[i]; + } else { + a = w[(i + 1) & 15]; + + b = w[(i + 14) & 15]; + + tmp = w[i & 15] = + (((a >>> 7) ^ (a >>> 18) ^ (a >>> 3) ^ (a << 25) ^ (a << 14)) + + ((b >>> 17) ^ (b >>> 19) ^ (b >>> 10) ^ (b << 15) ^ (b << 13)) + + w[i & 15] + + w[(i + 9) & 15]) | + 0; + } + + tmp = + tmp + + out7 + + ((out4 >>> 6) ^ (out4 >>> 11) ^ (out4 >>> 25) ^ (out4 << 26) ^ (out4 << 21) ^ (out4 << 7)) + + (out6 ^ (out4 & (out5 ^ out6))) + + key[i]; // | 0; + + // shift register + out7 = out6; + out6 = out5; + out5 = out4; + + out4 = (out3 + tmp) | 0; + + out3 = out2; + out2 = out1; + out1 = out0; + + out0 = + (tmp + + ((out1 & out2) ^ (out3 & (out1 ^ out2))) + + ((out1 >>> 2) ^ + (out1 >>> 13) ^ + (out1 >>> 22) ^ + (out1 << 30) ^ + (out1 << 19) ^ + (out1 << 10))) | + 0; + } + + out[0] = (out[0] + out0) | 0; + out[1] = (out[1] + out1) | 0; + out[2] = (out[2] + out2) | 0; + out[3] = (out[3] + out3) | 0; + out[4] = (out[4] + out4) | 0; + out[5] = (out[5] + out5) | 0; + out[6] = (out[6] + out6) | 0; + out[7] = (out[7] + out7) | 0; + } + + const bytes = new Uint8Array(out.buffer); + reverse_endianness(bytes); + + return base64(bytes); +} + +/** The SHA-256 initialization vector */ +const init = new Uint32Array(8); + +/** The SHA-256 hash key */ +const key = new Uint32Array(64); + +/** Function to precompute init and key. */ +function precompute() { + /** @param {number} x */ + function frac(x) { + return (x - Math.floor(x)) * 0x100000000; + } + + let prime = 2; + + for (let i = 0; i < 64; prime++) { + let is_prime = true; + + for (let factor = 2; factor * factor <= prime; factor++) { + if (prime % factor === 0) { + is_prime = false; + + break; + } + } + + if (is_prime) { + if (i < 8) { + init[i] = frac(prime ** (1 / 2)); + } + + key[i] = frac(prime ** (1 / 3)); + + i++; + } + } +} + +/** @param {Uint8Array} bytes */ +function reverse_endianness(bytes) { + for (let i = 0; i < bytes.length; i += 4) { + const a = bytes[i + 0]; + const b = bytes[i + 1]; + const c = bytes[i + 2]; + const d = bytes[i + 3]; + + bytes[i + 0] = d; + bytes[i + 1] = c; + bytes[i + 2] = b; + bytes[i + 3] = a; + } +} + +/** @param {string} str */ +function encode(str) { + const encoded = encoder.encode(str); + const length = encoded.length * 8; + + // result should be a multiple of 512 bits in length, + // with room for a 1 (after the data) and two 32-bit + // words containing the original input bit length + const size = 512 * Math.ceil((length + 65) / 512); + const bytes = new Uint8Array(size / 8); + bytes.set(encoded); + + // append a 1 + bytes[encoded.length] = 0b10000000; + + reverse_endianness(bytes); + + // add the input bit length + const words = new Uint32Array(bytes.buffer); + words[words.length - 2] = Math.floor(length / 0x100000000); // this will always be zero for us + words[words.length - 1] = length; + + return words; +} + +/* + Based on https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727 + + MIT License + Copyright (c) 2020 Egor Nepomnyaschih + 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. +*/ +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** @param {Uint8Array} bytes */ +export function base64(bytes) { + const l = bytes.length; + + let result = ''; + let i; + + for (i = 2; i < l; i += 3) { + result += chars[bytes[i - 2] >> 2]; + result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += chars[((bytes[i - 1] & 0x0f) << 2) | (bytes[i] >> 6)]; + result += chars[bytes[i] & 0x3f]; + } + + if (i === l + 1) { + // 1 octet yet to write + result += chars[bytes[i - 2] >> 2]; + result += chars[(bytes[i - 2] & 0x03) << 4]; + result += '=='; + } + + if (i === l) { + // 2 octets yet to write + result += chars[bytes[i - 2] >> 2]; + result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]; + result += chars[(bytes[i - 1] & 0x0f) << 2]; + result += '='; + } + + return result; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/page/csp.js b/node_modules/@sveltejs/kit/src/runtime/server/page/csp.js new file mode 100644 index 0000000..77cde16 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/page/csp.js @@ -0,0 +1,254 @@ +import { escape_html_attr } from '../../../utils/escape.js'; +import { base64, sha256 } from './crypto.js'; + +const array = new Uint8Array(16); + +function generate_nonce() { + crypto.getRandomValues(array); + return base64(array); +} + +const quoted = new Set([ + 'self', + 'unsafe-eval', + 'unsafe-hashes', + 'unsafe-inline', + 'none', + 'strict-dynamic', + 'report-sample', + 'wasm-unsafe-eval', + 'script' +]); + +const crypto_pattern = /^(nonce|sha\d\d\d)-/; + +// CSP and CSP Report Only are extremely similar with a few caveats +// the easiest/DRYest way to express this is with some private encapsulation +class BaseProvider { + /** @type {boolean} */ + #use_hashes; + + /** @type {boolean} */ + #script_needs_csp; + + /** @type {boolean} */ + #style_needs_csp; + + /** @type {import('types').CspDirectives} */ + #directives; + + /** @type {import('types').Csp.Source[]} */ + #script_src; + + /** @type {import('types').Csp.Source[]} */ + #style_src; + + /** @type {string} */ + #nonce; + + /** + * @param {boolean} use_hashes + * @param {import('types').CspDirectives} directives + * @param {string} nonce + */ + constructor(use_hashes, directives, nonce) { + this.#use_hashes = use_hashes; + this.#directives = __SVELTEKIT_DEV__ ? { ...directives } : directives; // clone in dev so we can safely mutate + + const d = this.#directives; + + if (__SVELTEKIT_DEV__) { + // remove strict-dynamic in dev... + // TODO reinstate this if we can figure out how to make strict-dynamic work + // if (d['default-src']) { + // d['default-src'] = d['default-src'].filter((name) => name !== 'strict-dynamic'); + // if (d['default-src'].length === 0) delete d['default-src']; + // } + + // if (d['script-src']) { + // d['script-src'] = d['script-src'].filter((name) => name !== 'strict-dynamic'); + // if (d['script-src'].length === 0) delete d['script-src']; + // } + + const effective_style_src = d['style-src'] || d['default-src']; + + // ...and add unsafe-inline so we can inject `; + } + + for (const dep of stylesheets) { + const path = prefixed(dep); + + const attributes = ['rel="stylesheet"']; + + if (inline_styles.has(dep)) { + // don't load stylesheets that are already inlined + // include them in disabled state so that Vite can detect them and doesn't try to add them + attributes.push('disabled', 'media="(max-width: 0)"'); + } else { + if (resolve_opts.preload({ type: 'css', path })) { + const preload_atts = ['rel="preload"', 'as="style"']; + link_header_preloads.add(`<${encodeURI(path)}>; ${preload_atts.join(';')}; nopush`); + } + } + + head += `\n\t\t`; + } + + for (const dep of fonts) { + const path = prefixed(dep); + + if (resolve_opts.preload({ type: 'font', path })) { + const ext = dep.slice(dep.lastIndexOf('.') + 1); + const attributes = [ + 'rel="preload"', + 'as="font"', + `type="font/${ext}"`, + `href="${path}"`, + 'crossorigin' + ]; + + head += `\n\t\t`; + } + } + + const global = __SVELTEKIT_DEV__ ? '__sveltekit_dev' : `__sveltekit_${options.version_hash}`; + + const { data, chunks } = get_data( + event, + options, + branch.map((b) => b.server_data), + global + ); + + if (page_config.ssr && page_config.csr) { + body += `\n\t\t\t${fetched + .map((item) => + serialize_data(item, resolve_opts.filterSerializedResponseHeaders, !!state.prerendering) + ) + .join('\n\t\t\t')}`; + } + + if (page_config.csr) { + const included_modulepreloads = Array.from(modulepreloads, (dep) => prefixed(dep)).filter( + (path) => resolve_opts.preload({ type: 'js', path }) + ); + + for (const path of included_modulepreloads) { + // see the kit.output.preloadStrategy option for details on why we have multiple options here + link_header_preloads.add(`<${encodeURI(path)}>; rel="modulepreload"; nopush`); + if (options.preload_strategy !== 'modulepreload') { + head += `\n\t\t`; + } else if (state.prerendering) { + head += `\n\t\t`; + } + } + + const blocks = []; + + const properties = [ + paths.assets && `assets: ${s(paths.assets)}`, + `base: ${base_expression}`, + `env: ${s(public_env)}` + ].filter(Boolean); + + if (chunks) { + blocks.push('const deferred = new Map();'); + + properties.push(`defer: (id) => new Promise((fulfil, reject) => { + deferred.set(id, { fulfil, reject }); + })`); + + properties.push(`resolve: ({ id, data, error }) => { + const { fulfil, reject } = deferred.get(id); + deferred.delete(id); + + if (error) reject(error); + else fulfil(data); + }`); + } + + blocks.push(`${global} = { + ${properties.join(',\n\t\t\t\t\t\t')} + };`); + + const args = ['app', 'element']; + + blocks.push('const element = document.currentScript.parentElement;'); + + if (page_config.ssr) { + const serialized = { form: 'null', error: 'null' }; + + blocks.push(`const data = ${data};`); + + if (form_value) { + serialized.form = uneval_action_response( + form_value, + /** @type {string} */ (event.route.id) + ); + } + + if (error) { + serialized.error = devalue.uneval(error); + } + + const hydrate = [ + `node_ids: [${branch.map(({ node }) => node.index).join(', ')}]`, + 'data', + `form: ${serialized.form}`, + `error: ${serialized.error}` + ]; + + if (status !== 200) { + hydrate.push(`status: ${status}`); + } + + if (options.embedded) { + hydrate.push(`params: ${devalue.uneval(event.params)}`, `route: ${s(event.route)}`); + } + + args.push(`{\n\t\t\t\t\t\t\t${hydrate.join(',\n\t\t\t\t\t\t\t')}\n\t\t\t\t\t\t}`); + } + + blocks.push(`Promise.all([ + import(${s(prefixed(client.start))}), + import(${s(prefixed(client.app))}) + ]).then(([kit, app]) => { + kit.start(${args.join(', ')}); + });`); + + if (options.service_worker) { + const opts = __SVELTEKIT_DEV__ ? ", { type: 'module' }" : ''; + + // we use an anonymous function instead of an arrow function to support + // older browsers (https://github.com/sveltejs/kit/pull/5417) + blocks.push(`if ('serviceWorker' in navigator) { + addEventListener('load', function () { + navigator.serviceWorker.register('${prefixed('service-worker.js')}'${opts}); + }); + }`); + } + + const init_app = ` + { + ${blocks.join('\n\n\t\t\t\t\t')} + } + `; + csp.add_script(init_app); + + body += `\n\t\t\t${init_app}\n\t\t`; + } + + const headers = new Headers({ + 'x-sveltekit-page': 'true', + 'content-type': 'text/html' + }); + + if (state.prerendering) { + // TODO read headers set with setHeaders and convert into http-equiv where possible + const http_equiv = []; + + const csp_headers = csp.csp_provider.get_meta(); + if (csp_headers) { + http_equiv.push(csp_headers); + } + + if (state.prerendering.cache) { + http_equiv.push(``); + } + + if (http_equiv.length > 0) { + head = http_equiv.join('\n') + head; + } + } else { + const csp_header = csp.csp_provider.get_header(); + if (csp_header) { + headers.set('content-security-policy', csp_header); + } + const report_only_header = csp.report_only_provider.get_header(); + if (report_only_header) { + headers.set('content-security-policy-report-only', report_only_header); + } + + if (link_header_preloads.size) { + headers.set('link', Array.from(link_header_preloads).join(', ')); + } + } + + // add the content after the script/css links so the link elements are parsed first + head += rendered.head; + + const html = options.templates.app({ + head, + body, + assets, + nonce: /** @type {string} */ (csp.nonce), + env: public_env + }); + + // TODO flush chunks as early as we can + const transformed = + (await resolve_opts.transformPageChunk({ + html, + done: true + })) || ''; + + if (!chunks) { + headers.set('etag', `"${hash(transformed)}"`); + } + + if (DEV) { + if (page_config.csr) { + if (transformed.split('`, so the script element might be unexpectedly + * kept open until until an unrelated HTML comment in the page. + * + * U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018 + * browsers. + * + * @see tests for unsafe parsing examples. + * @see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements + * @see https://html.spec.whatwg.org/multipage/syntax.html#cdata-rcdata-restrictions + * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-state + * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state + * @see https://github.com/tc39/proposal-json-superset + * @type {Record} + */ +const replacements = { + '<': '\\u003C', + '\u2028': '\\u2028', + '\u2029': '\\u2029' +}; + +const pattern = new RegExp(`[${Object.keys(replacements).join('')}]`, 'g'); + +/** + * Generates a raw HTML string containing a safe script element carrying data and associated attributes. + * + * It escapes all the special characters needed to guarantee the element is unbroken, but care must + * be taken to ensure it is inserted in the document at an acceptable position for a script element, + * and that the resulting string isn't further modified. + * + * @param {import('./types.js').Fetched} fetched + * @param {(name: string, value: string) => boolean} filter + * @param {boolean} [prerendering] + * @returns {string} The raw HTML of a script element carrying the JSON payload. + * @example const html = serialize_data('/data.json', null, { foo: 'bar' }); + */ +export function serialize_data(fetched, filter, prerendering = false) { + /** @type {Record} */ + const headers = {}; + + let cache_control = null; + let age = null; + let varyAny = false; + + for (const [key, value] of fetched.response.headers) { + if (filter(key, value)) { + headers[key] = value; + } + + if (key === 'cache-control') cache_control = value; + else if (key === 'age') age = value; + else if (key === 'vary' && value.trim() === '*') varyAny = true; + } + + const payload = { + status: fetched.response.status, + statusText: fetched.response.statusText, + headers, + body: fetched.response_body + }; + + const safe_payload = JSON.stringify(payload).replace(pattern, (match) => replacements[match]); + + const attrs = [ + 'type="application/json"', + 'data-sveltekit-fetched', + `data-url=${escape_html_attr(fetched.url)}` + ]; + + if (fetched.request_headers || fetched.request_body) { + /** @type {import('types').StrictBody[]} */ + const values = []; + + if (fetched.request_headers) { + values.push([...new Headers(fetched.request_headers)].join(',')); + } + + if (fetched.request_body) { + values.push(fetched.request_body); + } + + attrs.push(`data-hash="${hash(...values)}"`); + } + + // Compute the time the response should be cached, taking into account max-age and age. + // Do not cache at all if a `Vary: *` header is present, as this indicates that the + // cache is likely to get busted. + if (!prerendering && fetched.method === 'GET' && cache_control && !varyAny) { + const match = /s-maxage=(\d+)/g.exec(cache_control) ?? /max-age=(\d+)/g.exec(cache_control); + if (match) { + const ttl = +match[1] - +(age ?? '0'); + attrs.push(`data-ttl="${ttl}"`); + } + } + + return ``; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/page/types.d.ts b/node_modules/@sveltejs/kit/src/runtime/server/page/types.d.ts new file mode 100644 index 0000000..f5b0c2d --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/page/types.d.ts @@ -0,0 +1,35 @@ +import { CookieSerializeOptions } from 'cookie'; +import { SSRNode, CspDirectives, ServerDataNode } from 'types'; + +export interface Fetched { + url: string; + method: string; + request_body?: string | ArrayBufferView | null; + request_headers?: HeadersInit | undefined; + response_body: string; + response: Response; +} + +export type Loaded = { + node: SSRNode; + data: Record | null; + server_data: ServerDataNode | null; +}; + +type CspMode = 'hash' | 'nonce' | 'auto'; + +export interface CspConfig { + mode: CspMode; + directives: CspDirectives; + reportOnly: CspDirectives; +} + +export interface CspOpts { + prerender: boolean; +} + +export interface Cookie { + name: string; + value: string; + options: CookieSerializeOptions; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/respond.js b/node_modules/@sveltejs/kit/src/runtime/server/respond.js new file mode 100644 index 0000000..c6e02da --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/respond.js @@ -0,0 +1,500 @@ +import { DEV } from 'esm-env'; +import { base } from '__sveltekit/paths'; +import { is_endpoint_request, render_endpoint } from './endpoint.js'; +import { render_page } from './page/index.js'; +import { render_response } from './page/render.js'; +import { respond_with_error } from './page/respond_with_error.js'; +import { is_form_content_type } from '../../utils/http.js'; +import { handle_fatal_error, method_not_allowed, redirect_response } from './utils.js'; +import { + decode_pathname, + decode_params, + disable_search, + has_data_suffix, + normalize_path, + strip_data_suffix +} from '../../utils/url.js'; +import { exec } from '../../utils/routing.js'; +import { redirect_json_response, render_data } from './data/index.js'; +import { add_cookies_to_headers, get_cookies } from './cookie.js'; +import { create_fetch } from './fetch.js'; +import { Redirect } from '../control.js'; +import { + validate_layout_exports, + validate_layout_server_exports, + validate_page_exports, + validate_page_server_exports, + validate_server_exports +} from '../../utils/exports.js'; +import { get_option } from '../../utils/options.js'; +import { error, json, text } from '../../exports/index.js'; +import { action_json_redirect, is_action_json_request } from './page/actions.js'; +import { INVALIDATED_PARAM } from '../shared.js'; + +/* global __SVELTEKIT_ADAPTER_NAME__ */ + +/** @type {import('types').RequiredResolveOptions['transformPageChunk']} */ +const default_transform = ({ html }) => html; + +/** @type {import('types').RequiredResolveOptions['filterSerializedResponseHeaders']} */ +const default_filter = () => false; + +/** @type {import('types').RequiredResolveOptions['preload']} */ +const default_preload = ({ type }) => type === 'js' || type === 'css'; + +const page_methods = new Set(['GET', 'HEAD', 'POST']); + +const allowed_page_methods = new Set(['GET', 'HEAD', 'OPTIONS']); + +/** + * @param {Request} request + * @param {import('types').SSROptions} options + * @param {import('@sveltejs/kit').SSRManifest} manifest + * @param {import('types').SSRState} state + * @returns {Promise} + */ +export async function respond(request, options, manifest, state) { + /** URL but stripped from the potential `/__data.json` suffix and its search param */ + const url = new URL(request.url); + + if (options.csrf_check_origin) { + const forbidden = + is_form_content_type(request) && + (request.method === 'POST' || + request.method === 'PUT' || + request.method === 'PATCH' || + request.method === 'DELETE') && + request.headers.get('origin') !== url.origin; + + if (forbidden) { + const csrf_error = error(403, `Cross-site ${request.method} form submissions are forbidden`); + if (request.headers.get('accept') === 'application/json') { + return json(csrf_error.body, { status: csrf_error.status }); + } + return text(csrf_error.body.message, { status: csrf_error.status }); + } + } + + let decoded; + try { + decoded = decode_pathname(url.pathname); + } catch { + return text('Malformed URI', { status: 400 }); + } + + /** @type {import('types').SSRRoute | null} */ + let route = null; + + /** @type {Record} */ + let params = {}; + + if (base && !state.prerendering?.fallback) { + if (!decoded.startsWith(base)) { + return text('Not found', { status: 404 }); + } + decoded = decoded.slice(base.length) || '/'; + } + + const is_data_request = has_data_suffix(decoded); + /** @type {boolean[] | undefined} */ + let invalidated_data_nodes; + if (is_data_request) { + decoded = strip_data_suffix(decoded) || '/'; + url.pathname = strip_data_suffix(url.pathname) || '/'; + invalidated_data_nodes = url.searchParams + .get(INVALIDATED_PARAM) + ?.split('') + .map((node) => node === '1'); + url.searchParams.delete(INVALIDATED_PARAM); + } + + if (!state.prerendering?.fallback) { + // TODO this could theoretically break — should probably be inside a try-catch + const matchers = await manifest._.matchers(); + + for (const candidate of manifest._.routes) { + const match = candidate.pattern.exec(decoded); + if (!match) continue; + + const matched = exec(match, candidate.params, matchers); + if (matched) { + route = candidate; + params = decode_params(matched); + break; + } + } + } + + /** @type {import('types').TrailingSlash | void} */ + let trailing_slash = undefined; + + /** @type {Record} */ + const headers = {}; + + /** @type {Record} */ + let cookies_to_add = {}; + + /** @type {import('@sveltejs/kit').RequestEvent} */ + const event = { + // @ts-expect-error `cookies` and `fetch` need to be created after the `event` itself + cookies: null, + // @ts-expect-error + fetch: null, + getClientAddress: + state.getClientAddress || + (() => { + throw new Error( + `${__SVELTEKIT_ADAPTER_NAME__} does not specify getClientAddress. Please raise an issue` + ); + }), + locals: {}, + params, + platform: state.platform, + request, + route: { id: route?.id ?? null }, + setHeaders: (new_headers) => { + for (const key in new_headers) { + const lower = key.toLowerCase(); + const value = new_headers[key]; + + if (lower === 'set-cookie') { + throw new Error( + 'Use `event.cookies.set(name, value, options)` instead of `event.setHeaders` to set cookies' + ); + } else if (lower in headers) { + throw new Error(`"${key}" header is already set`); + } else { + headers[lower] = value; + + if (state.prerendering && lower === 'cache-control') { + state.prerendering.cache = /** @type {string} */ (value); + } + } + } + }, + url, + isDataRequest: is_data_request, + isSubRequest: state.depth > 0 + }; + + /** @type {import('types').RequiredResolveOptions} */ + let resolve_opts = { + transformPageChunk: default_transform, + filterSerializedResponseHeaders: default_filter, + preload: default_preload + }; + + try { + // determine whether we need to redirect to add/remove a trailing slash + if (route) { + // if `paths.base === '/a/b/c`, then the root route is `/a/b/c/`, + // regardless of the `trailingSlash` route option + if (url.pathname === base || url.pathname === base + '/') { + trailing_slash = 'always'; + } else if (route.page) { + const nodes = await Promise.all([ + // we use == here rather than === because [undefined] serializes as "[null]" + ...route.page.layouts.map((n) => (n == undefined ? n : manifest._.nodes[n]())), + manifest._.nodes[route.page.leaf]() + ]); + + if (DEV) { + const layouts = nodes.slice(0, -1); + const page = nodes.at(-1); + + for (const layout of layouts) { + if (layout) { + validate_layout_server_exports( + layout.server, + /** @type {string} */ (layout.server_id) + ); + validate_layout_exports( + layout.universal, + /** @type {string} */ (layout.universal_id) + ); + } + } + + if (page) { + validate_page_server_exports(page.server, /** @type {string} */ (page.server_id)); + validate_page_exports(page.universal, /** @type {string} */ (page.universal_id)); + } + } + + trailing_slash = get_option(nodes, 'trailingSlash'); + } else if (route.endpoint) { + const node = await route.endpoint(); + trailing_slash = node.trailingSlash; + + if (DEV) { + validate_server_exports(node, /** @type {string} */ (route.endpoint_id)); + } + } + + if (!is_data_request) { + const normalized = normalize_path(url.pathname, trailing_slash ?? 'never'); + + if (normalized !== url.pathname && !state.prerendering?.fallback) { + return new Response(undefined, { + status: 308, + headers: { + 'x-sveltekit-normalize': '1', + location: + // ensure paths starting with '//' are not treated as protocol-relative + (normalized.startsWith('//') ? url.origin + normalized : normalized) + + (url.search === '?' ? '' : url.search) + } + }); + } + } + } + + const { cookies, new_cookies, get_cookie_header, set_internal } = get_cookies( + request, + url, + trailing_slash ?? 'never' + ); + + cookies_to_add = new_cookies; + event.cookies = cookies; + event.fetch = create_fetch({ + event, + options, + manifest, + state, + get_cookie_header, + set_internal + }); + + if (state.prerendering && !state.prerendering.fallback) disable_search(url); + + const response = await options.hooks.handle({ + event, + resolve: (event, opts) => + resolve(event, opts).then((response) => { + // add headers/cookies here, rather than inside `resolve`, so that we + // can do it once for all responses instead of once per `return` + for (const key in headers) { + const value = headers[key]; + response.headers.set(key, /** @type {string} */ (value)); + } + + add_cookies_to_headers(response.headers, Object.values(cookies_to_add)); + + if (state.prerendering && event.route.id !== null) { + response.headers.set('x-sveltekit-routeid', encodeURI(event.route.id)); + } + + return response; + }) + }); + + // respond with 304 if etag matches + if (response.status === 200 && response.headers.has('etag')) { + let if_none_match_value = request.headers.get('if-none-match'); + + // ignore W/ prefix https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match#directives + if (if_none_match_value?.startsWith('W/"')) { + if_none_match_value = if_none_match_value.substring(2); + } + + const etag = /** @type {string} */ (response.headers.get('etag')); + + if (if_none_match_value === etag) { + const headers = new Headers({ etag }); + + // https://datatracker.ietf.org/doc/html/rfc7232#section-4.1 + set-cookie + for (const key of [ + 'cache-control', + 'content-location', + 'date', + 'expires', + 'vary', + 'set-cookie' + ]) { + const value = response.headers.get(key); + if (value) headers.set(key, value); + } + + return new Response(undefined, { + status: 304, + headers + }); + } + } + + // Edge case: If user does `return Response(30x)` in handle hook while processing a data request, + // we need to transform the redirect response to a corresponding JSON response. + if (is_data_request && response.status >= 300 && response.status <= 308) { + const location = response.headers.get('location'); + if (location) { + return redirect_json_response(new Redirect(/** @type {any} */ (response.status), location)); + } + } + + return response; + } catch (e) { + if (e instanceof Redirect) { + const response = is_data_request + ? redirect_json_response(e) + : route?.page && is_action_json_request(event) + ? action_json_redirect(e) + : redirect_response(e.status, e.location); + add_cookies_to_headers(response.headers, Object.values(cookies_to_add)); + return response; + } + return await handle_fatal_error(event, options, e); + } + + /** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('@sveltejs/kit').ResolveOptions} [opts] + */ + async function resolve(event, opts) { + try { + if (opts) { + if ('ssr' in opts) { + throw new Error( + 'ssr has been removed, set it in the appropriate +layout.js instead. See the PR for more information: https://github.com/sveltejs/kit/pull/6197' + ); + } + + resolve_opts = { + transformPageChunk: opts.transformPageChunk || default_transform, + filterSerializedResponseHeaders: opts.filterSerializedResponseHeaders || default_filter, + preload: opts.preload || default_preload + }; + } + + if (state.prerendering?.fallback) { + return await render_response({ + event, + options, + manifest, + state, + page_config: { ssr: false, csr: true }, + status: 200, + error: null, + branch: [], + fetched: [], + resolve_opts + }); + } + + if (route) { + const method = /** @type {import('types').HttpMethod} */ (event.request.method); + + /** @type {Response} */ + let response; + + if (is_data_request) { + response = await render_data( + event, + route, + options, + manifest, + state, + invalidated_data_nodes, + trailing_slash ?? 'never' + ); + } else if (route.endpoint && (!route.page || is_endpoint_request(event))) { + response = await render_endpoint(event, await route.endpoint(), state); + } else if (route.page) { + if (page_methods.has(method)) { + response = await render_page(event, route.page, options, manifest, state, resolve_opts); + } else { + const allowed_methods = new Set(allowed_page_methods); + const node = await manifest._.nodes[route.page.leaf](); + if (node?.server?.actions) { + allowed_methods.add('POST'); + } + + if (method === 'OPTIONS') { + // This will deny CORS preflight requests implicitly because we don't + // add the required CORS headers to the response. + response = new Response(null, { + status: 204, + headers: { + allow: Array.from(allowed_methods.values()).join(', ') + } + }); + } else { + const mod = [...allowed_methods].reduce((acc, curr) => { + acc[curr] = true; + return acc; + }, /** @type {Record} */ ({})); + response = method_not_allowed(mod, method); + } + } + } else { + // a route will always have a page or an endpoint, but TypeScript + // doesn't know that + throw new Error('This should never happen'); + } + + // If the route contains a page and an endpoint, we need to add a + // `Vary: Accept` header to the response because of browser caching + if (request.method === 'GET' && route.page && route.endpoint) { + const vary = response.headers + .get('vary') + ?.split(',') + ?.map((v) => v.trim().toLowerCase()); + if (!(vary?.includes('accept') || vary?.includes('*'))) { + // the returned response might have immutable headers, + // so we have to clone them before trying to mutate them + response = new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers: new Headers(response.headers) + }); + response.headers.append('Vary', 'Accept'); + } + } + + return response; + } + + if (state.error) { + return text('Internal Server Error', { + status: 500 + }); + } + + // if this request came direct from the user, rather than + // via our own `fetch`, render a 404 page + if (state.depth === 0) { + return await respond_with_error({ + event, + options, + manifest, + state, + status: 404, + error: new Error(`Not found: ${event.url.pathname}`), + resolve_opts + }); + } + + if (state.prerendering) { + return text('not found', { status: 404 }); + } + + // we can't load the endpoint from our own manifest, + // so we need to make an actual HTTP request + return await fetch(request); + } catch (e) { + // TODO if `e` is instead named `error`, some fucked up Vite transformation happens + // and I don't even know how to describe it. need to investigate at some point + + // HttpError from endpoint can end up here - TODO should it be handled there instead? + return await handle_fatal_error(event, options, e); + } finally { + event.cookies.set = () => { + throw new Error('Cannot use `cookies.set(...)` after the response has been generated'); + }; + + event.setHeaders = () => { + throw new Error('Cannot use `setHeaders(...)` after the response has been generated'); + }; + } + } +} diff --git a/node_modules/@sveltejs/kit/src/runtime/server/utils.js b/node_modules/@sveltejs/kit/src/runtime/server/utils.js new file mode 100644 index 0000000..ec5831b --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/server/utils.js @@ -0,0 +1,169 @@ +import { DEV } from 'esm-env'; +import { json, text } from '../../exports/index.js'; +import { coalesce_to_error } from '../../utils/error.js'; +import { negotiate } from '../../utils/http.js'; +import { HttpError } from '../control.js'; +import { fix_stack_trace } from '../shared-server.js'; +import { ENDPOINT_METHODS } from '../../constants.js'; + +/** @param {any} body */ +export function is_pojo(body) { + if (typeof body !== 'object') return false; + + if (body) { + if (body instanceof Uint8Array) return false; + if (body instanceof ReadableStream) return false; + } + + return true; +} + +/** + * @param {Partial>} mod + * @param {import('types').HttpMethod} method + */ +export function method_not_allowed(mod, method) { + return text(`${method} method not allowed`, { + status: 405, + headers: { + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 + // "The server must generate an Allow header field in a 405 status code response" + allow: allowed_methods(mod).join(', ') + } + }); +} + +/** @param {Partial>} mod */ +export function allowed_methods(mod) { + const allowed = Array.from(ENDPOINT_METHODS).filter((method) => method in mod); + + if ('GET' in mod || 'HEAD' in mod) allowed.push('HEAD'); + + return allowed; +} + +/** + * Return as a response that renders the error.html + * + * @param {import('types').SSROptions} options + * @param {number} status + * @param {string} message + */ +export function static_error_page(options, status, message) { + let page = options.templates.error({ status, message }); + + if (DEV) { + // inject Vite HMR client, for easier debugging + page = page.replace('', ''); + } + + return text(page, { + headers: { 'content-type': 'text/html; charset=utf-8' }, + status + }); +} + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('types').SSROptions} options + * @param {unknown} error + */ +export async function handle_fatal_error(event, options, error) { + error = error instanceof HttpError ? error : coalesce_to_error(error); + const status = error instanceof HttpError ? error.status : 500; + const body = await handle_error_and_jsonify(event, options, error); + + // ideally we'd use sec-fetch-dest instead, but Safari — quelle surprise — doesn't support it + const type = negotiate(event.request.headers.get('accept') || 'text/html', [ + 'application/json', + 'text/html' + ]); + + if (event.isDataRequest || type === 'application/json') { + return json(body, { + status + }); + } + + return static_error_page(options, status, body.message); +} + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('types').SSROptions} options + * @param {any} error + * @returns {Promise} + */ +export async function handle_error_and_jsonify(event, options, error) { + if (error instanceof HttpError) { + return error.body; + } else { + if (__SVELTEKIT_DEV__ && typeof error == 'object') { + error = new Proxy(error, { + get: (target, property) => { + if (property === 'stack') { + return fix_stack_trace(target.stack); + } + + return Reflect.get(target, property, target); + } + }); + } + + return ( + (await options.hooks.handleError({ error, event })) ?? { + message: event.route.id != null ? 'Internal Error' : 'Not Found' + } + ); + } +} + +/** + * @param {number} status + * @param {string} location + */ +export function redirect_response(status, location) { + const response = new Response(undefined, { + status, + headers: { location } + }); + return response; +} + +/** + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {Error & { path: string }} error + */ +export function clarify_devalue_error(event, error) { + if (error.path) { + return `Data returned from \`load\` while rendering ${event.route.id} is not serializable: ${error.message} (data${error.path})`; + } + + if (error.path === '') { + return `Data returned from \`load\` while rendering ${event.route.id} is not a plain object`; + } + + // belt and braces — this should never happen + return error.message; +} + +/** + * @param {import('types').ServerDataNode} node + */ +export function stringify_uses(node) { + const uses = []; + + if (node.uses && node.uses.dependencies.size > 0) { + uses.push(`"dependencies":${JSON.stringify(Array.from(node.uses.dependencies))}`); + } + + if (node.uses && node.uses.params.size > 0) { + uses.push(`"params":${JSON.stringify(Array.from(node.uses.params))}`); + } + + if (node.uses?.parent) uses.push('"parent":1'); + if (node.uses?.route) uses.push('"route":1'); + if (node.uses?.url) uses.push('"url":1'); + + return `"uses":{${uses.join(',')}}`; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/shared-server.js b/node_modules/@sveltejs/kit/src/runtime/shared-server.js new file mode 100644 index 0000000..ed1c5ef --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/shared-server.js @@ -0,0 +1,23 @@ +/** @type {Record} */ +export let private_env = {}; + +/** @type {Record} */ +export let public_env = {}; + +/** @param {string} stack */ +export let fix_stack_trace = (stack) => stack; + +/** @type {(environment: Record) => void} */ +export function set_private_env(environment) { + private_env = environment; +} + +/** @type {(environment: Record) => void} */ +export function set_public_env(environment) { + public_env = environment; +} + +/** @param {(stack: string) => string} value */ +export function set_fix_stack_trace(value) { + fix_stack_trace = value; +} diff --git a/node_modules/@sveltejs/kit/src/runtime/shared.js b/node_modules/@sveltejs/kit/src/runtime/shared.js new file mode 100644 index 0000000..d8f60e7 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/runtime/shared.js @@ -0,0 +1,14 @@ +/** + * @param {string} route_id + * @param {string} dep + */ +export function validate_depends(route_id, dep) { + const match = /^(moz-icon|view-source|jar):/.exec(dep); + if (match) { + console.warn( + `${route_id}: Calling \`depends('${dep}')\` will throw an error in Firefox because \`${match[1]}\` is a special URI scheme` + ); + } +} + +export const INVALIDATED_PARAM = 'x-sveltekit-invalidated'; diff --git a/node_modules/@sveltejs/kit/src/types/ambient-private.d.ts b/node_modules/@sveltejs/kit/src/types/ambient-private.d.ts new file mode 100644 index 0000000..843cc94 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/ambient-private.d.ts @@ -0,0 +1,11 @@ +declare global { + const __SVELTEKIT_ADAPTER_NAME__: string; + const __SVELTEKIT_APP_VERSION_FILE__: string; + const __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: number; + const __SVELTEKIT_DEV__: boolean; + const __SVELTEKIT_EMBEDDED__: boolean; + var Bun: object; + var Deno: object; +} + +export {}; diff --git a/node_modules/@sveltejs/kit/src/types/ambient.d.ts b/node_modules/@sveltejs/kit/src/types/ambient.d.ts new file mode 100644 index 0000000..b733140 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/ambient.d.ts @@ -0,0 +1,108 @@ +/** + * It's possible to tell SvelteKit how to type objects inside your app by declaring the `App` namespace. By default, a new project will have a file called `src/app.d.ts` containing the following: + * + * ```ts + * declare global { + * namespace App { + * // interface Error {} + * // interface Locals {} + * // interface PageData {} + * // interface Platform {} + * } + * } + * + * export {}; + * ``` + * + * The `export {}` line exists because without it, the file would be treated as an _ambient module_ which prevents you from adding `import` declarations. + * If you need to add ambient `declare module` declarations, do so in a separate file like `src/ambient.d.ts`. + * + * By populating these interfaces, you will gain type safety when using `event.locals`, `event.platform`, and `data` from `load` functions. + */ +declare namespace App { + /** + * Defines the common shape of expected and unexpected errors. Expected errors are thrown using the `error` function. Unexpected errors are handled by the `handleError` hooks which should return this shape. + */ + export interface Error { + message: string; + } + + /** + * The interface that defines `event.locals`, which can be accessed in [hooks](https://kit.svelte.dev/docs/hooks) (`handle`, and `handleError`), server-only `load` functions, and `+server.js` files. + */ + export interface Locals {} + + /** + * Defines the common shape of the [$page.data store](https://kit.svelte.dev/docs/modules#$app-stores-page) - that is, the data that is shared between all pages. + * The `Load` and `ServerLoad` functions in `./$types` will be narrowed accordingly. + * Use optional properties for data that is only present on specific pages. Do not add an index signature (`[key: string]: any`). + */ + export interface PageData {} + + /** + * If your adapter provides [platform-specific context](https://kit.svelte.dev/docs/adapters#platform-specific-context) via `event.platform`, you can specify it here. + */ + export interface Platform {} +} + +/** + * This module is only available to [service workers](https://kit.svelte.dev/docs/service-workers). + */ +declare module '$service-worker' { + /** + * The `base` path of the deployment. Typically this is equivalent to `config.kit.paths.base`, but it is calculated from `location.pathname` meaning that it will continue to work correctly if the site is deployed to a subdirectory. + * Note that there is a `base` but no `assets`, since service workers cannot be used if `config.kit.paths.assets` is specified. + */ + export const base: string; + /** + * An array of URL strings representing the files generated by Vite, suitable for caching with `cache.addAll(build)`. + * During development, this is an empty array. + */ + export const build: string[]; + /** + * An array of URL strings representing the files in your static directory, or whatever directory is specified by `config.kit.files.assets`. You can customize which files are included from `static` directory using [`config.kit.serviceWorker.files`](https://kit.svelte.dev/docs/configuration) + */ + export const files: string[]; + /** + * An array of pathnames corresponding to prerendered pages and endpoints. + * During development, this is an empty array. + */ + export const prerendered: string[]; + /** + * See [`config.kit.version`](https://kit.svelte.dev/docs/configuration#version). It's useful for generating unique cache names inside your service worker, so that a later deployment of your app can invalidate old caches. + */ + export const version: string; +} + +/** Internal version of $app/environment */ +declare module '__sveltekit/environment' { + /** + * SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. + */ + export const building: boolean; + /** + * The value of `config.kit.version.name`. + */ + export const version: string; + export function set_building(): void; +} + +/** Internal version of $app/paths */ +declare module '__sveltekit/paths' { + /** + * A string that matches [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths). + * + * Example usage: `
Link` + */ + export let base: '' | `/${string}`; + /** + * An absolute path that matches [`config.kit.paths.assets`](https://kit.svelte.dev/docs/configuration#paths). + * + * > If a value for `config.kit.paths.assets` is specified, it will be replaced with `'/_svelte_kit_assets'` during `vite dev` or `vite preview`, since the assets don't yet live at their eventual URL. + */ + export let assets: '' | `https://${string}` | `http://${string}` | '/_svelte_kit_assets'; + export let relative: boolean | undefined; // TODO in 2.0, make this a `boolean` that defaults to `true` + export function reset(): void; + export function override(paths: { base: string; assets: string }): void; + export function set_assets(path: string): void; +} diff --git a/node_modules/@sveltejs/kit/src/types/internal.d.ts b/node_modules/@sveltejs/kit/src/types/internal.d.ts new file mode 100644 index 0000000..ddd074b --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/internal.d.ts @@ -0,0 +1,417 @@ +import { SvelteComponent } from 'svelte'; +import { + Config, + ServerLoad, + Handle, + HandleServerError, + KitConfig, + Load, + RequestHandler, + ResolveOptions, + Server, + ServerInitOptions, + HandleFetch, + Actions, + HandleClientError +} from '@sveltejs/kit'; +import { + HttpMethod, + MaybePromise, + PrerenderOption, + RequestOptions, + TrailingSlash +} from './private.js'; + +export interface ServerModule { + Server: typeof InternalServer; +} + +export interface ServerInternalModule { + set_building(building: boolean): void; + set_assets(path: string): void; + set_private_env(environment: Record): void; + set_public_env(environment: Record): void; + set_version(version: string): void; + set_fix_stack_trace(fix_stack_trace: (stack: string) => string): void; +} + +export interface Asset { + file: string; + size: number; + type: string | null; +} + +export interface AssetDependencies { + file: string; + imports: string[]; + stylesheets: string[]; + fonts: string[]; +} + +export interface BuildData { + app_dir: string; + app_path: string; + manifest_data: ManifestData; + service_worker: string | null; + client: { + start: string; + app: string; + imports: string[]; + stylesheets: string[]; + fonts: string[]; + } | null; + server_manifest: import('vite').Manifest; +} + +export interface CSRPageNode { + component: typeof SvelteComponent; + universal: { + load?: Load; + trailingSlash?: TrailingSlash; + }; +} + +export type CSRPageNodeLoader = () => Promise; + +/** + * Definition of a client side route. + * The boolean in the tuples indicates whether the route has a server load. + */ +export type CSRRoute = { + id: string; + exec(path: string): undefined | Record; + errors: Array; + layouts: Array<[has_server_load: boolean, node_loader: CSRPageNodeLoader] | undefined>; + leaf: [has_server_load: boolean, node_loader: CSRPageNodeLoader]; +}; + +export interface Deferred { + fulfil: (value: any) => void; + reject: (error: Error) => void; +} + +export type GetParams = (match: RegExpExecArray) => Record; + +export interface ServerHooks { + handleFetch: HandleFetch; + handle: Handle; + handleError: HandleServerError; +} + +export interface ClientHooks { + handleError: HandleClientError; +} + +export interface Env { + private: Record; + public: Record; +} + +export class InternalServer extends Server { + init(options: ServerInitOptions): Promise; + respond( + request: Request, + options: RequestOptions & { + prerendering?: PrerenderOptions; + read: (file: string) => Buffer; + } + ): Promise; +} + +export interface ManifestData { + assets: Asset[]; + nodes: PageNode[]; + routes: RouteData[]; + matchers: Record; +} + +export interface PageNode { + depth: number; + component?: string; // TODO supply default component if it's missing (bit of an edge case) + universal?: string; + server?: string; + parent_id?: string; + parent?: PageNode; + /** + * Filled with the pages that reference this layout (if this is a layout) + */ + child_pages?: PageNode[]; +} + +export interface PrerenderDependency { + response: Response; + body: null | string | Uint8Array; +} + +export interface PrerenderOptions { + cache?: string; // including this here is a bit of a hack, but it makes it easy to add + fallback?: boolean; + dependencies: Map; +} + +export type RecursiveRequired = { + // Recursive implementation of TypeScript's Required utility type. + // Will recursively continue until it reaches a primitive or Function + [K in keyof T]-?: Extract extends never // If it does not have a Function type + ? RecursiveRequired // recursively continue through. + : T[K]; // Use the exact type for everything else +}; + +export type RequiredResolveOptions = Required; + +export interface RouteParam { + name: string; + matcher: string; + optional: boolean; + rest: boolean; + chained: boolean; +} + +/** + * Represents a route segment in the app. It can either be an intermediate node + * with only layout/error pages, or a leaf, at which point either `page` and `leaf` + * or `endpoint` is set. + */ +export interface RouteData { + id: string; + parent: RouteData | null; + + segment: string; + pattern: RegExp; + params: RouteParam[]; + + layout: PageNode | null; + error: PageNode | null; + leaf: PageNode | null; + + page: { + layouts: Array; + errors: Array; + leaf: number; + } | null; + + endpoint: { + file: string; + } | null; +} + +export type ServerRedirectNode = { + type: 'redirect'; + location: string; +}; + +export type ServerNodesResponse = { + type: 'data'; + /** + * If `null`, then there was no load function <- TODO is this outdated now with the recent changes? + */ + nodes: Array; +}; + +export type ServerDataResponse = ServerRedirectNode | ServerNodesResponse; + +/** + * Signals a successful response of the server `load` function. + * The `uses` property tells the client when it's possible to reuse this data + * in a subsequent request. + */ +export interface ServerDataNode { + type: 'data'; + /** + * The serialized version of this contains a serialized representation of any deferred promises, + * which will be resolved later through chunk nodes. + */ + data: Record | null; + uses: Uses; + slash?: TrailingSlash; +} + +/** + * Resolved data/error of a deferred promise. + */ +export interface ServerDataChunkNode { + type: 'chunk'; + id: number; + data?: Record; + error?: any; +} + +/** + * Signals that the server `load` function was not run, and the + * client should use what it has in memory + */ +export interface ServerDataSkippedNode { + type: 'skip'; +} + +/** + * Signals that the server `load` function failed + */ +export interface ServerErrorNode { + type: 'error'; + error: App.Error; + /** + * Only set for HttpErrors + */ + status?: number; +} + +export interface ServerMetadataRoute { + config: any; + api: { + methods: HttpMethod[]; + }; + page: { + methods: Array<'GET' | 'POST'>; + }; + methods: HttpMethod[]; + prerender: PrerenderOption | undefined; + entries: Array | undefined; +} + +export interface ServerMetadata { + nodes: Array<{ has_server_load: boolean }>; + routes: Map; +} + +export interface SSRComponent { + default: { + render(props: Record): { + html: string; + head: string; + css: { + code: string; + map: any; // TODO + }; + }; + }; +} + +export type SSRComponentLoader = () => Promise; + +export interface SSRNode { + component: SSRComponentLoader; + /** index into the `components` array in client/manifest.js */ + index: number; + /** external JS files */ + imports: string[]; + /** external CSS files */ + stylesheets: string[]; + /** external font files */ + fonts: string[]; + /** inlined styles */ + inline_styles?(): MaybePromise>; + + universal: { + load?: Load; + prerender?: PrerenderOption; + ssr?: boolean; + csr?: boolean; + trailingSlash?: TrailingSlash; + config?: any; + entries?: PrerenderEntryGenerator; + }; + + server: { + load?: ServerLoad; + prerender?: PrerenderOption; + ssr?: boolean; + csr?: boolean; + trailingSlash?: TrailingSlash; + actions?: Actions; + config?: any; + entries?: PrerenderEntryGenerator; + }; + + universal_id: string; + server_id: string; +} + +export type SSRNodeLoader = () => Promise; + +export interface SSROptions { + app_template_contains_nonce: boolean; + csp: ValidatedConfig['kit']['csp']; + csrf_check_origin: boolean; + track_server_fetches: boolean; + embedded: boolean; + env_public_prefix: string; + env_private_prefix: string; + hooks: ServerHooks; + preload_strategy: ValidatedConfig['kit']['output']['preloadStrategy']; + root: SSRComponent['default']; + service_worker: boolean; + templates: { + app(values: { + head: string; + body: string; + assets: string; + nonce: string; + env: Record; + }): string; + error(values: { message: string; status: number }): string; + }; + version_hash: string; +} + +export interface PageNodeIndexes { + errors: Array; + layouts: Array; + leaf: number; +} + +export type PrerenderEntryGenerator = () => MaybePromise>>; + +export type SSREndpoint = Partial> & { + prerender?: PrerenderOption; + trailingSlash?: TrailingSlash; + config?: any; + entries?: PrerenderEntryGenerator; +}; + +export interface SSRRoute { + id: string; + pattern: RegExp; + params: RouteParam[]; + page: PageNodeIndexes | null; + endpoint: (() => Promise) | null; + endpoint_id?: string; +} + +export interface SSRState { + fallback?: string; + getClientAddress(): string; + /** + * True if we're currently attempting to render an error page + */ + error: boolean; + /** + * Allows us to prevent `event.fetch` from making infinitely looping internal requests + */ + depth: number; + platform?: any; + prerendering?: PrerenderOptions; + /** + * When fetching data from a +server.js endpoint in `load`, the page's + * prerender option is inherited by the endpoint, unless overridden + */ + prerender_default?: PrerenderOption; + read?: (file: string) => Buffer; +} + +export type StrictBody = string | ArrayBufferView; + +export interface Uses { + dependencies: Set; + params: Set; + parent: boolean; + route: boolean; + url: boolean; +} + +export type ValidatedConfig = RecursiveRequired; + +export type ValidatedKitConfig = RecursiveRequired; + +export * from '../exports/index'; +export * from './private.js'; diff --git a/node_modules/@sveltejs/kit/src/types/private.d.ts b/node_modules/@sveltejs/kit/src/types/private.d.ts new file mode 100644 index 0000000..e84cf16 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/private.d.ts @@ -0,0 +1,235 @@ +// This module contains types that are visible in the documentation, +// but which cannot be imported from `@sveltejs/kit`. Care should +// be taken to avoid breaking changes when editing this file + +import { RouteDefinition } from '@sveltejs/kit'; + +export interface AdapterEntry { + /** + * A string that uniquely identifies an HTTP service (e.g. serverless function) and is used for deduplication. + * For example, `/foo/a-[b]` and `/foo/[c]` are different routes, but would both + * be represented in a Netlify _redirects file as `/foo/:param`, so they share an ID + */ + id: string; + + /** + * A function that compares the candidate route with the current route to determine + * if it should be grouped with the current route. + * + * Use cases: + * - Fallback pages: `/foo/[c]` is a fallback for `/foo/a-[b]`, and `/[...catchall]` is a fallback for all routes + * - Grouping routes that share a common `config`: `/foo` should be deployed to the edge, `/bar` and `/baz` should be deployed to a serverless function + */ + filter(route: RouteDefinition): boolean; + + /** + * A function that is invoked once the entry has been created. This is where you + * should write the function to the filesystem and generate redirect manifests. + */ + complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise; +} + +// Based on https://github.com/josh-hemphill/csp-typed-directives/blob/latest/src/csp.types.ts +// +// MIT License +// +// Copyright (c) 2021-present, Joshua Hemphill +// Copyright (c) 2021, Tecnico Corporation +// +// 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. + +export namespace Csp { + type ActionSource = 'strict-dynamic' | 'report-sample'; + type BaseSource = + | 'self' + | 'unsafe-eval' + | 'unsafe-hashes' + | 'unsafe-inline' + | 'wasm-unsafe-eval' + | 'none'; + type CryptoSource = `${'nonce' | 'sha256' | 'sha384' | 'sha512'}-${string}`; + type FrameSource = HostSource | SchemeSource | 'self' | 'none'; + type HostNameScheme = `${string}.${string}` | 'localhost'; + type HostSource = `${HostProtocolSchemes}${HostNameScheme}${PortScheme}`; + type HostProtocolSchemes = `${string}://` | ''; + type HttpDelineator = '/' | '?' | '#' | '\\'; + type PortScheme = `:${number}` | '' | ':*'; + type SchemeSource = 'http:' | 'https:' | 'data:' | 'mediastream:' | 'blob:' | 'filesystem:'; + type Source = HostSource | SchemeSource | CryptoSource | BaseSource; + type Sources = Source[]; + type UriPath = `${HttpDelineator}${string}`; +} + +export interface CspDirectives { + 'child-src'?: Csp.Sources; + 'default-src'?: Array; + 'frame-src'?: Csp.Sources; + 'worker-src'?: Csp.Sources; + 'connect-src'?: Csp.Sources; + 'font-src'?: Csp.Sources; + 'img-src'?: Csp.Sources; + 'manifest-src'?: Csp.Sources; + 'media-src'?: Csp.Sources; + 'object-src'?: Csp.Sources; + 'prefetch-src'?: Csp.Sources; + 'script-src'?: Array; + 'script-src-elem'?: Csp.Sources; + 'script-src-attr'?: Csp.Sources; + 'style-src'?: Array; + 'style-src-elem'?: Csp.Sources; + 'style-src-attr'?: Csp.Sources; + 'base-uri'?: Array; + sandbox?: Array< + | 'allow-downloads-without-user-activation' + | 'allow-forms' + | 'allow-modals' + | 'allow-orientation-lock' + | 'allow-pointer-lock' + | 'allow-popups' + | 'allow-popups-to-escape-sandbox' + | 'allow-presentation' + | 'allow-same-origin' + | 'allow-scripts' + | 'allow-storage-access-by-user-activation' + | 'allow-top-navigation' + | 'allow-top-navigation-by-user-activation' + >; + 'form-action'?: Array; + 'frame-ancestors'?: Array; + 'navigate-to'?: Array; + 'report-uri'?: Csp.UriPath[]; + 'report-to'?: string[]; + + 'require-trusted-types-for'?: Array<'script'>; + 'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>; + 'upgrade-insecure-requests'?: boolean; + + /** @deprecated */ + 'require-sri-for'?: Array<'script' | 'style' | 'script style'>; + + /** @deprecated */ + 'block-all-mixed-content'?: boolean; + + /** @deprecated */ + 'plugin-types'?: Array<`${string}/${string}` | 'none'>; + + /** @deprecated */ + referrer?: Array< + | 'no-referrer' + | 'no-referrer-when-downgrade' + | 'origin' + | 'origin-when-cross-origin' + | 'same-origin' + | 'strict-origin' + | 'strict-origin-when-cross-origin' + | 'unsafe-url' + | 'none' + >; +} + +export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS'; + +export interface Logger { + (msg: string): void; + success(msg: string): void; + error(msg: string): void; + warn(msg: string): void; + minor(msg: string): void; + info(msg: string): void; +} + +export type MaybePromise = T | Promise; + +export interface Prerendered { + /** + * A map of `path` to `{ file }` objects, where a path like `/foo` corresponds to `foo.html` and a path like `/bar/` corresponds to `bar/index.html`. + */ + pages: Map< + string, + { + /** The location of the .html file relative to the output directory */ + file: string; + } + >; + /** + * A map of `path` to `{ type }` objects. + */ + assets: Map< + string, + { + /** The MIME type of the asset */ + type: string; + } + >; + /** + * A map of redirects encountered during prerendering. + */ + redirects: Map< + string, + { + status: number; + location: string; + } + >; + /** An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config) */ + paths: string[]; +} + +export interface PrerenderHttpErrorHandler { + (details: { + status: number; + path: string; + referrer: string | null; + referenceType: 'linked' | 'fetched'; + message: string; + }): void; +} + +export interface PrerenderMissingIdHandler { + (details: { path: string; id: string; referrers: string[]; message: string }): void; +} + +export interface PrerenderEntryGeneratorMismatchHandler { + (details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void; +} + +export type PrerenderHttpErrorHandlerValue = 'fail' | 'warn' | 'ignore' | PrerenderHttpErrorHandler; +export type PrerenderMissingIdHandlerValue = 'fail' | 'warn' | 'ignore' | PrerenderMissingIdHandler; +export type PrerenderEntryGeneratorMismatchHandlerValue = + | 'fail' + | 'warn' + | 'ignore' + | PrerenderEntryGeneratorMismatchHandler; + +export type PrerenderOption = boolean | 'auto'; + +export type PrerenderMap = Map; + +export interface RequestOptions { + getClientAddress(): string; + platform?: App.Platform; +} + +export interface RouteSegment { + content: string; + dynamic: boolean; + rest: boolean; +} + +export type TrailingSlash = 'never' | 'always' | 'ignore'; diff --git a/node_modules/@sveltejs/kit/src/types/synthetic/$env+dynamic+private.md b/node_modules/@sveltejs/kit/src/types/synthetic/$env+dynamic+private.md new file mode 100644 index 0000000..99fabd4 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/synthetic/$env+dynamic+private.md @@ -0,0 +1,10 @@ +This module provides access to runtime environment variables, as defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/master/packages/adapter-node) (or running [`vite preview`](https://kit.svelte.dev/docs/cli)), this is equivalent to `process.env`. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://kit.svelte.dev/docs/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](https://kit.svelte.dev/docs/configuration#env) (if configured). + +This module cannot be imported into client-side code. + +```ts +import { env } from '$env/dynamic/private'; +console.log(env.DEPLOYMENT_SPECIFIC_VARIABLE); +``` + +> In `dev`, `$env/dynamic` always includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter. diff --git a/node_modules/@sveltejs/kit/src/types/synthetic/$env+dynamic+public.md b/node_modules/@sveltejs/kit/src/types/synthetic/$env+dynamic+public.md new file mode 100644 index 0000000..b70626b --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/synthetic/$env+dynamic+public.md @@ -0,0 +1,8 @@ +Similar to [`$env/dynamic/private`](https://kit.svelte.dev/docs/modules#$env-dynamic-private), but only includes variables that begin with [`config.kit.env.publicPrefix`](https://kit.svelte.dev/docs/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code. + +Note that public dynamic environment variables must all be sent from the server to the client, causing larger network requests — when possible, use `$env/static/public` instead. + +```ts +import { env } from '$env/dynamic/public'; +console.log(env.PUBLIC_DEPLOYMENT_SPECIFIC_VARIABLE); +``` diff --git a/node_modules/@sveltejs/kit/src/types/synthetic/$env+static+private.md b/node_modules/@sveltejs/kit/src/types/synthetic/$env+static+private.md new file mode 100644 index 0000000..40704d2 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/synthetic/$env+static+private.md @@ -0,0 +1,19 @@ +Environment variables [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env`. Like [`$env/dynamic/private`](https://kit.svelte.dev/docs/modules#$env-dynamic-private), this module cannot be imported into client-side code. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://kit.svelte.dev/docs/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](https://kit.svelte.dev/docs/configuration#env) (if configured). + +_Unlike_ [`$env/dynamic/private`](https://kit.svelte.dev/docs/modules#$env-dynamic-private), the values exported from this module are statically injected into your bundle at build time, enabling optimisations like dead code elimination. + +```ts +import { API_KEY } from '$env/static/private'; +``` + +Note that all environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed: + +``` +MY_FEATURE_FLAG="" +``` + +You can override `.env` values from the command line like so: + +```bash +MY_FEATURE_FLAG="enabled" npm run dev +``` diff --git a/node_modules/@sveltejs/kit/src/types/synthetic/$env+static+public.md b/node_modules/@sveltejs/kit/src/types/synthetic/$env+static+public.md new file mode 100644 index 0000000..2b55250 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/synthetic/$env+static+public.md @@ -0,0 +1,7 @@ +Similar to [`$env/static/private`](https://kit.svelte.dev/docs/modules#$env-static-private), except that it only includes environment variables that begin with [`config.kit.env.publicPrefix`](https://kit.svelte.dev/docs/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code. + +Values are replaced statically at build time. + +```ts +import { PUBLIC_BASE_URL } from '$env/static/public'; +``` diff --git a/node_modules/@sveltejs/kit/src/types/synthetic/$lib.md b/node_modules/@sveltejs/kit/src/types/synthetic/$lib.md new file mode 100644 index 0000000..9b76001 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/types/synthetic/$lib.md @@ -0,0 +1,5 @@ +This is a simple alias to `src/lib`, or whatever directory is specified as [`config.kit.files.lib`](https://kit.svelte.dev/docs/configuration#files). It allows you to access common components and utility modules without `../../../../` nonsense. + +### `$lib/server` + +A subdirectory of `$lib`. SvelteKit will prevent you from importing any modules in `$lib/server` into client-side code. See [server-only modules](/docs/server-only-modules). diff --git a/node_modules/@sveltejs/kit/src/utils/array.js b/node_modules/@sveltejs/kit/src/utils/array.js new file mode 100644 index 0000000..08f9384 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/array.js @@ -0,0 +1,9 @@ +/** + * Removes nullish values from an array. + * + * @template T + * @param {Array} arr + */ +export function compact(arr) { + return arr.filter(/** @returns {val is NonNullable} */ (val) => val != null); +} diff --git a/node_modules/@sveltejs/kit/src/utils/env.js b/node_modules/@sveltejs/kit/src/utils/env.js new file mode 100644 index 0000000..e2106f3 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/env.js @@ -0,0 +1,33 @@ +/** + * @param {Record} env + * @param {{ + * public_prefix: string; + * private_prefix: string; + * }} prefixes + * @returns {Record} + */ +export function filter_private_env(env, { public_prefix, private_prefix }) { + return Object.fromEntries( + Object.entries(env).filter( + ([k]) => + k.startsWith(private_prefix) && (public_prefix === '' || !k.startsWith(public_prefix)) + ) + ); +} + +/** + * @param {Record} env + * @param {{ + * public_prefix: string; + * private_prefix: string; + * }} prefixes + * @returns {Record} + */ +export function filter_public_env(env, { public_prefix, private_prefix }) { + return Object.fromEntries( + Object.entries(env).filter( + ([k]) => + k.startsWith(public_prefix) && (private_prefix === '' || !k.startsWith(private_prefix)) + ) + ); +} diff --git a/node_modules/@sveltejs/kit/src/utils/error.js b/node_modules/@sveltejs/kit/src/utils/error.js new file mode 100644 index 0000000..d485dc7 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/error.js @@ -0,0 +1,22 @@ +/** + * @param {unknown} err + * @return {Error} + */ +export function coalesce_to_error(err) { + return err instanceof Error || + (err && /** @type {any} */ (err).name && /** @type {any} */ (err).message) + ? /** @type {Error} */ (err) + : new Error(JSON.stringify(err)); +} + +/** + * This is an identity function that exists to make TypeScript less + * paranoid about people throwing things that aren't errors, which + * frankly is not something we should care about + * @param {unknown} error + */ +export function normalize_error(error) { + return /** @type {import('../runtime/control.js').Redirect | import('../runtime/control.js').HttpError | Error} */ ( + error + ); +} diff --git a/node_modules/@sveltejs/kit/src/utils/escape.js b/node_modules/@sveltejs/kit/src/utils/escape.js new file mode 100644 index 0000000..543e1a1 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/escape.js @@ -0,0 +1,46 @@ +/** + * When inside a double-quoted attribute value, only `&` and `"` hold special meaning. + * @see https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state + * @type {Record} + */ +const escape_html_attr_dict = { + '&': '&', + '"': '"' +}; + +const escape_html_attr_regex = new RegExp( + // special characters + `[${Object.keys(escape_html_attr_dict).join('')}]|` + + // high surrogate without paired low surrogate + '[\\ud800-\\udbff](?![\\udc00-\\udfff])|' + + // a valid surrogate pair, the only match with 2 code units + // we match it so that we can match unpaired low surrogates in the same pass + // TODO: use lookbehind assertions once they are widely supported: (?...`; + */ +export function escape_html_attr(str) { + const escaped_str = str.replace(escape_html_attr_regex, (match) => { + if (match.length === 2) { + // valid surrogate pair + return match; + } + + return escape_html_attr_dict[match] ?? `&#${match.charCodeAt(0)};`; + }); + + return `"${escaped_str}"`; +} diff --git a/node_modules/@sveltejs/kit/src/utils/exports.js b/node_modules/@sveltejs/kit/src/utils/exports.js new file mode 100644 index 0000000..8ec6ec0 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/exports.js @@ -0,0 +1,92 @@ +/** + * @param {Set} expected + */ +function validator(expected) { + /** + * @param {any} module + * @param {string} [file] + */ + function validate(module, file) { + if (!module) return; + + for (const key in module) { + if (key[0] === '_' || expected.has(key)) continue; // key is valid in this module + + const values = [...expected.values()]; + + const hint = + hint_for_supported_files(key, file?.slice(file.lastIndexOf('.'))) ?? + `valid exports are ${values.join(', ')}, or anything with a '_' prefix`; + + throw new Error(`Invalid export '${key}'${file ? ` in ${file}` : ''} (${hint})`); + } + } + + return validate; +} + +/** + * @param {string} key + * @param {string} ext + * @returns {string | void} + */ +function hint_for_supported_files(key, ext = '.js') { + const supported_files = []; + + if (valid_layout_exports.has(key)) { + supported_files.push(`+layout${ext}`); + } + + if (valid_page_exports.has(key)) { + supported_files.push(`+page${ext}`); + } + + if (valid_layout_server_exports.has(key)) { + supported_files.push(`+layout.server${ext}`); + } + + if (valid_page_server_exports.has(key)) { + supported_files.push(`+page.server${ext}`); + } + + if (valid_server_exports.has(key)) { + supported_files.push(`+server${ext}`); + } + + if (supported_files.length > 0) { + return `'${key}' is a valid export in ${supported_files.slice(0, -1).join(', ')}${ + supported_files.length > 1 ? ' or ' : '' + }${supported_files.at(-1)}`; + } +} + +const valid_layout_exports = new Set([ + 'load', + 'prerender', + 'csr', + 'ssr', + 'trailingSlash', + 'config' +]); +const valid_page_exports = new Set([...valid_layout_exports, 'entries']); +const valid_layout_server_exports = new Set([...valid_layout_exports]); +const valid_page_server_exports = new Set([...valid_layout_server_exports, 'actions', 'entries']); +const valid_server_exports = new Set([ + 'GET', + 'POST', + 'PATCH', + 'PUT', + 'DELETE', + 'OPTIONS', + 'HEAD', + 'prerender', + 'trailingSlash', + 'config', + 'entries' +]); + +export const validate_layout_exports = validator(valid_layout_exports); +export const validate_page_exports = validator(valid_page_exports); +export const validate_layout_server_exports = validator(valid_layout_server_exports); +export const validate_page_server_exports = validator(valid_page_server_exports); +export const validate_server_exports = validator(valid_server_exports); diff --git a/node_modules/@sveltejs/kit/src/utils/filesystem.js b/node_modules/@sveltejs/kit/src/utils/filesystem.js new file mode 100644 index 0000000..d79ead0 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/filesystem.js @@ -0,0 +1,183 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +/** @param {string} dir */ +export function mkdirp(dir) { + try { + fs.mkdirSync(dir, { recursive: true }); + } catch (/** @type {any} */ e) { + if (e.code === 'EEXIST') { + if (!fs.statSync(dir).isDirectory()) { + throw new Error(`Cannot create directory ${dir}, a file already exists at this position`); + } + return; + } + throw e; + } +} + +/** @param {string} path */ +export function rimraf(path) { + fs.rmSync(path, { force: true, recursive: true }); +} + +/** + * @param {string} source + * @param {string} target + * @param {{ + * filter?: (basename: string) => boolean; + * replace?: Record; + * }} opts + */ +export function copy(source, target, opts = {}) { + if (!fs.existsSync(source)) return []; + + /** @type {string[]} */ + const files = []; + + const prefix = posixify(target) + '/'; + + const regex = opts.replace + ? new RegExp(`\\b(${Object.keys(opts.replace).join('|')})\\b`, 'g') + : null; + + /** + * @param {string} from + * @param {string} to + */ + function go(from, to) { + if (opts.filter && !opts.filter(path.basename(from))) return; + + const stats = fs.statSync(from); + + if (stats.isDirectory()) { + fs.readdirSync(from).forEach((file) => { + go(path.join(from, file), path.join(to, file)); + }); + } else { + mkdirp(path.dirname(to)); + + if (opts.replace) { + const data = fs.readFileSync(from, 'utf-8'); + fs.writeFileSync( + to, + data.replace( + /** @type {RegExp} */ (regex), + (_match, key) => /** @type {Record} */ (opts.replace)[key] + ) + ); + } else { + fs.copyFileSync(from, to); + } + + files.push(to === target ? posixify(path.basename(to)) : posixify(to).replace(prefix, '')); + } + } + + go(source, target); + + return files; +} + +/** + * Get a list of all files in a directory + * @param {string} cwd - the directory to walk + * @param {boolean} [dirs] - whether to include directories in the result + * @returns {string[]} a list of all found files (and possibly directories) relative to `cwd` + */ +export function walk(cwd, dirs = false) { + /** @type {string[]} */ + const all_files = []; + + /** @param {string} dir */ + function walk_dir(dir) { + const files = fs.readdirSync(path.join(cwd, dir)); + + for (const file of files) { + const joined = path.join(dir, file); + const stats = fs.statSync(path.join(cwd, joined)); + if (stats.isDirectory()) { + if (dirs) all_files.push(joined); + walk_dir(joined); + } else { + all_files.push(joined); + } + } + } + + return walk_dir(''), all_files; +} + +/** @param {string} str */ +export function posixify(str) { + return str.replace(/\\/g, '/'); +} + +/** + * Like `path.join`, but posixified and with a leading `./` if necessary + * @param {string[]} str + */ +export function join_relative(...str) { + let result = posixify(path.join(...str)); + if (!result.startsWith('.')) { + result = `./${result}`; + } + return result; +} + +/** + * Like `path.relative`, but always posixified and with a leading `./` if necessary. + * Useful for JS imports so the path can safely reside inside of `node_modules`. + * Otherwise paths could be falsely interpreted as package paths. + * @param {string} from + * @param {string} to + */ +export function relative_path(from, to) { + return join_relative(path.relative(from, to)); +} + +/** + * Prepend given path with `/@fs` prefix + * @param {string} str + */ +export function to_fs(str) { + str = posixify(str); + return `/@fs${ + // Windows/Linux separation - Windows starts with a drive letter, we need a / in front there + str.startsWith('/') ? '' : '/' + }${str}`; +} + +/** + * Given an entry point like [cwd]/src/hooks, returns a filename like [cwd]/src/hooks.js or [cwd]/src/hooks/index.js + * @param {string} entry + * @returns {string|null} + */ +export function resolve_entry(entry) { + if (fs.existsSync(entry)) { + const stats = fs.statSync(entry); + if (stats.isDirectory()) { + return resolve_entry(path.join(entry, 'index')); + } + + return entry; + } else { + const dir = path.dirname(entry); + + if (fs.existsSync(dir)) { + const base = path.basename(entry); + const files = fs.readdirSync(dir); + + const found = files.find((file) => file.replace(/\.[^.]+$/, '') === base); + + if (found) return path.join(dir, found); + } + } + + return null; +} + +/** @param {string} file */ +export function read(file) { + return fs.readFileSync(file, 'utf-8'); +} diff --git a/node_modules/@sveltejs/kit/src/utils/fork.js b/node_modules/@sveltejs/kit/src/utils/fork.js new file mode 100644 index 0000000..cbf24ac --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/fork.js @@ -0,0 +1,71 @@ +import { fileURLToPath } from 'node:url'; +import { Worker, parentPort } from 'node:worker_threads'; + +/** + * Runs a task in a subprocess so any dangling stuff gets killed upon completion. + * The subprocess needs to be the file `forked` is called in, and `forked` needs to be called eagerly at the top level. + * @template T + * @template U + * @param {string} module `import.meta.url` of the file + * @param {(opts: T) => U} callback The function that is invoked in the subprocess + * @returns {(opts: T) => Promise} A function that when called starts the subprocess + */ +export function forked(module, callback) { + if (process.env.SVELTEKIT_FORK && parentPort) { + parentPort.on( + 'message', + /** @param {any} data */ async (data) => { + if (data?.type === 'args' && data.module === module) { + parentPort?.postMessage({ + type: 'result', + module, + payload: await callback(data.payload) + }); + } + } + ); + + parentPort.postMessage({ type: 'ready', module }); + } + + /** + * @param {T} opts + * @returns {Promise} + */ + const fn = function (opts) { + return new Promise((fulfil, reject) => { + const worker = new Worker(fileURLToPath(module), { + env: { + ...process.env, + SVELTEKIT_FORK: 'true' + } + }); + + worker.on( + 'message', + /** @param {any} data */ (data) => { + if (data?.type === 'ready' && data.module === module) { + worker.postMessage({ + type: 'args', + module, + payload: opts + }); + } + + if (data?.type === 'result' && data.module === module) { + worker.terminate(); + fulfil(data.payload); + } + } + ); + + worker.on('exit', (code) => { + if (code) { + reject(new Error(`Failed with code ${code}`)); + } + }); + }); + }; + + return fn; +} diff --git a/node_modules/@sveltejs/kit/src/utils/functions.js b/node_modules/@sveltejs/kit/src/utils/functions.js new file mode 100644 index 0000000..0629107 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/functions.js @@ -0,0 +1,16 @@ +/** + * @template T + * @param {() => T} fn + */ +export function once(fn) { + let done = false; + + /** @type T */ + let result; + + return () => { + if (done) return result; + done = true; + return (result = fn()); + }; +} diff --git a/node_modules/@sveltejs/kit/src/utils/http.js b/node_modules/@sveltejs/kit/src/utils/http.js new file mode 100644 index 0000000..7399934 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/http.js @@ -0,0 +1,79 @@ +/** + * Given an Accept header and a list of possible content types, pick + * the most suitable one to respond with + * @param {string} accept + * @param {string[]} types + */ +export function negotiate(accept, types) { + /** @type {Array<{ type: string, subtype: string, q: number, i: number }>} */ + const parts = []; + + accept.split(',').forEach((str, i) => { + const match = /([^/]+)\/([^;]+)(?:;q=([0-9.]+))?/.exec(str); + + // no match equals invalid header — ignore + if (match) { + const [, type, subtype, q = '1'] = match; + parts.push({ type, subtype, q: +q, i }); + } + }); + + parts.sort((a, b) => { + if (a.q !== b.q) { + return b.q - a.q; + } + + if ((a.subtype === '*') !== (b.subtype === '*')) { + return a.subtype === '*' ? 1 : -1; + } + + if ((a.type === '*') !== (b.type === '*')) { + return a.type === '*' ? 1 : -1; + } + + return a.i - b.i; + }); + + let accepted; + let min_priority = Infinity; + + for (const mimetype of types) { + const [type, subtype] = mimetype.split('/'); + const priority = parts.findIndex( + (part) => + (part.type === type || part.type === '*') && + (part.subtype === subtype || part.subtype === '*') + ); + + if (priority !== -1 && priority < min_priority) { + accepted = mimetype; + min_priority = priority; + } + } + + return accepted; +} + +/** + * Returns `true` if the request contains a `content-type` header with the given type + * @param {Request} request + * @param {...string} types + */ +function is_content_type(request, ...types) { + const type = request.headers.get('content-type')?.split(';', 1)[0].trim() ?? ''; + return types.includes(type.toLowerCase()); +} + +/** + * @param {Request} request + */ +export function is_form_content_type(request) { + // These content types must be protected against CSRF + // https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/enctype + return is_content_type( + request, + 'application/x-www-form-urlencoded', + 'multipart/form-data', + 'text/plain' + ); +} diff --git a/node_modules/@sveltejs/kit/src/utils/misc.js b/node_modules/@sveltejs/kit/src/utils/misc.js new file mode 100644 index 0000000..cd64ed2 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/misc.js @@ -0,0 +1 @@ +export const s = JSON.stringify; diff --git a/node_modules/@sveltejs/kit/src/utils/options.js b/node_modules/@sveltejs/kit/src/utils/options.js new file mode 100644 index 0000000..46a3253 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/options.js @@ -0,0 +1,16 @@ +/** + * @template {'prerender' | 'ssr' | 'csr' | 'trailingSlash' | 'entries'} Option + * @template {(import('types').SSRNode['universal'] | import('types').SSRNode['server'])[Option]} Value + * + * @param {Array} nodes + * @param {Option} option + * + * @returns {Value | undefined} + */ +export function get_option(nodes, option) { + return nodes.reduce((value, node) => { + return /** @type {Value} TypeScript's too dumb to understand this */ ( + node?.universal?.[option] ?? node?.server?.[option] ?? value + ); + }, /** @type {Value | undefined} */ (undefined)); +} diff --git a/node_modules/@sveltejs/kit/src/utils/platform.js b/node_modules/@sveltejs/kit/src/utils/platform.js new file mode 100644 index 0000000..e32dd5f --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/platform.js @@ -0,0 +1 @@ +export const should_polyfill = typeof Deno === 'undefined' && typeof Bun === 'undefined'; diff --git a/node_modules/@sveltejs/kit/src/utils/promises.js b/node_modules/@sveltejs/kit/src/utils/promises.js new file mode 100644 index 0000000..ac2b53a --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/promises.js @@ -0,0 +1,17 @@ +/** + * Given an object, return a new object where all top level values are awaited + * + * @param {Record} object + * @returns {Promise>} + */ +export async function unwrap_promises(object) { + for (const key in object) { + if (typeof object[key]?.then === 'function') { + return Object.fromEntries( + await Promise.all(Object.entries(object).map(async ([key, value]) => [key, await value])) + ); + } + } + + return object; +} diff --git a/node_modules/@sveltejs/kit/src/utils/routing.js b/node_modules/@sveltejs/kit/src/utils/routing.js new file mode 100644 index 0000000..e6c90f3 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/routing.js @@ -0,0 +1,206 @@ +const param_pattern = /^(\[)?(\.\.\.)?(\w+)(?:=(\w+))?(\])?$/; + +/** + * Creates the regex pattern, extracts parameter names, and generates types for a route + * @param {string} id + */ +export function parse_route_id(id) { + /** @type {import('types').RouteParam[]} */ + const params = []; + + const pattern = + id === '/' + ? /^\/$/ + : new RegExp( + `^${get_route_segments(id) + .map((segment) => { + // special case — /[...rest]/ could contain zero segments + const rest_match = /^\[\.\.\.(\w+)(?:=(\w+))?\]$/.exec(segment); + if (rest_match) { + params.push({ + name: rest_match[1], + matcher: rest_match[2], + optional: false, + rest: true, + chained: true + }); + return '(?:/(.*))?'; + } + // special case — /[[optional]]/ could contain zero segments + const optional_match = /^\[\[(\w+)(?:=(\w+))?\]\]$/.exec(segment); + if (optional_match) { + params.push({ + name: optional_match[1], + matcher: optional_match[2], + optional: true, + rest: false, + chained: true + }); + return '(?:/([^/]+))?'; + } + + if (!segment) { + return; + } + + const parts = segment.split(/\[(.+?)\](?!\])/); + const result = parts + .map((content, i) => { + if (i % 2) { + if (content.startsWith('x+')) { + return escape(String.fromCharCode(parseInt(content.slice(2), 16))); + } + + if (content.startsWith('u+')) { + return escape( + String.fromCharCode( + ...content + .slice(2) + .split('-') + .map((code) => parseInt(code, 16)) + ) + ); + } + + const match = param_pattern.exec(content); + if (!match) { + throw new Error( + `Invalid param: ${content}. Params and matcher names can only have underscores and alphanumeric characters.` + ); + } + + const [, is_optional, is_rest, name, matcher] = match; + // It's assumed that the following invalid route id cases are already checked + // - unbalanced brackets + // - optional param following rest param + + params.push({ + name, + matcher, + optional: !!is_optional, + rest: !!is_rest, + chained: is_rest ? i === 1 && parts[0] === '' : false + }); + return is_rest ? '(.*?)' : is_optional ? '([^/]*)?' : '([^/]+?)'; + } + + return escape(content); + }) + .join(''); + + return '/' + result; + }) + .join('')}/?$` + ); + + return { pattern, params }; +} + +const optional_param_regex = /\/\[\[\w+?(?:=\w+)?\]\]/; + +/** + * Removes optional params from a route ID. + * @param {string} id + * @returns The route id with optional params removed + */ +export function remove_optional_params(id) { + return id.replace(optional_param_regex, ''); +} + +/** + * Returns `false` for `(group)` segments + * @param {string} segment + */ +function affects_path(segment) { + return !/^\([^)]+\)$/.test(segment); +} + +/** + * Splits a route id into its segments, removing segments that + * don't affect the path (i.e. groups). The root route is represented by `/` + * and will be returned as `['']`. + * @param {string} route + * @returns string[] + */ +export function get_route_segments(route) { + return route.slice(1).split('/').filter(affects_path); +} + +/** + * @param {RegExpMatchArray} match + * @param {import('types').RouteParam[]} params + * @param {Record} matchers + */ +export function exec(match, params, matchers) { + /** @type {Record} */ + const result = {}; + + const values = match.slice(1); + + let buffered = 0; + + for (let i = 0; i < params.length; i += 1) { + const param = params[i]; + let value = values[i - buffered]; + + // in the `[[a=b]]/.../[...rest]` case, if one or more optional parameters + // weren't matched, roll the skipped values into the rest + if (param.chained && param.rest && buffered) { + value = values + .slice(i - buffered, i + 1) + .filter((s) => s) + .join('/'); + + buffered = 0; + } + + // if `value` is undefined, it means this is an optional or rest parameter + if (value === undefined) { + if (param.rest) result[param.name] = ''; + continue; + } + + if (!param.matcher || matchers[param.matcher](value)) { + result[param.name] = value; + + // Now that the params match, reset the buffer if the next param isn't the [...rest] + // and the next value is defined, otherwise the buffer will cause us to skip values + const next_param = params[i + 1]; + const next_value = values[i + 1]; + if (next_param && !next_param.rest && next_param.optional && next_value && param.chained) { + buffered = 0; + } + continue; + } + + // in the `/[[a=b]]/...` case, if the value didn't satisfy the matcher, + // keep track of the number of skipped optional parameters and continue + if (param.optional && param.chained) { + buffered++; + continue; + } + + // otherwise, if the matcher returns `false`, the route did not match + return; + } + + if (buffered) return; + return result; +} + +/** @param {string} str */ +function escape(str) { + return ( + str + .normalize() + // escape [ and ] before escaping other characters, since they are used in the replacements + .replace(/[[\]]/g, '\\$&') + // replace %, /, ? and # with their encoded versions because decode_pathname leaves them untouched + .replace(/%/g, '%25') + .replace(/\//g, '%2[Ff]') + .replace(/\?/g, '%3[Ff]') + .replace(/#/g, '%23') + // escape characters that have special meaning in regex + .replace(/[.*+?^${}()|\\]/g, '\\$&') + ); +} diff --git a/node_modules/@sveltejs/kit/src/utils/streaming.js b/node_modules/@sveltejs/kit/src/utils/streaming.js new file mode 100644 index 0000000..cfb0d6a --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/streaming.js @@ -0,0 +1,51 @@ +/** + * @returns {import('types').Deferred & { promise: Promise }}} + */ +function defer() { + let fulfil; + let reject; + + const promise = new Promise((f, r) => { + fulfil = f; + reject = r; + }); + + // @ts-expect-error + return { promise, fulfil, reject }; +} + +/** + * Create an async iterator and a function to push values into it + * @returns {{ + * iterator: AsyncIterable; + * push: (value: any) => void; + * done: () => void; + * }} + */ +export function create_async_iterator() { + const deferred = [defer()]; + + return { + iterator: { + [Symbol.asyncIterator]() { + return { + next: async () => { + const next = await deferred[0].promise; + if (!next.done) deferred.shift(); + return next; + } + }; + } + }, + push: (value) => { + deferred[deferred.length - 1].fulfil({ + value, + done: false + }); + deferred.push(defer()); + }, + done: () => { + deferred[deferred.length - 1].fulfil({ done: true }); + } + }; +} diff --git a/node_modules/@sveltejs/kit/src/utils/url.js b/node_modules/@sveltejs/kit/src/utils/url.js new file mode 100644 index 0000000..2eb7f99 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/utils/url.js @@ -0,0 +1,180 @@ +import { BROWSER } from 'esm-env'; + +const absolute = /^([a-z]+:)?\/?\//; +const scheme = /^[a-z]+:/; + +/** + * @param {string} base + * @param {string} path + */ +export function resolve(base, path) { + if (scheme.test(path)) return path; + if (path[0] === '#') return base + path; + + const base_match = absolute.exec(base); + const path_match = absolute.exec(path); + + if (!base_match) { + throw new Error(`bad base path: "${base}"`); + } + + const baseparts = path_match ? [] : base.slice(base_match[0].length).split('/'); + const pathparts = path_match ? path.slice(path_match[0].length).split('/') : path.split('/'); + + baseparts.pop(); + + for (let i = 0; i < pathparts.length; i += 1) { + const part = pathparts[i]; + if (part === '.') continue; + else if (part === '..') baseparts.pop(); + else baseparts.push(part); + } + + const prefix = (path_match && path_match[0]) || (base_match && base_match[0]) || ''; + + return `${prefix}${baseparts.join('/')}`; +} + +/** @param {string} path */ +export function is_root_relative(path) { + return path[0] === '/' && path[1] !== '/'; +} + +/** + * @param {string} path + * @param {import('types').TrailingSlash} trailing_slash + */ +export function normalize_path(path, trailing_slash) { + if (path === '/' || trailing_slash === 'ignore') return path; + + if (trailing_slash === 'never') { + return path.endsWith('/') ? path.slice(0, -1) : path; + } else if (trailing_slash === 'always' && !path.endsWith('/')) { + return path + '/'; + } + + return path; +} + +/** + * Decode pathname excluding %25 to prevent further double decoding of params + * @param {string} pathname + */ +export function decode_pathname(pathname) { + return pathname.split('%25').map(decodeURI).join('%25'); +} + +/** @param {Record} params */ +export function decode_params(params) { + for (const key in params) { + // input has already been decoded by decodeURI + // now handle the rest + params[key] = decodeURIComponent(params[key]); + } + + return params; +} + +/** + * The error when a URL is malformed is not very helpful, so we augment it with the URI + * @param {string} uri + */ +export function decode_uri(uri) { + try { + return decodeURI(uri); + } catch (e) { + if (e instanceof Error) { + e.message = `Failed to decode URI: ${uri}\n` + e.message; + } + throw e; + } +} + +/** + * URL properties that could change during the lifetime of the page, + * which excludes things like `origin` + */ +const tracked_url_properties = /** @type {const} */ ([ + 'href', + 'pathname', + 'search', + 'searchParams', + 'toString', + 'toJSON' +]); + +/** + * @param {URL} url + * @param {() => void} callback + */ +export function make_trackable(url, callback) { + const tracked = new URL(url); + + for (const property of tracked_url_properties) { + Object.defineProperty(tracked, property, { + get() { + callback(); + return url[property]; + }, + + enumerable: true, + configurable: true + }); + } + + if (!BROWSER) { + // @ts-ignore + tracked[Symbol.for('nodejs.util.inspect.custom')] = (depth, opts, inspect) => { + return inspect(url, opts); + }; + } + + disable_hash(tracked); + + return tracked; +} + +/** + * Disallow access to `url.hash` on the server and in `load` + * @param {URL} url + */ +export function disable_hash(url) { + Object.defineProperty(url, 'hash', { + get() { + throw new Error( + 'Cannot access event.url.hash. Consider using `$page.url.hash` inside a component instead' + ); + } + }); +} + +/** + * Disallow access to `url.search` and `url.searchParams` during prerendering + * @param {URL} url + */ +export function disable_search(url) { + for (const property of ['search', 'searchParams']) { + Object.defineProperty(url, property, { + get() { + throw new Error(`Cannot access url.${property} on a page with prerendering enabled`); + } + }); + } +} + +const DATA_SUFFIX = '/__data.json'; + +/** @param {string} pathname */ +export function has_data_suffix(pathname) { + return pathname.endsWith(DATA_SUFFIX); +} + +/** @param {string} pathname */ +export function add_data_suffix(pathname) { + return pathname.replace(/\/$/, '') + DATA_SUFFIX; +} + +/** @param {string} pathname */ +export function strip_data_suffix(pathname) { + return pathname.slice(0, -DATA_SUFFIX.length); +} diff --git a/node_modules/@sveltejs/kit/src/version.js b/node_modules/@sveltejs/kit/src/version.js new file mode 100644 index 0000000..b0cb0b6 --- /dev/null +++ b/node_modules/@sveltejs/kit/src/version.js @@ -0,0 +1,4 @@ +// generated during release, do not modify + +/** @type {string} */ +export const VERSION = '1.22.4'; diff --git a/node_modules/@sveltejs/kit/svelte-kit.js b/node_modules/@sveltejs/kit/svelte-kit.js new file mode 100644 index 0000000..b48389f --- /dev/null +++ b/node_modules/@sveltejs/kit/svelte-kit.js @@ -0,0 +1,2 @@ +#!/usr/bin/env node +import './src/cli.js'; diff --git a/node_modules/@sveltejs/kit/types/index.d.ts b/node_modules/@sveltejs/kit/types/index.d.ts new file mode 100644 index 0000000..56fc2d4 --- /dev/null +++ b/node_modules/@sveltejs/kit/types/index.d.ts @@ -0,0 +1,2107 @@ +/// +/// + +declare module '@sveltejs/kit' { + import type { CompileOptions } from 'svelte/types/compiler/interfaces'; + import type { PluginOptions } from '@sveltejs/vite-plugin-svelte'; + /** + * [Adapters](https://kit.svelte.dev/docs/adapters) are responsible for taking the production build and turning it into something that can be deployed to a platform of your choosing. + */ + export interface Adapter { + /** + * The name of the adapter, using for logging. Will typically correspond to the package name. + */ + name: string; + /** + * This function is called after SvelteKit has built your app. + * @param builder An object provided by SvelteKit that contains methods for adapting the app + */ + adapt(builder: Builder): MaybePromise; + } + + type AwaitedPropertiesUnion | void> = input extends void + ? undefined // needs to be undefined, because void will break intellisense + : input extends Record + ? { + [key in keyof input]: Awaited; + } + : {} extends input // handles the any case + ? input + : unknown; + + export type AwaitedProperties | void> = + AwaitedPropertiesUnion extends Record + ? OptionalUnion> + : AwaitedPropertiesUnion; + + export type AwaitedActions any>> = OptionalUnion< + { + [Key in keyof T]: UnpackValidationError>>; + }[keyof T] + >; + + // Takes a union type and returns a union type where each type also has all properties + // of all possible types (typed as undefined), making accessing them more ergonomic + type OptionalUnion< + U extends Record, // not unknown, else interfaces don't satisfy this constraint + A extends keyof U = U extends U ? keyof U : never + > = U extends unknown ? { [P in Exclude]?: never } & U : never; + + type UnpackValidationError = T extends ActionFailure + ? X + : T extends void + ? undefined // needs to be undefined, because void will corrupt union type + : T; + + /** + * This object is passed to the `adapt` function of adapters. + * It contains various methods and properties that are useful for adapting the app. + */ + export interface Builder { + /** Print messages to the console. `log.info` and `log.minor` are silent unless Vite's `logLevel` is `info`. */ + log: Logger; + /** Remove `dir` and all its contents. */ + rimraf(dir: string): void; + /** Create `dir` and any required parent directories. */ + mkdirp(dir: string): void; + + /** The fully resolved `svelte.config.js`. */ + config: ValidatedConfig; + /** Information about prerendered pages and assets, if any. */ + prerendered: Prerendered; + /** An array of all routes (including prerendered) */ + routes: RouteDefinition[]; + + /** + * Create separate functions that map to one or more routes of your app. + * @param fn A function that groups a set of routes into an entry point + * @deprecated Use `builder.routes` instead + */ + createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise; + + /** + * Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps. + */ + generateFallback(dest: string): Promise; + + /** + * Generate a server-side manifest to initialise the SvelteKit [server](https://kit.svelte.dev/docs/types#public-types-server) with. + * @param opts a relative path to the base directory of the app and optionally in which format (esm or cjs) the manifest should be generated + */ + generateManifest(opts: { relativePath: string; routes?: RouteDefinition[] }): string; + + /** + * Resolve a path to the `name` directory inside `outDir`, e.g. `/path/to/.svelte-kit/my-adapter`. + * @param name path to the file, relative to the build directory + */ + getBuildDirectory(name: string): string; + /** Get the fully resolved path to the directory containing client-side assets, including the contents of your `static` directory. */ + getClientDirectory(): string; + /** Get the fully resolved path to the directory containing server-side code. */ + getServerDirectory(): string; + /** Get the application path including any configured `base` path, e.g. `/my-base-path/_app`. */ + getAppPath(): string; + + /** + * Write client assets to `dest`. + * @param dest the destination folder + * @returns an array of files written to `dest` + */ + writeClient(dest: string): string[]; + /** + * Write prerendered files to `dest`. + * @param dest the destination folder + * @returns an array of files written to `dest` + */ + writePrerendered(dest: string): string[]; + /** + * Write server-side code to `dest`. + * @param dest the destination folder + * @returns an array of files written to `dest` + */ + writeServer(dest: string): string[]; + /** + * Copy a file or directory. + * @param from the source file or directory + * @param to the destination file or directory + * @param opts.filter a function to determine whether a file or directory should be copied + * @param opts.replace a map of strings to replace + * @returns an array of files that were copied + */ + copy( + from: string, + to: string, + opts?: { + filter?(basename: string): boolean; + replace?: Record; + } + ): string[]; + + /** + * Compress files in `directory` with gzip and brotli, where appropriate. Generates `.gz` and `.br` files alongside the originals. + * @param directory The directory containing the files to be compressed + */ + compress(directory: string): Promise; + } + + export interface Config { + /** + * Options passed to [`svelte.compile`](https://svelte.dev/docs#compile-time-svelte-compile). + * @default {} + */ + compilerOptions?: CompileOptions; + /** + * List of file extensions that should be treated as Svelte files. + * @default [".svelte"] + */ + extensions?: string[]; + /** SvelteKit options */ + kit?: KitConfig; + /** [`@sveltejs/package`](/docs/packaging) options. */ + package?: { + source?: string; + dir?: string; + emitTypes?: boolean; + exports?(filepath: string): boolean; + files?(filepath: string): boolean; + }; + /** Preprocessor options, if any. Preprocessing can alternatively also be done through Vite's preprocessor capabilities. */ + preprocess?: any; + /** `vite-plugin-svelte` plugin options. */ + vitePlugin?: PluginOptions; + /** Any additional options required by tooling that integrates with Svelte. */ + [key: string]: any; + } + + export interface Cookies { + /** + * Gets a cookie that was previously set with `cookies.set`, or from the request headers. + * @param name the name of the cookie + * @param opts the options, passed directly to `cookie.parse`. See documentation [here](https://github.com/jshttp/cookie#cookieparsestr-options) + */ + get(name: string, opts?: import('cookie').CookieParseOptions): string | undefined; + + /** + * Gets all cookies that were previously set with `cookies.set`, or from the request headers. + * @param opts the options, passed directily to `cookie.parse`. See documentation [here](https://github.com/jshttp/cookie#cookieparsestr-options) + */ + getAll(opts?: import('cookie').CookieParseOptions): Array<{ name: string; value: string }>; + + /** + * Sets a cookie. This will add a `set-cookie` header to the response, but also make the cookie available via `cookies.get` or `cookies.getAll` during the current request. + * + * The `httpOnly` and `secure` options are `true` by default (except on http://localhost, where `secure` is `false`), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The `sameSite` option defaults to `lax`. + * + * By default, the `path` of a cookie is the 'directory' of the current pathname. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. + * @param name the name of the cookie + * @param value the cookie value + * @param opts the options, passed directory to `cookie.serialize`. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) + */ + set(name: string, value: string, opts?: import('cookie').CookieSerializeOptions): void; + + /** + * Deletes a cookie by setting its value to an empty string and setting the expiry date in the past. + * + * By default, the `path` of a cookie is the 'directory' of the current pathname. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. + * @param name the name of the cookie + * @param opts the options, passed directory to `cookie.serialize`. The `path` must match the path of the cookie you want to delete. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) + */ + delete(name: string, opts?: import('cookie').CookieSerializeOptions): void; + + /** + * Serialize a cookie name-value pair into a `Set-Cookie` header string, but don't apply it to the response. + * + * The `httpOnly` and `secure` options are `true` by default (except on http://localhost, where `secure` is `false`), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The `sameSite` option defaults to `lax`. + * + * By default, the `path` of a cookie is the current pathname. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. + * + * @param name the name of the cookie + * @param value the cookie value + * @param opts the options, passed directory to `cookie.serialize`. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) + */ + serialize(name: string, value: string, opts?: import('cookie').CookieSerializeOptions): string; + } + + export interface KitConfig { + /** + * Your [adapter](https://kit.svelte.dev/docs/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms. + * @default undefined + */ + adapter?: Adapter; + /** + * An object containing zero or more aliases used to replace values in `import` statements. These aliases are automatically passed to Vite and TypeScript. + * + * ```js + * /// file: svelte.config.js + * /// type: import('@sveltejs/kit').Config + * const config = { + * kit: { + * alias: { + * // this will match a file + * 'my-file': 'path/to/my-file.js', + * + * // this will match a directory and its contents + * // (`my-directory/x` resolves to `path/to/my-directory/x`) + * 'my-directory': 'path/to/my-directory', + * + * // an alias ending /* will only match + * // the contents of a directory, not the directory itself + * 'my-directory/*': 'path/to/my-directory/*' + * } + * } + * }; + * ``` + * + * > The built-in `$lib` alias is controlled by `config.kit.files.lib` as it is used for packaging. + * + * > You will need to run `npm run dev` to have SvelteKit automatically generate the required alias configuration in `jsconfig.json` or `tsconfig.json`. + * @default {} + */ + alias?: Record; + /** + * The directory relative to `paths.assets` where the built JS and CSS (and imported assets) are served from. (The filenames therein contain content-based hashes, meaning they can be cached indefinitely). Must not start or end with `/`. + * @default "_app" + */ + appDir?: string; + /** + * [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) configuration. CSP helps to protect your users against cross-site scripting (XSS) attacks, by limiting the places resources can be loaded from. For example, a configuration like this... + * + * ```js + * /// file: svelte.config.js + * /// type: import('@sveltejs/kit').Config + * const config = { + * kit: { + * csp: { + * directives: { + * 'script-src': ['self'] + * }, + * reportOnly: { + * 'script-src': ['self'] + * } + * } + * } + * }; + * + * export default config; + * ``` + * + * ...would prevent scripts loading from external sites. SvelteKit will augment the specified directives with nonces or hashes (depending on `mode`) for any inline styles and scripts it generates. + * + * To add a nonce for scripts and links manually included in `src/app.html`, you may use the placeholder `%sveltekit.nonce%` (for example ` + * ``` + * + * If you set `pollInterval` to a non-zero value, SvelteKit will poll for new versions in the background and set the value of the [`updated`](/docs/modules#$app-stores-updated) store to `true` when it detects one. + */ + version?: { + /** + * The current app version string. If specified, this must be deterministic (e.g. a commit ref rather than `Math.random()` or `Date.now().toString()`), otherwise defaults to a timestamp of the build. + * + * For example, to use the current commit hash, you could do use `git rev-parse HEAD`: + * + * ```js + * /// file: svelte.config.js + * import * as child_process from 'node:child_process'; + * + * export default { + * kit: { + * version: { + * name: child_process.execSync('git rev-parse HEAD').toString().trim() + * } + * } + * }; + * ``` + */ + name?: string; + /** + * The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs. + * @default 0 + */ + pollInterval?: number; + }; + } + + /** + * The [`handle`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) hook runs every time the SvelteKit server receives a [request](https://kit.svelte.dev/docs/web-standards#fetch-apis-request) and + * determines the [response](https://kit.svelte.dev/docs/web-standards#fetch-apis-response). + * It receives an `event` object representing the request and a function called `resolve`, which renders the route and generates a `Response`. + * This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example). + */ + export type Handle = (input: { + event: RequestEvent; + resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise; + }) => MaybePromise; + + /** + * The server-side [`handleError`](https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror) hook runs when an unexpected error is thrown while responding to a request. + * + * If an unexpected error is thrown during loading or rendering, this function will be called with the error and the event. + * Make sure that this function _never_ throws an error. + */ + export type HandleServerError = (input: { + error: unknown; + event: RequestEvent; + }) => MaybePromise; + + /** + * The client-side [`handleError`](https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror) hook runs when an unexpected error is thrown while navigating. + * + * If an unexpected error is thrown during loading or the following render, this function will be called with the error and the event. + * Make sure that this function _never_ throws an error. + */ + export type HandleClientError = (input: { + error: unknown; + event: NavigationEvent; + }) => MaybePromise; + + /** + * The [`handleFetch`](https://kit.svelte.dev/docs/hooks#server-hooks-handlefetch) hook allows you to modify (or replace) a `fetch` request that happens inside a `load` function that runs on the server (or during pre-rendering) + */ + export type HandleFetch = (input: { + event: RequestEvent; + request: Request; + fetch: typeof fetch; + }) => MaybePromise; + + /** + * The generic form of `PageLoad` and `LayoutLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) + * rather than using `Load` directly. + */ + export type Load< + Params extends Partial> = Partial>, + InputData extends Record | null = Record | null, + ParentData extends Record = Record, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null + > = (event: LoadEvent) => MaybePromise; + + /** + * The generic form of `PageLoadEvent` and `LayoutLoadEvent`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) + * rather than using `LoadEvent` directly. + */ + export interface LoadEvent< + Params extends Partial> = Partial>, + Data extends Record | null = Record | null, + ParentData extends Record = Record, + RouteId extends string | null = string | null + > extends NavigationEvent { + /** + * `fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features: + * + * - It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request. + * - It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context). + * - Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call. + * - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) + * - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request. + * + * You can learn more about making credentialed requests with cookies [here](https://kit.svelte.dev/docs/load#cookies) + */ + fetch: typeof fetch; + /** + * Contains the data returned by the route's server `load` function (in `+layout.server.js` or `+page.server.js`), if any. + */ + data: Data; + /** + * If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: + * + * ```js + * /// file: src/routes/blog/+page.js + * export async function load({ fetch, setHeaders }) { + * const url = `https://cms.example.com/articles.json`; + * const response = await fetch(url); + * + * setHeaders({ + * age: response.headers.get('age'), + * 'cache-control': response.headers.get('cache-control') + * }); + * + * return response.json(); + * } + * ``` + * + * Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once. + * + * You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](https://kit.svelte.dev/docs/types#public-types-cookies) API in a server-only `load` function instead. + * + * `setHeaders` has no effect when a `load` function runs in the browser. + */ + setHeaders(headers: Record): void; + /** + * `await parent()` returns data from parent `+layout.js` `load` functions. + * Implicitly, a missing `+layout.js` is treated as a `({ data }) => data` function, meaning that it will return and forward data from parent `+layout.server.js` files. + * + * Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data. + */ + parent(): Promise; + /** + * This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/modules#$app-navigation-invalidate) to cause `load` to rerun. + * + * Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`. + * + * URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). + * + * Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html). + * + * The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun. + * + * ```js + * /// file: src/routes/+page.js + * let count = 0; + * export async function load({ depends }) { + * depends('increase:count'); + * + * return { count: count++ }; + * } + * ``` + * + * ```html + * /// file: src/routes/+page.svelte + * + * + *

{data.count}

+ * + * ``` + */ + depends(...deps: string[]): void; + } + + export interface NavigationEvent< + Params extends Partial> = Partial>, + RouteId extends string | null = string | null + > { + /** + * The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + */ + params: Params; + /** + * Info about the current route + */ + route: { + /** + * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + */ + id: RouteId; + }; + /** + * The URL of the current page + */ + url: URL; + } + + /** + * Information about the target of a specific navigation. + */ + export interface NavigationTarget { + /** + * Parameters of the target page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object. + * Is `null` if the target is not part of the SvelteKit app (could not be resolved to a route). + */ + params: Record | null; + /** + * Info about the target route + */ + route: { id: string | null }; + /** + * The URL that is navigated to + */ + url: URL; + } + + /** + * - `enter`: The app has hydrated + * - `form`: The user submitted a `` with a GET method + * - `leave`: The user is leaving the app by closing the tab or using the back/forward buttons to go to a different document + * - `link`: Navigation was triggered by a link click + * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect + * - `popstate`: Navigation was triggered by back/forward navigation + */ + export type NavigationType = 'enter' | 'form' | 'leave' | 'link' | 'goto' | 'popstate'; + + export interface Navigation { + /** + * Where navigation was triggered from + */ + from: NavigationTarget | null; + /** + * Where navigation is going to/has gone to + */ + to: NavigationTarget | null; + /** + * The type of navigation: + * - `form`: The user submitted a `` + * - `leave`: The user is leaving the app by closing the tab or using the back/forward buttons to go to a different document + * - `link`: Navigation was triggered by a link click + * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect + * - `popstate`: Navigation was triggered by back/forward navigation + */ + type: Omit; + /** + * Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation) + */ + willUnload: boolean; + /** + * In case of a history back/forward navigation, the number of steps to go back/forward + */ + delta?: number; + } + + /** + * The argument passed to [`beforeNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-beforenavigate) callbacks. + */ + export interface BeforeNavigate extends Navigation { + /** + * Call this to prevent the navigation from starting. + */ + cancel(): void; + } + + /** + * The argument passed to [`afterNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-afternavigate) callbacks. + */ + export interface AfterNavigate extends Navigation { + /** + * The type of navigation: + * - `enter`: The app has hydrated + * - `form`: The user submitted a `` + * - `link`: Navigation was triggered by a link click + * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect + * - `popstate`: Navigation was triggered by back/forward navigation + */ + type: Omit; + /** + * Since `afterNavigate` is called after a navigation completes, it will never be called with a navigation that unloads the page. + */ + willUnload: false; + } + + /** + * The shape of the `$page` store + */ + export interface Page< + Params extends Record = Record, + RouteId extends string | null = string | null + > { + /** + * The URL of the current page + */ + url: URL; + /** + * The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + */ + params: Params; + /** + * Info about the current route + */ + route: { + /** + * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + */ + id: RouteId; + }; + /** + * Http status code of the current page + */ + status: number; + /** + * The error object of the current page, if any. Filled from the `handleError` hooks. + */ + error: App.Error | null; + /** + * The merged result of all data from all `load` functions on the current page. You can type a common denominator through `App.PageData`. + */ + data: App.PageData & Record; + /** + * Filled only after a form submission. See [form actions](https://kit.svelte.dev/docs/form-actions) for more info. + */ + form: any; + } + + /** + * The shape of a param matcher. See [matching](https://kit.svelte.dev/docs/advanced-routing#matching) for more info. + */ + export type ParamMatcher = (param: string) => boolean; + + export interface RequestEvent< + Params extends Partial> = Partial>, + RouteId extends string | null = string | null + > { + /** + * Get or set cookies related to the current request + */ + cookies: Cookies; + /** + * `fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features: + * + * - It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request. + * - It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context). + * - Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call. + * - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) + * - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request. + * + * You can learn more about making credentialed requests with cookies [here](https://kit.svelte.dev/docs/load#cookies) + */ + fetch: typeof fetch; + /** + * The client's IP address, set by the adapter. + */ + getClientAddress(): string; + /** + * Contains custom data that was added to the request within the [`handle hook`](https://kit.svelte.dev/docs/hooks#server-hooks-handle). + */ + locals: App.Locals; + /** + * The parameters of the current route - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + */ + params: Params; + /** + * Additional data made available through the adapter. + */ + platform: Readonly | undefined; + /** + * The original request object + */ + request: Request; + /** + * Info about the current route + */ + route: { + /** + * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + */ + id: RouteId; + }; + /** + * If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: + * + * ```js + * /// file: src/routes/blog/+page.js + * export async function load({ fetch, setHeaders }) { + * const url = `https://cms.example.com/articles.json`; + * const response = await fetch(url); + * + * setHeaders({ + * age: response.headers.get('age'), + * 'cache-control': response.headers.get('cache-control') + * }); + * + * return response.json(); + * } + * ``` + * + * Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once. + * + * You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](https://kit.svelte.dev/docs/types#public-types-cookies) API instead. + */ + setHeaders(headers: Record): void; + /** + * The requested URL. + */ + url: URL; + /** + * `true` if the request comes from the client asking for `+page/layout.server.js` data. The `url` property will be stripped of the internal information + * related to the data request in this case. Use this property instead if the distinction is important to you. + */ + isDataRequest: boolean; + /** + * `true` for `+server.js` calls coming from SvelteKit without the overhead of actually making an HTTP request. This happens when you make same-origin `fetch` requests on the server. + */ + isSubRequest: boolean; + } + + /** + * A `(event: RequestEvent) => Response` function exported from a `+server.js` file that corresponds to an HTTP verb (`GET`, `PUT`, `PATCH`, etc) and handles requests with that method. + * + * It receives `Params` as the first generic argument, which you can skip by using [generated types](https://kit.svelte.dev/docs/types#generated-types) instead. + */ + export type RequestHandler< + Params extends Partial> = Partial>, + RouteId extends string | null = string | null + > = (event: RequestEvent) => MaybePromise; + + export interface ResolveOptions { + /** + * Applies custom transforms to HTML. If `done` is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML + * (they could include an element's opening tag but not its closing tag, for example) + * but they will always be split at sensible boundaries such as `%sveltekit.head%` or layout/page components. + * @param input the html chunk and the info if this is the last chunk + */ + transformPageChunk?(input: { html: string; done: boolean }): MaybePromise; + /** + * Determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`. + * By default, none will be included. + * @param name header name + * @param value header value + */ + filterSerializedResponseHeaders?(name: string, value: string): boolean; + /** + * Determines what should be added to the `` tag to preload it. + * By default, `js` and `css` files will be preloaded. + * @param input the type of the file and its path + */ + preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean; + } + + export interface RouteDefinition { + id: string; + api: { + methods: HttpMethod[]; + }; + page: { + methods: Extract[]; + }; + pattern: RegExp; + prerender: PrerenderOption; + segments: RouteSegment[]; + methods: HttpMethod[]; + config: Config; + } + + export class Server { + constructor(manifest: SSRManifest); + init(options: ServerInitOptions): Promise; + respond(request: Request, options: RequestOptions): Promise; + } + + export interface ServerInitOptions { + env: Record; + } + + export interface SSRManifest { + appDir: string; + appPath: string; + assets: Set; + mimeTypes: Record; + + /** private fields */ + _: { + client: NonNullable; + nodes: SSRNodeLoader[]; + routes: SSRRoute[]; + matchers(): Promise>; + }; + } + + /** + * The generic form of `PageServerLoad` and `LayoutServerLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) + * rather than using `ServerLoad` directly. + */ + export type ServerLoad< + Params extends Partial> = Partial>, + ParentData extends Record = Record, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null + > = (event: ServerLoadEvent) => MaybePromise; + + export interface ServerLoadEvent< + Params extends Partial> = Partial>, + ParentData extends Record = Record, + RouteId extends string | null = string | null + > extends RequestEvent { + /** + * `await parent()` returns data from parent `+layout.server.js` `load` functions. + * + * Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data. + */ + parent(): Promise; + /** + * This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/modules#$app-navigation-invalidate) to cause `load` to rerun. + * + * Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`. + * + * URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). + * + * Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html). + * + * The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun. + * + * ```js + * /// file: src/routes/+page.js + * let count = 0; + * export async function load({ depends }) { + * depends('increase:count'); + * + * return { count: count++ }; + * } + * ``` + * + * ```html + * /// file: src/routes/+page.svelte + * + * + *

{data.count}

+ * + * ``` + */ + depends(...deps: string[]): void; + } + + /** + * Shape of a form action method that is part of `export const actions = {..}` in `+page.server.js`. + * See [form actions](https://kit.svelte.dev/docs/form-actions) for more information. + */ + export type Action< + Params extends Partial> = Partial>, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null + > = (event: RequestEvent) => MaybePromise; + + /** + * Shape of the `export const actions = {..}` object in `+page.server.js`. + * See [form actions](https://kit.svelte.dev/docs/form-actions) for more information. + */ + export type Actions< + Params extends Partial> = Partial>, + OutputData extends Record | void = Record | void, + RouteId extends string | null = string | null + > = Record>; + + /** + * When calling a form action via fetch, the response will be one of these shapes. + * ```svelte + * { + * return ({ result }) => { + * // result is of type ActionResult + * }; + * }} + * ``` + */ + export type ActionResult< + Success extends Record | undefined = Record, + Failure extends Record | undefined = Record + > = + | { type: 'success'; status: number; data?: Success } + | { type: 'failure'; status: number; data?: Failure } + | { type: 'redirect'; status: number; location: string } + | { type: 'error'; status?: number; error: any }; + + /** + * The object returned by the [`error`](https://kit.svelte.dev/docs/modules#sveltejs-kit-error) function. + */ + export interface HttpError { + /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses), in the range 400-599. */ + status: number; + /** The content of the error. */ + body: App.Error; + } + + /** + * The object returned by the [`redirect`](https://kit.svelte.dev/docs/modules#sveltejs-kit-redirect) function + */ + export interface Redirect { + /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages), in the range 300-308. */ + status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308; + /** The location to redirect to. */ + location: string; + } + + export type SubmitFunction< + Success extends Record | undefined = Record, + Failure extends Record | undefined = Record + > = (input: { + action: URL; + /** + * use `formData` instead of `data` + * @deprecated + */ + data: FormData; + formData: FormData; + /** + * use `formElement` instead of `form` + * @deprecated + */ + form: HTMLFormElement; + formElement: HTMLFormElement; + controller: AbortController; + submitter: HTMLElement | null; + cancel(): void; + }) => MaybePromise< + | void + | ((opts: { + /** + * use `formData` instead of `data` + * @deprecated + */ + data: FormData; + formData: FormData; + /** + * use `formElement` instead of `form` + * @deprecated + */ + form: HTMLFormElement; + formElement: HTMLFormElement; + action: URL; + result: ActionResult; + /** + * Call this to get the default behavior of a form submission response. + * @param options Set `reset: false` if you don't want the `` values to be reset after a successful submission. + */ + update(options?: { reset: boolean }): Promise; + }) => void) + >; + + /** + * The type of `export const snapshot` exported from a page or layout component. + */ + export interface Snapshot { + capture: () => T; + restore: (snapshot: T) => void; + } + interface AdapterEntry { + /** + * A string that uniquely identifies an HTTP service (e.g. serverless function) and is used for deduplication. + * For example, `/foo/a-[b]` and `/foo/[c]` are different routes, but would both + * be represented in a Netlify _redirects file as `/foo/:param`, so they share an ID + */ + id: string; + + /** + * A function that compares the candidate route with the current route to determine + * if it should be grouped with the current route. + * + * Use cases: + * - Fallback pages: `/foo/[c]` is a fallback for `/foo/a-[b]`, and `/[...catchall]` is a fallback for all routes + * - Grouping routes that share a common `config`: `/foo` should be deployed to the edge, `/bar` and `/baz` should be deployed to a serverless function + */ + filter(route: RouteDefinition): boolean; + + /** + * A function that is invoked once the entry has been created. This is where you + * should write the function to the filesystem and generate redirect manifests. + */ + complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise; + } + + // Based on https://github.com/josh-hemphill/csp-typed-directives/blob/latest/src/csp.types.ts + // + // MIT License + // + // Copyright (c) 2021-present, Joshua Hemphill + // Copyright (c) 2021, Tecnico Corporation + // + // 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. + + namespace Csp { + type ActionSource = 'strict-dynamic' | 'report-sample'; + type BaseSource = + | 'self' + | 'unsafe-eval' + | 'unsafe-hashes' + | 'unsafe-inline' + | 'wasm-unsafe-eval' + | 'none'; + type CryptoSource = `${'nonce' | 'sha256' | 'sha384' | 'sha512'}-${string}`; + type FrameSource = HostSource | SchemeSource | 'self' | 'none'; + type HostNameScheme = `${string}.${string}` | 'localhost'; + type HostSource = `${HostProtocolSchemes}${HostNameScheme}${PortScheme}`; + type HostProtocolSchemes = `${string}://` | ''; + type HttpDelineator = '/' | '?' | '#' | '\\'; + type PortScheme = `:${number}` | '' | ':*'; + type SchemeSource = 'http:' | 'https:' | 'data:' | 'mediastream:' | 'blob:' | 'filesystem:'; + type Source = HostSource | SchemeSource | CryptoSource | BaseSource; + type Sources = Source[]; + type UriPath = `${HttpDelineator}${string}`; + } + + interface CspDirectives { + 'child-src'?: Csp.Sources; + 'default-src'?: Array; + 'frame-src'?: Csp.Sources; + 'worker-src'?: Csp.Sources; + 'connect-src'?: Csp.Sources; + 'font-src'?: Csp.Sources; + 'img-src'?: Csp.Sources; + 'manifest-src'?: Csp.Sources; + 'media-src'?: Csp.Sources; + 'object-src'?: Csp.Sources; + 'prefetch-src'?: Csp.Sources; + 'script-src'?: Array; + 'script-src-elem'?: Csp.Sources; + 'script-src-attr'?: Csp.Sources; + 'style-src'?: Array; + 'style-src-elem'?: Csp.Sources; + 'style-src-attr'?: Csp.Sources; + 'base-uri'?: Array; + sandbox?: Array< + | 'allow-downloads-without-user-activation' + | 'allow-forms' + | 'allow-modals' + | 'allow-orientation-lock' + | 'allow-pointer-lock' + | 'allow-popups' + | 'allow-popups-to-escape-sandbox' + | 'allow-presentation' + | 'allow-same-origin' + | 'allow-scripts' + | 'allow-storage-access-by-user-activation' + | 'allow-top-navigation' + | 'allow-top-navigation-by-user-activation' + >; + 'form-action'?: Array; + 'frame-ancestors'?: Array; + 'navigate-to'?: Array; + 'report-uri'?: Csp.UriPath[]; + 'report-to'?: string[]; + + 'require-trusted-types-for'?: Array<'script'>; + 'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>; + 'upgrade-insecure-requests'?: boolean; + + /** @deprecated */ + 'require-sri-for'?: Array<'script' | 'style' | 'script style'>; + + /** @deprecated */ + 'block-all-mixed-content'?: boolean; + + /** @deprecated */ + 'plugin-types'?: Array<`${string}/${string}` | 'none'>; + + /** @deprecated */ + referrer?: Array< + | 'no-referrer' + | 'no-referrer-when-downgrade' + | 'origin' + | 'origin-when-cross-origin' + | 'same-origin' + | 'strict-origin' + | 'strict-origin-when-cross-origin' + | 'unsafe-url' + | 'none' + >; + } + + type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS'; + + interface Logger { + (msg: string): void; + success(msg: string): void; + error(msg: string): void; + warn(msg: string): void; + minor(msg: string): void; + info(msg: string): void; + } + + type MaybePromise = T | Promise; + + interface Prerendered { + /** + * A map of `path` to `{ file }` objects, where a path like `/foo` corresponds to `foo.html` and a path like `/bar/` corresponds to `bar/index.html`. + */ + pages: Map< + string, + { + /** The location of the .html file relative to the output directory */ + file: string; + } + >; + /** + * A map of `path` to `{ type }` objects. + */ + assets: Map< + string, + { + /** The MIME type of the asset */ + type: string; + } + >; + /** + * A map of redirects encountered during prerendering. + */ + redirects: Map< + string, + { + status: number; + location: string; + } + >; + /** An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config) */ + paths: string[]; + } + + interface PrerenderHttpErrorHandler { + (details: { + status: number; + path: string; + referrer: string | null; + referenceType: 'linked' | 'fetched'; + message: string; + }): void; + } + + interface PrerenderMissingIdHandler { + (details: { path: string; id: string; referrers: string[]; message: string }): void; + } + + interface PrerenderEntryGeneratorMismatchHandler { + (details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void; + } + + type PrerenderHttpErrorHandlerValue = 'fail' | 'warn' | 'ignore' | PrerenderHttpErrorHandler; + type PrerenderMissingIdHandlerValue = 'fail' | 'warn' | 'ignore' | PrerenderMissingIdHandler; + type PrerenderEntryGeneratorMismatchHandlerValue = + | 'fail' + | 'warn' + | 'ignore' + | PrerenderEntryGeneratorMismatchHandler; + + export type PrerenderOption = boolean | 'auto'; + + interface RequestOptions { + getClientAddress(): string; + platform?: App.Platform; + } + + interface RouteSegment { + content: string; + dynamic: boolean; + rest: boolean; + } + + type TrailingSlash = 'never' | 'always' | 'ignore'; + class HttpError_1 { + + constructor(status: number, body: { + message: string; + } extends App.Error ? (App.Error | string | undefined) : App.Error); + status: number; + body: App.Error; + toString(): string; + } + class Redirect_1 { + + constructor(status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308, location: string); + status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308; + location: string; + } + + export class ActionFailure | undefined = undefined> { + + constructor(status: number, data?: T | undefined); + status: number; + data: T | undefined; + } + interface Asset { + file: string; + size: number; + type: string | null; + } + + interface BuildData { + app_dir: string; + app_path: string; + manifest_data: ManifestData; + service_worker: string | null; + client: { + start: string; + app: string; + imports: string[]; + stylesheets: string[]; + fonts: string[]; + } | null; + server_manifest: import('vite').Manifest; + } + + interface ManifestData { + assets: Asset[]; + nodes: PageNode[]; + routes: RouteData[]; + matchers: Record; + } + + interface PageNode { + depth: number; + component?: string; // TODO supply default component if it's missing (bit of an edge case) + universal?: string; + server?: string; + parent_id?: string; + parent?: PageNode; + /** + * Filled with the pages that reference this layout (if this is a layout) + */ + child_pages?: PageNode[]; + } + + type RecursiveRequired = { + // Recursive implementation of TypeScript's Required utility type. + // Will recursively continue until it reaches a primitive or Function + [K in keyof T]-?: Extract extends never // If it does not have a Function type + ? RecursiveRequired // recursively continue through. + : T[K]; // Use the exact type for everything else + }; + + interface RouteParam { + name: string; + matcher: string; + optional: boolean; + rest: boolean; + chained: boolean; + } + + /** + * Represents a route segment in the app. It can either be an intermediate node + * with only layout/error pages, or a leaf, at which point either `page` and `leaf` + * or `endpoint` is set. + */ + interface RouteData { + id: string; + parent: RouteData | null; + + segment: string; + pattern: RegExp; + params: RouteParam[]; + + layout: PageNode | null; + error: PageNode | null; + leaf: PageNode | null; + + page: { + layouts: Array; + errors: Array; + leaf: number; + } | null; + + endpoint: { + file: string; + } | null; + } + + interface SSRComponent { + default: { + render(props: Record): { + html: string; + head: string; + css: { + code: string; + map: any; // TODO + }; + }; + }; + } + + type SSRComponentLoader = () => Promise; + + interface SSRNode { + component: SSRComponentLoader; + /** index into the `components` array in client/manifest.js */ + index: number; + /** external JS files */ + imports: string[]; + /** external CSS files */ + stylesheets: string[]; + /** external font files */ + fonts: string[]; + /** inlined styles */ + inline_styles?(): MaybePromise>; + + universal: { + load?: Load; + prerender?: PrerenderOption; + ssr?: boolean; + csr?: boolean; + trailingSlash?: TrailingSlash; + config?: any; + entries?: PrerenderEntryGenerator; + }; + + server: { + load?: ServerLoad; + prerender?: PrerenderOption; + ssr?: boolean; + csr?: boolean; + trailingSlash?: TrailingSlash; + actions?: Actions; + config?: any; + entries?: PrerenderEntryGenerator; + }; + + universal_id: string; + server_id: string; + } + + type SSRNodeLoader = () => Promise; + + interface PageNodeIndexes { + errors: Array; + layouts: Array; + leaf: number; + } + + type PrerenderEntryGenerator = () => MaybePromise>>; + + type SSREndpoint = Partial> & { + prerender?: PrerenderOption; + trailingSlash?: TrailingSlash; + config?: any; + entries?: PrerenderEntryGenerator; + }; + + interface SSRRoute { + id: string; + pattern: RegExp; + params: RouteParam[]; + page: PageNodeIndexes | null; + endpoint: (() => Promise) | null; + endpoint_id?: string; + } + + type ValidatedConfig = RecursiveRequired; + export function error(status: number, body: App.Error): HttpError_1; + export function error(status: number, body?: { + message: string; + } extends App.Error ? App.Error | string | undefined : never): HttpError_1; + /** + * Create a `Redirect` object. If thrown during request handling, SvelteKit will return a redirect response. + * Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it. + * @param status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages). Must be in the range 300-308. + * @param location The location to redirect to. + */ + export function redirect(status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308, location: string): Redirect_1; + /** + * Create a JSON `Response` object from the supplied data. + * @param data The value that will be serialized as JSON. + * @param init Options such as `status` and `headers` that will be added to the response. `Content-Type: application/json` and `Content-Length` headers will be added automatically. + */ + export function json(data: any, init?: ResponseInit | undefined): Response; + /** + * Create a `Response` object from the supplied body. + * @param body The value that will be used as-is. + * @param init Options such as `status` and `headers` that will be added to the response. A `Content-Length` header will be added automatically. + */ + export function text(body: string, init?: ResponseInit | undefined): Response; + /** + * Create an `ActionFailure` object. + * @param status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. + * @param data Data associated with the failure (e.g. validation errors) + * */ + export function fail | undefined = undefined>(status: number, data?: T | undefined): ActionFailure; + /** + * Populate a route ID with params to resolve a pathname. + * @example + * ```js + * resolvePath( + * `/blog/[slug]/[...somethingElse]`, + * { + * slug: 'hello-world', + * somethingElse: 'something/else' + * } + * ); // `/blog/hello-world/something/else` + * ``` + * */ + export function resolvePath(id: string, params: Record): string; + export const VERSION: string; +} + +declare module '@sveltejs/kit/hooks' { + /** + * A helper function for sequencing multiple `handle` calls in a middleware-like manner. + * The behavior for the `handle` options is as follows: + * - `transformPageChunk` is applied in reverse order and merged + * - `preload` is applied in forward order, the first option "wins" and no `preload` options after it are called + * - `filterSerializedResponseHeaders` behaves the same as `preload` + * + * ```js + * /// file: src/hooks.server.js + * import { sequence } from '@sveltejs/kit/hooks'; + * + * /// type: import('@sveltejs/kit').Handle + * async function first({ event, resolve }) { + * console.log('first pre-processing'); + * const result = await resolve(event, { + * transformPageChunk: ({ html }) => { + * // transforms are applied in reverse order + * console.log('first transform'); + * return html; + * }, + * preload: () => { + * // this one wins as it's the first defined in the chain + * console.log('first preload'); + * } + * }); + * console.log('first post-processing'); + * return result; + * } + * + * /// type: import('@sveltejs/kit').Handle + * async function second({ event, resolve }) { + * console.log('second pre-processing'); + * const result = await resolve(event, { + * transformPageChunk: ({ html }) => { + * console.log('second transform'); + * return html; + * }, + * preload: () => { + * console.log('second preload'); + * }, + * filterSerializedResponseHeaders: () => { + * // this one wins as it's the first defined in the chain + * console.log('second filterSerializedResponseHeaders'); + * } + * }); + * console.log('second post-processing'); + * return result; + * } + * + * export const handle = sequence(first, second); + * ``` + * + * The example above would print: + * + * ``` + * first pre-processing + * first preload + * second pre-processing + * second filterSerializedResponseHeaders + * second transform + * first transform + * second post-processing + * first post-processing + * ``` + * + * @param handlers The chain of `handle` functions + * */ + export function sequence(...handlers: import('@sveltejs/kit').Handle[]): import('@sveltejs/kit').Handle; +} + +declare module '@sveltejs/kit/node' { + export function getRequest({ request, base, bodySizeLimit }: { + request: import('http').IncomingMessage; + base: string; + bodySizeLimit?: number; + }): Promise; + + export function setResponse(res: import('http').ServerResponse, response: Response): Promise; +} + +declare module '@sveltejs/kit/node/polyfills' { + /** + * Make various web APIs available as globals: + * - `crypto` + * - `fetch` + * - `Headers` + * - `Request` + * - `Response` + */ + export function installPolyfills(): void; +} + +declare module '@sveltejs/kit/vite' { + export { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; + /** + * Returns the SvelteKit Vite plugins. + * */ + export function sveltekit(): Promise; +} + +declare module '$app/environment' { + export { building, version } from '__sveltekit/environment'; + /** + * `true` if the app is running in the browser. + */ + export const browser: boolean; + /** + * Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`. + */ + export const dev: boolean; +} + +declare module '$app/forms' { + /** + * This action updates the `form` property of the current page with the given data and updates `$page.status`. + * In case of an error, it redirects to the nearest error page. + * */ + export function applyAction | undefined, Failure extends Record | undefined>(result: import("@sveltejs/kit").ActionResult): Promise; + /** + * Use this function to deserialize the response from a form submission. + * Usage: + * + * ```js + * import { deserialize } from '$app/forms'; + * + * async function handleSubmit(event) { + * const response = await fetch('/form?/action', { + * method: 'POST', + * body: new FormData(event.target) + * }); + * + * const result = deserialize(await response.text()); + * // ... + * } + * ``` + * */ + export function deserialize | undefined, Failure extends Record | undefined>(result: string): import("@sveltejs/kit").ActionResult; + /** + * This action enhances a `` element that otherwise would work without JavaScript. + * + * The `submit` function is called upon submission with the given FormData and the `action` that should be triggered. + * If `cancel` is called, the form will not be submitted. + * You can use the abort `controller` to cancel the submission in case another one starts. + * If a function is returned, that function is called with the response from the server. + * If nothing is returned, the fallback will be used. + * + * If this function or its return value isn't set, it + * - falls back to updating the `form` prop with the returned data if the action is one same page as the form + * - updates `$page.status` + * - resets the `` element and invalidates all data in case of successful submission with no redirect response + * - redirects in case of a redirect response + * - redirects to the nearest error page in case of an unexpected error + * + * If you provide a custom function with a callback and want to use the default behavior, invoke `update` in your callback. + * @param form_element The form element + * @param submit Submit callback + */ + export function enhance | undefined, Failure extends Record | undefined>(form_element: HTMLFormElement, submit?: import("@sveltejs/kit").SubmitFunction): { + destroy(): void; + }; +} + +declare module '$app/navigation' { + /** + * If called when the page is being updated following a navigation (in `onMount` or `afterNavigate` or an action, for example), this disables SvelteKit's built-in scroll handling. + * This is generally discouraged, since it breaks user expectations. + * */ + export const disableScrollHandling: () => void; + /** + * Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified `url`. + * For external URLs, use `window.location = url` instead of calling `goto(url)`. + * + * @param url Where to navigate to. Note that if you've set [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths) and the URL is root-relative, you need to prepend the base path if you want to navigate within the app. + * @param {Object} opts Options related to the navigation + * @param invalidateAll If `true`, all `load` functions of the page will be rerun. See https://kit.svelte.dev/docs/load#rerunning-load-functions for more info on invalidation. + * @param opts.state The state of the new/updated history entry + * */ + export const goto: (url: string | URL, opts?: { + replaceState?: boolean; + noScroll?: boolean; + keepFocus?: boolean; + invalidateAll?: boolean; + state?: any; + }) => Promise; + /** + * Causes any `load` functions belonging to the currently active page to re-run if they depend on the `url` in question, via `fetch` or `depends`. Returns a `Promise` that resolves when the page is subsequently updated. + * + * If the argument is given as a `string` or `URL`, it must resolve to the same URL that was passed to `fetch` or `depends` (including query parameters). + * To create a custom identifier, use a string beginning with `[a-z]+:` (e.g. `custom:state`) — this is a valid URL. + * + * The `function` argument can be used define a custom predicate. It receives the full `URL` and causes `load` to rerun if `true` is returned. + * This can be useful if you want to invalidate based on a pattern instead of a exact match. + * + * ```ts + * // Example: Match '/path' regardless of the query parameters + * import { invalidate } from '$app/navigation'; + * + * invalidate((url) => url.pathname === '/path'); + * ``` + * @param url The invalidated URL + * */ + export const invalidate: (url: string | URL | ((url: URL) => boolean)) => Promise; + /** + * Causes all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated. + * */ + export const invalidateAll: () => Promise; + /** + * Programmatically preloads the given page, which means + * 1. ensuring that the code for the page is loaded, and + * 2. calling the page's load function with the appropriate options. + * + * This is the same behaviour that SvelteKit triggers when the user taps or mouses over an `` element with `data-sveltekit-preload-data`. + * If the next navigation is to `href`, the values returned from load will be used, making navigation instantaneous. + * Returns a Promise that resolves when the preload is complete. + * + * @param href Page to preload + * */ + export const preloadData: (href: string) => Promise; + /** + * Programmatically imports the code for routes that haven't yet been fetched. + * Typically, you might call this to speed up subsequent navigation. + * + * You can specify routes by any matching pathname such as `/about` (to match `src/routes/about/+page.svelte`) or `/blog/*` (to match `src/routes/blog/[slug]/+page.svelte`). + * + * Unlike `preloadData`, this won't call `load` functions. + * Returns a Promise that resolves when the modules have been imported. + * + * */ + export const preloadCode: (...urls: string[]) => Promise; + /** + * A navigation interceptor that triggers before we navigate to a new URL, whether by clicking a link, calling `goto(...)`, or using the browser back/forward controls. + * Calling `cancel()` will prevent the navigation from completing. If the navigation would have directly unloaded the current page, calling `cancel` will trigger the native + * browser unload confirmation dialog. In these cases, `navigation.willUnload` is `true`. + * + * When a navigation isn't client side, `navigation.to.route.id` will be `null`. + * + * `beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + * */ + export const beforeNavigate: (callback: (navigation: import('@sveltejs/kit').BeforeNavigate) => void) => void; + /** + * A lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a new URL. + * + * `afterNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + * */ + export const afterNavigate: (callback: (navigation: import('@sveltejs/kit').AfterNavigate) => void) => void; +} + +declare module '$app/paths' { + export { base, assets } from '__sveltekit/paths'; +} + +declare module '$app/stores' { + export function getStores(): { + + page: typeof page; + + navigating: typeof navigating; + + updated: typeof updated; + }; + /** + * A readable store whose value contains page data. + * + * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + * + * */ + export const page: import('svelte/store').Readable; + /** + * A readable store. + * When navigating starts, its value is a `Navigation` object with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties. + * When navigating finishes, its value reverts to `null`. + * + * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + * */ + export const navigating: import('svelte/store').Readable; + /** + * A readable store whose initial value is `false`. If [`version.pollInterval`](https://kit.svelte.dev/docs/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update the store value to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling. + * + * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + * */ + export const updated: import('svelte/store').Readable & { + check(): Promise; + }; +}/** + * It's possible to tell SvelteKit how to type objects inside your app by declaring the `App` namespace. By default, a new project will have a file called `src/app.d.ts` containing the following: + * + * ```ts + * declare global { + * namespace App { + * // interface Error {} + * // interface Locals {} + * // interface PageData {} + * // interface Platform {} + * } + * } + * + * export {}; + * ``` + * + * The `export {}` line exists because without it, the file would be treated as an _ambient module_ which prevents you from adding `import` declarations. + * If you need to add ambient `declare module` declarations, do so in a separate file like `src/ambient.d.ts`. + * + * By populating these interfaces, you will gain type safety when using `event.locals`, `event.platform`, and `data` from `load` functions. + */ +declare namespace App { + /** + * Defines the common shape of expected and unexpected errors. Expected errors are thrown using the `error` function. Unexpected errors are handled by the `handleError` hooks which should return this shape. + */ + export interface Error { + message: string; + } + + /** + * The interface that defines `event.locals`, which can be accessed in [hooks](https://kit.svelte.dev/docs/hooks) (`handle`, and `handleError`), server-only `load` functions, and `+server.js` files. + */ + export interface Locals {} + + /** + * Defines the common shape of the [$page.data store](https://kit.svelte.dev/docs/modules#$app-stores-page) - that is, the data that is shared between all pages. + * The `Load` and `ServerLoad` functions in `./$types` will be narrowed accordingly. + * Use optional properties for data that is only present on specific pages. Do not add an index signature (`[key: string]: any`). + */ + export interface PageData {} + + /** + * If your adapter provides [platform-specific context](https://kit.svelte.dev/docs/adapters#platform-specific-context) via `event.platform`, you can specify it here. + */ + export interface Platform {} +} + +/** + * This module is only available to [service workers](https://kit.svelte.dev/docs/service-workers). + */ +declare module '$service-worker' { + /** + * The `base` path of the deployment. Typically this is equivalent to `config.kit.paths.base`, but it is calculated from `location.pathname` meaning that it will continue to work correctly if the site is deployed to a subdirectory. + * Note that there is a `base` but no `assets`, since service workers cannot be used if `config.kit.paths.assets` is specified. + */ + export const base: string; + /** + * An array of URL strings representing the files generated by Vite, suitable for caching with `cache.addAll(build)`. + * During development, this is an empty array. + */ + export const build: string[]; + /** + * An array of URL strings representing the files in your static directory, or whatever directory is specified by `config.kit.files.assets`. You can customize which files are included from `static` directory using [`config.kit.serviceWorker.files`](https://kit.svelte.dev/docs/configuration) + */ + export const files: string[]; + /** + * An array of pathnames corresponding to prerendered pages and endpoints. + * During development, this is an empty array. + */ + export const prerendered: string[]; + /** + * See [`config.kit.version`](https://kit.svelte.dev/docs/configuration#version). It's useful for generating unique cache names inside your service worker, so that a later deployment of your app can invalidate old caches. + */ + export const version: string; +} + +/** Internal version of $app/environment */ +declare module '__sveltekit/environment' { + /** + * SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. + */ + export const building: boolean; + /** + * The value of `config.kit.version.name`. + */ + export const version: string; + export function set_building(): void; +} + +/** Internal version of $app/paths */ +declare module '__sveltekit/paths' { + /** + * A string that matches [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths). + * + * Example usage: `Link` + */ + export let base: '' | `/${string}`; + /** + * An absolute path that matches [`config.kit.paths.assets`](https://kit.svelte.dev/docs/configuration#paths). + * + * > If a value for `config.kit.paths.assets` is specified, it will be replaced with `'/_svelte_kit_assets'` during `vite dev` or `vite preview`, since the assets don't yet live at their eventual URL. + */ + export let assets: '' | `https://${string}` | `http://${string}` | '/_svelte_kit_assets'; + export let relative: boolean | undefined; // TODO in 2.0, make this a `boolean` that defaults to `true` + export function reset(): void; + export function override(paths: { base: string; assets: string }): void; + export function set_assets(path: string): void; +} + +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@sveltejs/kit/types/index.d.ts.map b/node_modules/@sveltejs/kit/types/index.d.ts.map new file mode 100644 index 0000000..bffb351 --- /dev/null +++ b/node_modules/@sveltejs/kit/types/index.d.ts.map @@ -0,0 +1,138 @@ +{ + "version": 3, + "file": "index.d.ts", + "names": [ + "Adapter", + "AwaitedProperties", + "AwaitedActions", + "Builder", + "Config", + "Cookies", + "KitConfig", + "Handle", + "HandleServerError", + "HandleClientError", + "HandleFetch", + "Load", + "LoadEvent", + "NavigationEvent", + "NavigationTarget", + "NavigationType", + "Navigation", + "BeforeNavigate", + "AfterNavigate", + "Page", + "ParamMatcher", + "RequestEvent", + "RequestHandler", + "ResolveOptions", + "RouteDefinition", + "Server", + "ServerInitOptions", + "SSRManifest", + "ServerLoad", + "ServerLoadEvent", + "Action", + "Actions", + "ActionResult", + "HttpError", + "Redirect", + "SubmitFunction", + "Snapshot", + "AdapterEntry", + "Csp", + "CspDirectives", + "HttpMethod", + "Logger", + "MaybePromise", + "Prerendered", + "PrerenderHttpErrorHandler", + "PrerenderMissingIdHandler", + "PrerenderEntryGeneratorMismatchHandler", + "PrerenderHttpErrorHandlerValue", + "PrerenderMissingIdHandlerValue", + "PrerenderEntryGeneratorMismatchHandlerValue", + "PrerenderOption", + "RequestOptions", + "RouteSegment", + "TrailingSlash", + "ActionFailure", + "Asset", + "BuildData", + "ManifestData", + "PageNode", + "RecursiveRequired", + "RouteParam", + "RouteData", + "SSRComponent", + "SSRComponentLoader", + "SSRNode", + "SSRNodeLoader", + "PageNodeIndexes", + "PrerenderEntryGenerator", + "SSREndpoint", + "SSRRoute", + "ValidatedConfig", + "redirect", + "json", + "text", + "fail", + "resolvePath", + "VERSION", + "sequence", + "getRequest", + "setResponse", + "installPolyfills", + "sveltekit", + "browser", + "dev", + "applyAction", + "deserialize", + "enhance", + "disableScrollHandling", + "goto", + "invalidate", + "invalidateAll", + "preloadData", + "preloadCode", + "beforeNavigate", + "afterNavigate", + "getStores", + "page", + "navigating", + "updated" + ], + "sources": [ + "../src/exports/public.d.ts", + "../src/runtime/control.js", + "../src/types/private.d.ts", + "../src/types/internal.d.ts", + "../src/exports/index.js", + "../src/version.js", + "../src/exports/hooks/sequence.js", + "../src/exports/node/index.js", + "../src/exports/node/polyfills.js", + "../src/exports/vite/index.js", + "../src/runtime/app/environment.js", + "../src/runtime/app/forms.js", + "../src/runtime/app/navigation.js", + "../src/runtime/app/stores.js" + ], + "sourcesContent": [ + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null + ], + "mappings": ";;;;;;;;;kBA6BiBA,OAAOA;;;;;;;;;;;;;;;;;;;;;;aAsBZC,iBAAiBA;;;;;aAKjBC,cAAcA;;;;;;;;;;;;;;;;;;;;;;;kBAuBTC,OAAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAuFPC,MAAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBA6BNC,OAAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAiDPC,SAASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aA0YdC,MAAMA;;;;;;;;;;;a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;;;;;;;;;iBCrFjBC,gBAAgBA;;;;;;;;iBCqFVC,SAASA;;;;;;;;cC/GlBC,OAAOA;;;;cAKPC,GAAGA;;;;;;;;iBCEAC,WAAWA;;;;;;;;;;;;;;;;;;;iBA8BXC,WAAWA;;;;;;;;;;;;;;;;;;;;;iBAuDXC,OAAOA;;;;;;;;;;cC3FVC,qBAAqBA;;;;;;;;;;cAsBrBC,IAAIA;;;;;;;;;;;;;;;;;;;;;;;;cAqBJC,UAAUA;;;;cAOVC,aAAaA;;;;;;;;;;;;cAebC,WAAWA;;;;;;;;;;;cAeXC,WAAWA;;;;;;;;;;cAcXC,cAAcA;;;;;;cAUdC,aAAaA;;;;;;;;iBCvGbC,SAASA;;;;;;;;;;;;;;cAwBTC,IAAIA;;;;;;;;cAeJC,UAAUA;;;;;;cAaVC,OAAOA" +} \ No newline at end of file diff --git a/node_modules/@sveltejs/vite-plugin-svelte-inspector/LICENSE b/node_modules/@sveltejs/vite-plugin-svelte-inspector/LICENSE new file mode 100644 index 0000000..c1a5d8f --- /dev/null +++ b/node_modules/@sveltejs/vite-plugin-svelte-inspector/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 [these people](https://github.com/sveltejs/vite-plugin-svelte/graphs/contributors) + +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/@sveltejs/vite-plugin-svelte-inspector/README.md b/node_modules/@sveltejs/vite-plugin-svelte-inspector/README.md new file mode 100644 index 0000000..bbdf50c --- /dev/null +++ b/node_modules/@sveltejs/vite-plugin-svelte-inspector/README.md @@ -0,0 +1,26 @@ +# @sveltejs/vite-plugin-svelte-inspector + +A [Svelte](https://svelte.dev) inspector plugin for [Vite](https://vitejs.dev). + +## Usage + +```js +// vite.config.js +import { defineConfig } from 'vite'; +import { svelte } from '@sveltejs/vite-plugin-svelte'; +import { svelteInspector } from '@sveltejs/vite-plugin-svelte-inspector'; + +export default defineConfig({ + plugins: [ + // the svelte plugin is required to work + svelte(), + svelteInspector({ + /* plugin options */ + }) + ] +}); +``` + +## License + +[MIT](./LICENSE) diff --git a/node_modules/@sveltejs/vite-plugin-svelte-inspector/package.json b/node_modules/@sveltejs/vite-plugin-svelte-inspector/package.json new file mode 100644 index 0000000..604118f --- /dev/null +++ b/node_modules/@sveltejs/vite-plugin-svelte-inspector/package.json @@ -0,0 +1,52 @@ +{ + "name": "@sveltejs/vite-plugin-svelte-inspector", + "version": "1.0.3", + "license": "MIT", + "author": "dominikg", + "files": [ + "src" + ], + "type": "module", + "types": "src/index.d.ts", + "exports": { + ".": { + "types": "./src/index.d.ts", + "import": "./src/index.js" + } + }, + "engines": { + "node": "^14.18.0 || >= 16" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/sveltejs/vite-plugin-svelte.git", + "directory": "packages/vite-plugin-svelte-inspector" + }, + "keywords": [ + "vite-plugin", + "vite plugin", + "vite", + "svelte" + ], + "bugs": { + "url": "https://github.com/sveltejs/vite-plugin-svelte/issues" + }, + "homepage": "https://github.com/sveltejs/vite-plugin-svelte#readme", + "dependencies": { + "debug": "^4.3.4" + }, + "peerDependencies": { + "@sveltejs/vite-plugin-svelte": "^2.2.0", + "svelte": "^3.54.0 || ^4.0.0", + "vite": "^4.0.0" + }, + "devDependencies": { + "@types/debug": "^4.1.8", + "svelte": "^3.59.2", + "vite": "^4.3.9" + }, + "scripts": { + "check:publint": "publint --strict", + "check:types": "tsc --noEmit" + } +} \ No newline at end of file diff --git a/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/debug.js b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/debug.js new file mode 100644 index 0000000..0575a83 --- /dev/null +++ b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/debug.js @@ -0,0 +1,3 @@ +import _debug from 'debug'; + +export const debug = _debug('vite-plugin-svelte-inspector'); diff --git a/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/index.d.ts b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/index.d.ts new file mode 100644 index 0000000..b5c2ce2 --- /dev/null +++ b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/index.d.ts @@ -0,0 +1,73 @@ +import type { Plugin } from 'vite'; + +export interface Options { + /** + * define a key combo to toggle inspector, + * @default 'meta-shift' on mac, 'control-shift' on other os + * + * any number of modifiers `control` `shift` `alt` `meta` followed by zero or one regular key, separated by - + * examples: control-shift, control-o, control-alt-s meta-x control-meta + * Some keys have native behavior (e.g. alt-s opens history menu on firefox). + * To avoid conflicts or accidentally typing into inputs, modifier only combinations are recommended. + */ + toggleKeyCombo?: string; + + /** + * define keys to select elements with via keyboard + * @default {parent: 'ArrowUp', child: 'ArrowDown', next: 'ArrowRight', prev: 'ArrowLeft' } + * + * improves accessibility and also helps when you want to select elements that do not have a hoverable surface area + * due to tight wrapping + * + * A note for users of screen-readers: + * If you are using arrow keys to navigate the page itself, change the navKeys to avoid conflicts. + * e.g. navKeys: {parent: 'w', prev: 'a', child: 's', next: 'd'} + * + * + * parent: select closest parent + * child: select first child (or grandchild) + * next: next sibling (or parent if no next sibling exists) + * prev: previous sibling (or parent if no prev sibling exists) + */ + navKeys?: { parent: string; child: string; next: string; prev: string }; + + /** + * define key to open the editor for the currently selected dom node + * + * @default 'Enter' + */ + openKey?: string; + + /** + * inspector is automatically disabled when releasing toggleKeyCombo after holding it for a longpress + * @default true + */ + holdMode?: boolean; + + /** + * when to show the toggle button + * @default 'active' + */ + showToggleButton?: 'always' | 'active' | 'never'; + + /** + * where to display the toggle button + * @default top-right + */ + toggleButtonPos?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'; + + /** + * inject custom styles when inspector is active + */ + customStyles?: boolean; + + /** + * internal options that are automatically set, not to be set or used by users + */ + __internal?: { + // vite base url + base: string; + }; +} + +export declare function svelteInspector(options?: Options): Plugin; diff --git a/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/index.js b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/index.js new file mode 100644 index 0000000..fd28940 --- /dev/null +++ b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/index.js @@ -0,0 +1,110 @@ +import { normalizePath } from 'vite'; +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import { debug } from './debug.js'; +import { defaultInspectorOptions, parseEnvironmentOptions } from './options.js'; +import { cleanUrl } from './utils.js'; + +function getInspectorPath() { + const pluginPath = normalizePath(path.dirname(fileURLToPath(import.meta.url))); + return pluginPath.replace( + /\/vite-plugin-svelte-inspector\/src$/, + '/vite-plugin-svelte-inspector/src/runtime/' + ); +} + +/** @type {import('.').svelteInspector} */ +export function svelteInspector(options) { + const inspectorPath = getInspectorPath(); + debug(`svelte inspector path: ${inspectorPath}`); + + /** @type {import('vite').ResolvedConfig} */ + let viteConfig; + /** @type {import('.').Options} */ + let inspectorOptions; + let disabled = false; + + return { + name: 'vite-plugin-svelte-inspector', + apply: 'serve', + enforce: 'pre', + + configResolved(config) { + viteConfig = config; + + const environmentOptions = parseEnvironmentOptions(config); + if (environmentOptions === false) { + debug(`environment options set to false, inspector disabled`); + disabled = true; + return; + } + + // Handle config from svelte.config.js through vite-plugin-svelte + const vps = config.plugins.find((p) => p.name === 'vite-plugin-svelte'); + const configFileOptions = vps?.api?.options?.inspector; + + // vite-plugin-svelte can only pass options through it's `api` instead of `options`. + // that means this plugin could be created but should be disabled, so we check this case here. + if (vps && !options && !configFileOptions && !environmentOptions) { + debug(`vite-plugin-svelte didn't pass options, inspector disabled`); + disabled = true; + return; + } + + if (environmentOptions === true) { + inspectorOptions = defaultInspectorOptions; + } else { + inspectorOptions = { + ...defaultInspectorOptions, + ...configFileOptions, + ...options, + ...(environmentOptions || {}) + }; + } + + inspectorOptions.__internal = { + base: config.base?.replace(/\/$/, '') || '' + }; + }, + + async resolveId(importee, _, options) { + if (options?.ssr || disabled) { + return; + } + if (importee.startsWith('virtual:svelte-inspector-options')) { + return importee; + } else if (importee.startsWith('virtual:svelte-inspector-path:')) { + return importee.replace('virtual:svelte-inspector-path:', inspectorPath); + } + }, + + async load(id, options) { + if (options?.ssr || disabled) { + return; + } + if (id === 'virtual:svelte-inspector-options') { + return `export default ${JSON.stringify(inspectorOptions ?? {})}`; + } else if (id.startsWith(inspectorPath)) { + // read file ourselves to avoid getting shut out by vites fs.allow check + const file = cleanUrl(id); + if (fs.existsSync(id)) { + return await fs.promises.readFile(file, 'utf-8'); + } else { + viteConfig.logger.error( + `[vite-plugin-svelte-inspector] failed to find svelte-inspector: ${id}` + ); + } + } + }, + + transform(code, id, options) { + if (options?.ssr || disabled) { + return; + } + if (id.includes('vite/dist/client/client.mjs')) { + return { code: `${code}\nimport('virtual:svelte-inspector-path:load-inspector.js')` }; + } + } + }; +} diff --git a/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/options.js b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/options.js new file mode 100644 index 0000000..9283df9 --- /dev/null +++ b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/options.js @@ -0,0 +1,61 @@ +import { loadEnv } from 'vite'; +import { debug } from './debug.js'; + +/** @type {import('.').Options} */ +export const defaultInspectorOptions = { + toggleKeyCombo: process.platform === 'darwin' ? 'meta-shift' : 'control-shift', + navKeys: { parent: 'ArrowUp', child: 'ArrowDown', next: 'ArrowRight', prev: 'ArrowLeft' }, + openKey: 'Enter', + holdMode: true, + showToggleButton: 'active', + toggleButtonPos: 'top-right', + customStyles: true +}; + +/** + * @param {import('vite').ResolvedConfig} config + * @returns {Partial | boolean | void} + */ +export function parseEnvironmentOptions(config) { + const env = loadEnv(config.mode, config.envDir ?? process.cwd(), 'SVELTE_INSPECTOR'); + const options = env?.SVELTE_INSPECTOR_OPTIONS; + const toggle = env?.SVELTE_INSPECTOR_TOGGLE; + if (options) { + try { + const parsed = JSON.parse(options); + const parsedType = typeof parsed; + if (parsedType === 'boolean') { + return parsed; + } else if (parsedType === 'object') { + if (Array.isArray(parsed)) { + throw new Error('invalid type, expected object map but got array'); + } + const parsedKeys = Object.keys(parsed); + const defaultKeys = Object.keys(defaultInspectorOptions); + const unknownKeys = parsedKeys.filter((k) => !defaultKeys.includes(k)); + if (unknownKeys.length) { + config.logger.warn( + `[vite-plugin-svelte-inspector] ignoring unknown options in environment SVELTE_INSPECTOR_OPTIONS: ${unknownKeys.join( + ', ' + )}` + ); + for (const key of unknownKeys) { + delete parsed[key]; + } + } + debug('loaded environment config', parsed); + return parsed; + } + } catch (e) { + config.logger.error( + `[vite-plugin-svelte-inspector] failed to parse inspector options from environment SVELTE_INSPECTOR_OPTIONS="${options}"\n${e}` + ); + } + } else if (toggle) { + const keyConfig = { + toggleKeyCombo: toggle + }; + debug('loaded environment config', keyConfig); + return keyConfig; + } +} diff --git a/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/runtime/Inspector.svelte b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/runtime/Inspector.svelte new file mode 100644 index 0000000..40084c8 --- /dev/null +++ b/node_modules/@sveltejs/vite-plugin-svelte-inspector/src/runtime/Inspector.svelte @@ -0,0 +1,384 @@ + + +{#if show_toggle} +