Erster Docker-Stand

This commit is contained in:
Ali
2026-02-20 16:06:40 +09:00
commit f31e2e8ed3
8818 changed files with 1605323 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
node_modules
# Keep environment variables out of version control
.env
/src/generated/prisma

7
Dockerfile Normal file
View File

@@ -0,0 +1,7 @@
FROM node:20
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 5003
CMD ["npm", "run", "dev"]

16
_node_modules/.bin/bcrypt generated Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../bcryptjs/bin/bcrypt" "$@"
else
exec node "$basedir/../bcryptjs/bin/bcrypt" "$@"
fi

17
_node_modules/.bin/bcrypt.cmd generated Normal file
View File

@@ -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%\..\bcryptjs\bin\bcrypt" %*

28
_node_modules/.bin/bcrypt.ps1 generated Normal file
View File

@@ -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/../bcryptjs/bin/bcrypt" $args
} else {
& "$basedir/node$exe" "$basedir/../bcryptjs/bin/bcrypt" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../bcryptjs/bin/bcrypt" $args
} else {
& "node$exe" "$basedir/../bcryptjs/bin/bcrypt" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
_node_modules/.bin/giget generated Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../giget/dist/cli.mjs" "$@"
else
exec node "$basedir/../giget/dist/cli.mjs" "$@"
fi

17
_node_modules/.bin/giget.cmd generated Normal file
View File

@@ -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%\..\giget\dist\cli.mjs" %*

28
_node_modules/.bin/giget.ps1 generated Normal file
View File

@@ -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/../giget/dist/cli.mjs" $args
} else {
& "$basedir/node$exe" "$basedir/../giget/dist/cli.mjs" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../giget/dist/cli.mjs" $args
} else {
& "node$exe" "$basedir/../giget/dist/cli.mjs" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
_node_modules/.bin/jiti generated Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../jiti/lib/jiti-cli.mjs" "$@"
else
exec node "$basedir/../jiti/lib/jiti-cli.mjs" "$@"
fi

17
_node_modules/.bin/jiti.cmd generated Normal file
View File

@@ -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%\..\jiti\lib\jiti-cli.mjs" %*

28
_node_modules/.bin/jiti.ps1 generated Normal file
View File

@@ -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/../jiti/lib/jiti-cli.mjs" $args
} else {
& "$basedir/node$exe" "$basedir/../jiti/lib/jiti-cli.mjs" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../jiti/lib/jiti-cli.mjs" $args
} else {
& "node$exe" "$basedir/../jiti/lib/jiti-cli.mjs" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
_node_modules/.bin/node-which generated Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../which/bin/node-which" "$@"
else
exec node "$basedir/../which/bin/node-which" "$@"
fi

17
_node_modules/.bin/node-which.cmd generated Normal file
View File

@@ -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%\..\which\bin\node-which" %*

28
_node_modules/.bin/node-which.ps1 generated Normal file
View File

@@ -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/../which/bin/node-which" $args
} else {
& "$basedir/node$exe" "$basedir/../which/bin/node-which" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../which/bin/node-which" $args
} else {
& "node$exe" "$basedir/../which/bin/node-which" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
_node_modules/.bin/nypm generated Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../nypm/dist/cli.mjs" "$@"
else
exec node "$basedir/../nypm/dist/cli.mjs" "$@"
fi

17
_node_modules/.bin/nypm.cmd generated Normal file
View File

@@ -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%\..\nypm\dist\cli.mjs" %*

28
_node_modules/.bin/nypm.ps1 generated Normal file
View File

@@ -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/../nypm/dist/cli.mjs" $args
} else {
& "$basedir/node$exe" "$basedir/../nypm/dist/cli.mjs" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../nypm/dist/cli.mjs" $args
} else {
& "node$exe" "$basedir/../nypm/dist/cli.mjs" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
_node_modules/.bin/pglite-server generated Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../@electric-sql/pglite-socket/dist/scripts/server.js" "$@"
else
exec node "$basedir/../@electric-sql/pglite-socket/dist/scripts/server.js" "$@"
fi

17
_node_modules/.bin/pglite-server.cmd generated Normal file
View File

@@ -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%\..\@electric-sql\pglite-socket\dist\scripts\server.js" %*

28
_node_modules/.bin/pglite-server.ps1 generated Normal file
View File

@@ -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/../@electric-sql/pglite-socket/dist/scripts/server.js" $args
} else {
& "$basedir/node$exe" "$basedir/../@electric-sql/pglite-socket/dist/scripts/server.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../@electric-sql/pglite-socket/dist/scripts/server.js" $args
} else {
& "node$exe" "$basedir/../@electric-sql/pglite-socket/dist/scripts/server.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
_node_modules/.bin/prisma generated Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../prisma/build/index.js" "$@"
else
exec node "$basedir/../prisma/build/index.js" "$@"
fi

17
_node_modules/.bin/prisma.cmd generated Normal file
View File

@@ -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%\..\prisma\build\index.js" %*

28
_node_modules/.bin/prisma.ps1 generated Normal file
View File

@@ -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/../prisma/build/index.js" $args
} else {
& "$basedir/node$exe" "$basedir/../prisma/build/index.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../prisma/build/index.js" $args
} else {
& "node$exe" "$basedir/../prisma/build/index.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
_node_modules/.bin/semver generated Normal file
View File

@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../semver/bin/semver.js" "$@"
else
exec node "$basedir/../semver/bin/semver.js" "$@"
fi

17
_node_modules/.bin/semver.cmd generated Normal file
View File

@@ -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%\..\semver\bin\semver.js" %*

28
_node_modules/.bin/semver.ps1 generated Normal file
View File

@@ -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/../semver/bin/semver.js" $args
} else {
& "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../semver/bin/semver.js" $args
} else {
& "node$exe" "$basedir/../semver/bin/semver.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

View File

@@ -0,0 +1,15 @@
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.default = void 0;
await jitiImport("dotenv/config");
var _config2 = await jitiImport("prisma/config"); // This file was generated by Prisma, and assumes you have installed the following:
// npm install --save-dev prisma dotenv
var _default = exports.default = (0, _config2.defineConfig)({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations"
},
datasource: {
provider: "postgresql",
url: process.env.DATABASE_URL
}
}); /* v9-a1459f8d607d8082 */

2069
_node_modules/.package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -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.

View File

@@ -0,0 +1,2 @@
import { Rule, GenerateDtsOptions } from "@chevrotain/types";
export declare function generateCstDts(productions: Record<string, Rule>, options?: GenerateDtsOptions): string;

View File

@@ -0,0 +1,27 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateCstDts = void 0;
var model_1 = require("./model");
var generate_1 = require("./generate");
var defaultOptions = {
includeVisitorInterface: true,
visitorInterfaceName: "ICstNodeVisitor"
};
function generateCstDts(productions, options) {
var effectiveOptions = __assign(__assign({}, defaultOptions), options);
var model = (0, model_1.buildModel)(productions);
return (0, generate_1.genDts)(model, effectiveOptions);
}
exports.generateCstDts = generateCstDts;
//# sourceMappingURL=api.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/api.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AACA,iCAAoC;AACpC,uCAAmC;AAEnC,IAAM,cAAc,GAAiC;IACnD,uBAAuB,EAAE,IAAI;IAC7B,oBAAoB,EAAE,iBAAiB;CACxC,CAAA;AAED,SAAgB,cAAc,CAC5B,WAAiC,EACjC,OAA4B;IAE5B,IAAM,gBAAgB,yBACjB,cAAc,GACd,OAAO,CACX,CAAA;IAED,IAAM,KAAK,GAAG,IAAA,kBAAU,EAAC,WAAW,CAAC,CAAA;IAErC,OAAO,IAAA,iBAAM,EAAC,KAAK,EAAE,gBAAgB,CAAC,CAAA;AACxC,CAAC;AAZD,wCAYC"}

View File

@@ -0,0 +1,3 @@
import { GenerateDtsOptions } from "@chevrotain/types";
import { CstNodeTypeDefinition } from "./model";
export declare function genDts(model: CstNodeTypeDefinition[], options: Required<GenerateDtsOptions>): string;

View File

@@ -0,0 +1,70 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.genDts = void 0;
var flatten_1 = __importDefault(require("lodash/flatten"));
var isArray_1 = __importDefault(require("lodash/isArray"));
var map_1 = __importDefault(require("lodash/map"));
var reduce_1 = __importDefault(require("lodash/reduce"));
var uniq_1 = __importDefault(require("lodash/uniq"));
var upperFirst_1 = __importDefault(require("lodash/upperFirst"));
function genDts(model, options) {
var contentParts = [];
contentParts = contentParts.concat("import type { CstNode, ICstVisitor, IToken } from \"chevrotain\";");
contentParts = contentParts.concat((0, flatten_1.default)((0, map_1.default)(model, function (node) { return genCstNodeTypes(node); })));
if (options.includeVisitorInterface) {
contentParts = contentParts.concat(genVisitor(options.visitorInterfaceName, model));
}
return contentParts.join("\n\n") + "\n";
}
exports.genDts = genDts;
function genCstNodeTypes(node) {
var nodeCstInterface = genNodeInterface(node);
var nodeChildrenInterface = genNodeChildrenType(node);
return [nodeCstInterface, nodeChildrenInterface];
}
function genNodeInterface(node) {
var nodeInterfaceName = getNodeInterfaceName(node.name);
var childrenTypeName = getNodeChildrenTypeName(node.name);
return "export interface ".concat(nodeInterfaceName, " extends CstNode {\n name: \"").concat(node.name, "\";\n children: ").concat(childrenTypeName, ";\n}");
}
function genNodeChildrenType(node) {
var typeName = getNodeChildrenTypeName(node.name);
return "export type ".concat(typeName, " = {\n ").concat((0, map_1.default)(node.properties, function (property) { return genChildProperty(property); }).join("\n "), "\n};");
}
function genChildProperty(prop) {
var typeName = buildTypeString(prop.type);
return "".concat(prop.name).concat(prop.optional ? "?" : "", ": ").concat(typeName, "[];");
}
function genVisitor(name, nodes) {
return "export interface ".concat(name, "<IN, OUT> extends ICstVisitor<IN, OUT> {\n ").concat((0, map_1.default)(nodes, function (node) { return genVisitorFunction(node); }).join("\n "), "\n}");
}
function genVisitorFunction(node) {
var childrenTypeName = getNodeChildrenTypeName(node.name);
return "".concat(node.name, "(children: ").concat(childrenTypeName, ", param?: IN): OUT;");
}
function buildTypeString(type) {
if ((0, isArray_1.default)(type)) {
var typeNames = (0, uniq_1.default)((0, map_1.default)(type, function (t) { return getTypeString(t); }));
var typeString = (0, reduce_1.default)(typeNames, function (sum, t) { return sum + " | " + t; });
return "(" + typeString + ")";
}
else {
return getTypeString(type);
}
}
function getTypeString(type) {
if (type.kind === "token") {
return "IToken";
}
return getNodeInterfaceName(type.name);
}
function getNodeInterfaceName(ruleName) {
return (0, upperFirst_1.default)(ruleName) + "CstNode";
}
function getNodeChildrenTypeName(ruleName) {
return (0, upperFirst_1.default)(ruleName) + "CstChildren";
}
//# sourceMappingURL=generate.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"generate.js","sourceRoot":"","sources":["../../src/generate.ts"],"names":[],"mappings":";;;;;;AAAA,2DAAoC;AACpC,2DAAoC;AACpC,mDAA4B;AAC5B,yDAAkC;AAClC,qDAA8B;AAC9B,iEAA0C;AAU1C,SAAgB,MAAM,CACpB,KAA8B,EAC9B,OAAqC;IAErC,IAAI,YAAY,GAAa,EAAE,CAAA;IAE/B,YAAY,GAAG,YAAY,CAAC,MAAM,CAChC,mEAAiE,CAClE,CAAA;IAED,YAAY,GAAG,YAAY,CAAC,MAAM,CAChC,IAAA,iBAAO,EAAC,IAAA,aAAG,EAAC,KAAK,EAAE,UAAC,IAAI,IAAK,OAAA,eAAe,CAAC,IAAI,CAAC,EAArB,CAAqB,CAAC,CAAC,CACrD,CAAA;IAED,IAAI,OAAO,CAAC,uBAAuB,EAAE;QACnC,YAAY,GAAG,YAAY,CAAC,MAAM,CAChC,UAAU,CAAC,OAAO,CAAC,oBAAoB,EAAE,KAAK,CAAC,CAChD,CAAA;KACF;IAED,OAAO,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAA;AACzC,CAAC;AArBD,wBAqBC;AAED,SAAS,eAAe,CAAC,IAA2B;IAClD,IAAM,gBAAgB,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAA;IAC/C,IAAM,qBAAqB,GAAG,mBAAmB,CAAC,IAAI,CAAC,CAAA;IAEvD,OAAO,CAAC,gBAAgB,EAAE,qBAAqB,CAAC,CAAA;AAClD,CAAC;AAED,SAAS,gBAAgB,CAAC,IAA2B;IACnD,IAAM,iBAAiB,GAAG,oBAAoB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IACzD,IAAM,gBAAgB,GAAG,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAE3D,OAAO,2BAAoB,iBAAiB,2CACnC,IAAI,CAAC,IAAI,8BACN,gBAAgB,SAC5B,CAAA;AACF,CAAC;AAED,SAAS,mBAAmB,CAAC,IAA2B;IACtD,IAAM,QAAQ,GAAG,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAEnD,OAAO,sBAAe,QAAQ,qBAC5B,IAAA,aAAG,EAAC,IAAI,CAAC,UAAU,EAAE,UAAC,QAAQ,IAAK,OAAA,gBAAgB,CAAC,QAAQ,CAAC,EAA1B,CAA0B,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,SAC5E,CAAA;AACH,CAAC;AAED,SAAS,gBAAgB,CAAC,IAA4B;IACpD,IAAM,QAAQ,GAAG,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAC3C,OAAO,UAAG,IAAI,CAAC,IAAI,SAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,eAAK,QAAQ,QAAK,CAAA;AAClE,CAAC;AAED,SAAS,UAAU,CAAC,IAAY,EAAE,KAA8B;IAC9D,OAAO,2BAAoB,IAAI,yDAC7B,IAAA,aAAG,EAAC,KAAK,EAAE,UAAC,IAAI,IAAK,OAAA,kBAAkB,CAAC,IAAI,CAAC,EAAxB,CAAwB,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,QAC7D,CAAA;AACF,CAAC;AAED,SAAS,kBAAkB,CAAC,IAA2B;IACrD,IAAM,gBAAgB,GAAG,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAC3D,OAAO,UAAG,IAAI,CAAC,IAAI,wBAAc,gBAAgB,wBAAqB,CAAA;AACxE,CAAC;AAED,SAAS,eAAe,CAAC,IAAuB;IAC9C,IAAI,IAAA,iBAAO,EAAC,IAAI,CAAC,EAAE;QACjB,IAAM,SAAS,GAAG,IAAA,cAAI,EAAC,IAAA,aAAG,EAAC,IAAI,EAAE,UAAC,CAAC,IAAK,OAAA,aAAa,CAAC,CAAC,CAAC,EAAhB,CAAgB,CAAC,CAAC,CAAA;QAC1D,IAAM,UAAU,GAAG,IAAA,gBAAM,EAAC,SAAS,EAAE,UAAC,GAAG,EAAE,CAAC,IAAK,OAAA,GAAG,GAAG,KAAK,GAAG,CAAC,EAAf,CAAe,CAAC,CAAA;QACjE,OAAO,GAAG,GAAG,UAAU,GAAG,GAAG,CAAA;KAC9B;SAAM;QACL,OAAO,aAAa,CAAC,IAAI,CAAC,CAAA;KAC3B;AACH,CAAC;AAED,SAAS,aAAa,CAAC,IAAoC;IACzD,IAAI,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE;QACzB,OAAO,QAAQ,CAAA;KAChB;IACD,OAAO,oBAAoB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AACxC,CAAC;AAED,SAAS,oBAAoB,CAAC,QAAgB;IAC5C,OAAO,IAAA,oBAAU,EAAC,QAAQ,CAAC,GAAG,SAAS,CAAA;AACzC,CAAC;AAED,SAAS,uBAAuB,CAAC,QAAgB;IAC/C,OAAO,IAAA,oBAAU,EAAC,QAAQ,CAAC,GAAG,aAAa,CAAA;AAC7C,CAAC"}

View File

@@ -0,0 +1,19 @@
import type { Rule } from "@chevrotain/types";
export declare function buildModel(productions: Record<string, Rule>): CstNodeTypeDefinition[];
export type CstNodeTypeDefinition = {
name: string;
properties: PropertyTypeDefinition[];
};
export type PropertyTypeDefinition = {
name: string;
type: PropertyArrayType;
optional: boolean;
};
export type PropertyArrayType = TokenArrayType | RuleArrayType | (TokenArrayType | RuleArrayType)[];
export type TokenArrayType = {
kind: "token";
};
export type RuleArrayType = {
kind: "rule";
name: string;
};

View File

@@ -0,0 +1,129 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildModel = void 0;
var gast_1 = require("@chevrotain/gast");
var map_1 = __importDefault(require("lodash/map"));
var flatten_1 = __importDefault(require("lodash/flatten"));
var values_1 = __importDefault(require("lodash/values"));
var some_1 = __importDefault(require("lodash/some"));
var groupBy_1 = __importDefault(require("lodash/groupBy"));
var assign_1 = __importDefault(require("lodash/assign"));
function buildModel(productions) {
var generator = new CstNodeDefinitionGenerator();
var allRules = (0, values_1.default)(productions);
return (0, map_1.default)(allRules, function (rule) { return generator.visitRule(rule); });
}
exports.buildModel = buildModel;
var CstNodeDefinitionGenerator = /** @class */ (function (_super) {
__extends(CstNodeDefinitionGenerator, _super);
function CstNodeDefinitionGenerator() {
return _super !== null && _super.apply(this, arguments) || this;
}
CstNodeDefinitionGenerator.prototype.visitRule = function (node) {
var rawElements = this.visitEach(node.definition);
var grouped = (0, groupBy_1.default)(rawElements, function (el) { return el.propertyName; });
var properties = (0, map_1.default)(grouped, function (group, propertyName) {
var allNullable = !(0, some_1.default)(group, function (el) { return !el.canBeNull; });
// In an alternation with a label a property name can have
// multiple types.
var propertyType = group[0].type;
if (group.length > 1) {
propertyType = (0, map_1.default)(group, function (g) { return g.type; });
}
return {
name: propertyName,
type: propertyType,
optional: allNullable
};
});
return {
name: node.name,
properties: properties
};
};
CstNodeDefinitionGenerator.prototype.visitAlternative = function (node) {
return this.visitEachAndOverrideWith(node.definition, { canBeNull: true });
};
CstNodeDefinitionGenerator.prototype.visitOption = function (node) {
return this.visitEachAndOverrideWith(node.definition, { canBeNull: true });
};
CstNodeDefinitionGenerator.prototype.visitRepetition = function (node) {
return this.visitEachAndOverrideWith(node.definition, { canBeNull: true });
};
CstNodeDefinitionGenerator.prototype.visitRepetitionMandatory = function (node) {
return this.visitEach(node.definition);
};
CstNodeDefinitionGenerator.prototype.visitRepetitionMandatoryWithSeparator = function (node) {
return this.visitEach(node.definition).concat({
propertyName: node.separator.name,
canBeNull: true,
type: getType(node.separator)
});
};
CstNodeDefinitionGenerator.prototype.visitRepetitionWithSeparator = function (node) {
return this.visitEachAndOverrideWith(node.definition, {
canBeNull: true
}).concat({
propertyName: node.separator.name,
canBeNull: true,
type: getType(node.separator)
});
};
CstNodeDefinitionGenerator.prototype.visitAlternation = function (node) {
return this.visitEachAndOverrideWith(node.definition, { canBeNull: true });
};
CstNodeDefinitionGenerator.prototype.visitTerminal = function (node) {
return [
{
propertyName: node.label || node.terminalType.name,
canBeNull: false,
type: getType(node)
}
];
};
CstNodeDefinitionGenerator.prototype.visitNonTerminal = function (node) {
return [
{
propertyName: node.label || node.nonTerminalName,
canBeNull: false,
type: getType(node)
}
];
};
CstNodeDefinitionGenerator.prototype.visitEachAndOverrideWith = function (definition, override) {
return (0, map_1.default)(this.visitEach(definition), function (definition) { return (0, assign_1.default)({}, definition, override); });
};
CstNodeDefinitionGenerator.prototype.visitEach = function (definition) {
var _this = this;
return (0, flatten_1.default)((0, map_1.default)(definition, function (definition) { return _this.visit(definition); }));
};
return CstNodeDefinitionGenerator;
}(gast_1.GAstVisitor));
function getType(production) {
if (production instanceof gast_1.NonTerminal) {
return {
kind: "rule",
name: production.referencedRule.name
};
}
return { kind: "token" };
}
//# sourceMappingURL=model.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"model.js","sourceRoot":"","sources":["../../src/model.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;AAaA,yCAA2D;AAC3D,mDAA4B;AAC5B,2DAAoC;AACpC,yDAAkC;AAClC,qDAA8B;AAC9B,2DAAoC;AACpC,yDAAkC;AAElC,SAAgB,UAAU,CACxB,WAAiC;IAEjC,IAAM,SAAS,GAAG,IAAI,0BAA0B,EAAE,CAAA;IAClD,IAAM,QAAQ,GAAG,IAAA,gBAAM,EAAC,WAAW,CAAC,CAAA;IACpC,OAAO,IAAA,aAAG,EAAC,QAAQ,EAAE,UAAC,IAAI,IAAK,OAAA,SAAS,CAAC,SAAS,CAAC,IAAI,CAAC,EAAzB,CAAyB,CAAC,CAAA;AAC3D,CAAC;AAND,gCAMC;AAwBD;IAAyC,8CAAW;IAApD;;IA0GA,CAAC;IAzGC,8CAAS,GAAT,UAAU,IAAU;QAClB,IAAM,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;QAEnD,IAAM,OAAO,GAAG,IAAA,iBAAO,EAAC,WAAW,EAAE,UAAC,EAAE,IAAK,OAAA,EAAE,CAAC,YAAY,EAAf,CAAe,CAAC,CAAA;QAC7D,IAAM,UAAU,GAAG,IAAA,aAAG,EAAC,OAAO,EAAE,UAAC,KAAK,EAAE,YAAY;YAClD,IAAM,WAAW,GAAG,CAAC,IAAA,cAAI,EAAC,KAAK,EAAE,UAAC,EAAE,IAAK,OAAA,CAAC,EAAE,CAAC,SAAS,EAAb,CAAa,CAAC,CAAA;YAEvD,0DAA0D;YAC1D,kBAAkB;YAClB,IAAI,YAAY,GAAsB,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;YACnD,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;gBACpB,YAAY,GAAG,IAAA,aAAG,EAAC,KAAK,EAAE,UAAC,CAAC,IAAK,OAAA,CAAC,CAAC,IAAI,EAAN,CAAM,CAAC,CAAA;aACzC;YAED,OAAO;gBACL,IAAI,EAAE,YAAY;gBAClB,IAAI,EAAE,YAAY;gBAClB,QAAQ,EAAE,WAAW;aACI,CAAA;QAC7B,CAAC,CAAC,CAAA;QAEF,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,UAAU,EAAE,UAAU;SACvB,CAAA;IACH,CAAC;IAED,qDAAgB,GAAhB,UAAiB,IAAiB;QAChC,OAAO,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAA;IAC5E,CAAC;IAED,gDAAW,GAAX,UAAY,IAAY;QACtB,OAAO,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAA;IAC5E,CAAC;IAED,oDAAe,GAAf,UAAgB,IAAgB;QAC9B,OAAO,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAA;IAC5E,CAAC;IAED,6DAAwB,GAAxB,UAAyB,IAAyB;QAChD,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;IACxC,CAAC;IAED,0EAAqC,GAArC,UACE,IAAsC;QAEtC,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC;YAC5C,YAAY,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI;YACjC,SAAS,EAAE,IAAI;YACf,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC;SAC9B,CAAC,CAAA;IACJ,CAAC;IAED,iEAA4B,GAA5B,UAA6B,IAA6B;QACxD,OAAO,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,UAAU,EAAE;YACpD,SAAS,EAAE,IAAI;SAChB,CAAC,CAAC,MAAM,CAAC;YACR,YAAY,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI;YACjC,SAAS,EAAE,IAAI;YACf,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC;SAC9B,CAAC,CAAA;IACJ,CAAC;IAED,qDAAgB,GAAhB,UAAiB,IAAiB;QAChC,OAAO,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAA;IAC5E,CAAC;IAED,kDAAa,GAAb,UAAc,IAAc;QAC1B,OAAO;YACL;gBACE,YAAY,EAAE,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,YAAY,CAAC,IAAI;gBAClD,SAAS,EAAE,KAAK;gBAChB,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC;aACpB;SACF,CAAA;IACH,CAAC;IAED,qDAAgB,GAAhB,UAAiB,IAAiB;QAChC,OAAO;YACL;gBACE,YAAY,EAAE,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,eAAe;gBAChD,SAAS,EAAE,KAAK;gBAChB,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC;aACpB;SACF,CAAA;IACH,CAAC;IAEO,6DAAwB,GAAhC,UACE,UAAyB,EACzB,QAAuC;QAEvC,OAAO,IAAA,aAAG,EACR,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,EAC1B,UAAC,UAAU,IAAK,OAAA,IAAA,gBAAM,EAAC,EAAE,EAAE,UAAU,EAAE,QAAQ,CAAyB,EAAxD,CAAwD,CACzE,CAAA;IACH,CAAC;IAEO,8CAAS,GAAjB,UAAkB,UAAyB;QAA3C,iBAOC;QANC,OAAO,IAAA,iBAAO,EACZ,IAAA,aAAG,EACD,UAAU,EACV,UAAC,UAAU,IAAK,OAAA,KAAI,CAAC,KAAK,CAAC,UAAU,CAA2B,EAAhD,CAAgD,CACjE,CACF,CAAA;IACH,CAAC;IACH,iCAAC;AAAD,CAAC,AA1GD,CAAyC,kBAAW,GA0GnD;AAQD,SAAS,OAAO,CACd,UAA8C;IAE9C,IAAI,UAAU,YAAY,kBAAW,EAAE;QACrC,OAAO;YACL,IAAI,EAAE,MAAM;YACZ,IAAI,EAAE,UAAU,CAAC,cAAc,CAAC,IAAI;SACrC,CAAA;KACF;IAED,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAA;AAC1B,CAAC"}

View File

@@ -0,0 +1,44 @@
{
"name": "@chevrotain/cst-dts-gen",
"version": "10.5.0",
"description": "Generates type definitions for chevrotain CST nodes",
"keywords": [],
"bugs": {
"url": "https://github.com/Chevrotain/chevrotain/issues"
},
"license": "Apache-2.0",
"typings": "lib/src/api.d.ts",
"main": "lib/src/api.js",
"files": [
"src/**/*.ts",
"lib/src/**/*.js",
"lib/src/**/*.d.ts",
"lib/src/**/*.js.map"
],
"repository": {
"type": "git",
"url": "git://github.com/Chevrotain/chevrotain.git"
},
"scripts": {
"---------- CI FLOWS --------": "",
"ci": "pnpm run build test",
"build": "npm-run-all clean compile",
"test": "echo \"tests are in a different package\"",
"---------- BUILD STEPS --------": "",
"clean": "shx rm -rf lib",
"compile:watch": "tsc -w",
"compile": "tsc"
},
"dependencies": {
"@chevrotain/gast": "10.5.0",
"@chevrotain/types": "10.5.0",
"lodash": "4.17.21"
},
"devDependencies": {
"@types/lodash": "4.14.191"
},
"publishConfig": {
"access": "public"
},
"gitHead": "f5fdf95b8da570c702753252b0a3f7aa34d64f3b"
}

View File

@@ -0,0 +1,22 @@
import { Rule, GenerateDtsOptions } from "@chevrotain/types"
import { buildModel } from "./model"
import { genDts } from "./generate"
const defaultOptions: Required<GenerateDtsOptions> = {
includeVisitorInterface: true,
visitorInterfaceName: "ICstNodeVisitor"
}
export function generateCstDts(
productions: Record<string, Rule>,
options?: GenerateDtsOptions
): string {
const effectiveOptions = {
...defaultOptions,
...options
}
const model = buildModel(productions)
return genDts(model, effectiveOptions)
}

View File

@@ -0,0 +1,103 @@
import flatten from "lodash/flatten"
import isArray from "lodash/isArray"
import map from "lodash/map"
import reduce from "lodash/reduce"
import uniq from "lodash/uniq"
import upperFirst from "lodash/upperFirst"
import { GenerateDtsOptions } from "@chevrotain/types"
import {
CstNodeTypeDefinition,
PropertyTypeDefinition,
PropertyArrayType,
TokenArrayType,
RuleArrayType
} from "./model"
export function genDts(
model: CstNodeTypeDefinition[],
options: Required<GenerateDtsOptions>
): string {
let contentParts: string[] = []
contentParts = contentParts.concat(
`import type { CstNode, ICstVisitor, IToken } from "chevrotain";`
)
contentParts = contentParts.concat(
flatten(map(model, (node) => genCstNodeTypes(node)))
)
if (options.includeVisitorInterface) {
contentParts = contentParts.concat(
genVisitor(options.visitorInterfaceName, model)
)
}
return contentParts.join("\n\n") + "\n"
}
function genCstNodeTypes(node: CstNodeTypeDefinition) {
const nodeCstInterface = genNodeInterface(node)
const nodeChildrenInterface = genNodeChildrenType(node)
return [nodeCstInterface, nodeChildrenInterface]
}
function genNodeInterface(node: CstNodeTypeDefinition) {
const nodeInterfaceName = getNodeInterfaceName(node.name)
const childrenTypeName = getNodeChildrenTypeName(node.name)
return `export interface ${nodeInterfaceName} extends CstNode {
name: "${node.name}";
children: ${childrenTypeName};
}`
}
function genNodeChildrenType(node: CstNodeTypeDefinition) {
const typeName = getNodeChildrenTypeName(node.name)
return `export type ${typeName} = {
${map(node.properties, (property) => genChildProperty(property)).join("\n ")}
};`
}
function genChildProperty(prop: PropertyTypeDefinition) {
const typeName = buildTypeString(prop.type)
return `${prop.name}${prop.optional ? "?" : ""}: ${typeName}[];`
}
function genVisitor(name: string, nodes: CstNodeTypeDefinition[]) {
return `export interface ${name}<IN, OUT> extends ICstVisitor<IN, OUT> {
${map(nodes, (node) => genVisitorFunction(node)).join("\n ")}
}`
}
function genVisitorFunction(node: CstNodeTypeDefinition) {
const childrenTypeName = getNodeChildrenTypeName(node.name)
return `${node.name}(children: ${childrenTypeName}, param?: IN): OUT;`
}
function buildTypeString(type: PropertyArrayType) {
if (isArray(type)) {
const typeNames = uniq(map(type, (t) => getTypeString(t)))
const typeString = reduce(typeNames, (sum, t) => sum + " | " + t)
return "(" + typeString + ")"
} else {
return getTypeString(type)
}
}
function getTypeString(type: TokenArrayType | RuleArrayType) {
if (type.kind === "token") {
return "IToken"
}
return getNodeInterfaceName(type.name)
}
function getNodeInterfaceName(ruleName: string) {
return upperFirst(ruleName) + "CstNode"
}
function getNodeChildrenTypeName(ruleName: string) {
return upperFirst(ruleName) + "CstChildren"
}

View File

@@ -0,0 +1,177 @@
import type {
Alternation,
Alternative,
IProduction,
Option,
Repetition,
RepetitionMandatory,
RepetitionMandatoryWithSeparator,
RepetitionWithSeparator,
Rule,
Terminal,
TokenType
} from "@chevrotain/types"
import { NonTerminal, GAstVisitor } from "@chevrotain/gast"
import map from "lodash/map"
import flatten from "lodash/flatten"
import values from "lodash/values"
import some from "lodash/some"
import groupBy from "lodash/groupBy"
import assign from "lodash/assign"
export function buildModel(
productions: Record<string, Rule>
): CstNodeTypeDefinition[] {
const generator = new CstNodeDefinitionGenerator()
const allRules = values(productions)
return map(allRules, (rule) => generator.visitRule(rule))
}
export type CstNodeTypeDefinition = {
name: string
properties: PropertyTypeDefinition[]
}
export type PropertyTypeDefinition = {
name: string
type: PropertyArrayType
optional: boolean
}
export type PropertyArrayType =
| TokenArrayType
| RuleArrayType
| (TokenArrayType | RuleArrayType)[]
export type TokenArrayType = { kind: "token" }
export type RuleArrayType = {
kind: "rule"
name: string
}
class CstNodeDefinitionGenerator extends GAstVisitor {
visitRule(node: Rule): CstNodeTypeDefinition {
const rawElements = this.visitEach(node.definition)
const grouped = groupBy(rawElements, (el) => el.propertyName)
const properties = map(grouped, (group, propertyName) => {
const allNullable = !some(group, (el) => !el.canBeNull)
// In an alternation with a label a property name can have
// multiple types.
let propertyType: PropertyArrayType = group[0].type
if (group.length > 1) {
propertyType = map(group, (g) => g.type)
}
return {
name: propertyName,
type: propertyType,
optional: allNullable
} as PropertyTypeDefinition
})
return {
name: node.name,
properties: properties
}
}
visitAlternative(node: Alternative) {
return this.visitEachAndOverrideWith(node.definition, { canBeNull: true })
}
visitOption(node: Option) {
return this.visitEachAndOverrideWith(node.definition, { canBeNull: true })
}
visitRepetition(node: Repetition) {
return this.visitEachAndOverrideWith(node.definition, { canBeNull: true })
}
visitRepetitionMandatory(node: RepetitionMandatory) {
return this.visitEach(node.definition)
}
visitRepetitionMandatoryWithSeparator(
node: RepetitionMandatoryWithSeparator
) {
return this.visitEach(node.definition).concat({
propertyName: node.separator.name,
canBeNull: true,
type: getType(node.separator)
})
}
visitRepetitionWithSeparator(node: RepetitionWithSeparator) {
return this.visitEachAndOverrideWith(node.definition, {
canBeNull: true
}).concat({
propertyName: node.separator.name,
canBeNull: true,
type: getType(node.separator)
})
}
visitAlternation(node: Alternation) {
return this.visitEachAndOverrideWith(node.definition, { canBeNull: true })
}
visitTerminal(node: Terminal): PropertyTupleElement[] {
return [
{
propertyName: node.label || node.terminalType.name,
canBeNull: false,
type: getType(node)
}
]
}
visitNonTerminal(node: NonTerminal): PropertyTupleElement[] {
return [
{
propertyName: node.label || node.nonTerminalName,
canBeNull: false,
type: getType(node)
}
]
}
private visitEachAndOverrideWith(
definition: IProduction[],
override: Partial<PropertyTupleElement>
) {
return map(
this.visitEach(definition),
(definition) => assign({}, definition, override) as PropertyTupleElement
)
}
private visitEach(definition: IProduction[]) {
return flatten<PropertyTupleElement>(
map(
definition,
(definition) => this.visit(definition) as PropertyTupleElement[]
)
)
}
}
type PropertyTupleElement = {
propertyName: string
canBeNull: boolean
type: TokenArrayType | RuleArrayType
}
function getType(
production: Terminal | NonTerminal | TokenType
): TokenArrayType | RuleArrayType {
if (production instanceof NonTerminal) {
return {
kind: "rule",
name: production.referencedRule.name
}
}
return { kind: "token" }
}

202
_node_modules/@chevrotain/gast/LICENSE.txt generated Normal file
View File

@@ -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.

3
_node_modules/@chevrotain/gast/lib/src/api.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
export { Rule, Terminal, NonTerminal, Option, Repetition, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator, Alternation, Alternative, serializeGrammar, serializeProduction } from "./model";
export { GAstVisitor } from "./visitor";
export { getProductionDslName, isOptionalProd, isBranchingProd, isSequenceProd } from "./helpers";

View File

@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isSequenceProd = exports.isBranchingProd = exports.isOptionalProd = exports.getProductionDslName = exports.GAstVisitor = exports.serializeProduction = exports.serializeGrammar = exports.Alternative = exports.Alternation = exports.RepetitionWithSeparator = exports.RepetitionMandatoryWithSeparator = exports.RepetitionMandatory = exports.Repetition = exports.Option = exports.NonTerminal = exports.Terminal = exports.Rule = void 0;
var model_1 = require("./model");
Object.defineProperty(exports, "Rule", { enumerable: true, get: function () { return model_1.Rule; } });
Object.defineProperty(exports, "Terminal", { enumerable: true, get: function () { return model_1.Terminal; } });
Object.defineProperty(exports, "NonTerminal", { enumerable: true, get: function () { return model_1.NonTerminal; } });
Object.defineProperty(exports, "Option", { enumerable: true, get: function () { return model_1.Option; } });
Object.defineProperty(exports, "Repetition", { enumerable: true, get: function () { return model_1.Repetition; } });
Object.defineProperty(exports, "RepetitionMandatory", { enumerable: true, get: function () { return model_1.RepetitionMandatory; } });
Object.defineProperty(exports, "RepetitionMandatoryWithSeparator", { enumerable: true, get: function () { return model_1.RepetitionMandatoryWithSeparator; } });
Object.defineProperty(exports, "RepetitionWithSeparator", { enumerable: true, get: function () { return model_1.RepetitionWithSeparator; } });
Object.defineProperty(exports, "Alternation", { enumerable: true, get: function () { return model_1.Alternation; } });
Object.defineProperty(exports, "Alternative", { enumerable: true, get: function () { return model_1.Alternative; } });
Object.defineProperty(exports, "serializeGrammar", { enumerable: true, get: function () { return model_1.serializeGrammar; } });
Object.defineProperty(exports, "serializeProduction", { enumerable: true, get: function () { return model_1.serializeProduction; } });
var visitor_1 = require("./visitor");
Object.defineProperty(exports, "GAstVisitor", { enumerable: true, get: function () { return visitor_1.GAstVisitor; } });
var helpers_1 = require("./helpers");
Object.defineProperty(exports, "getProductionDslName", { enumerable: true, get: function () { return helpers_1.getProductionDslName; } });
Object.defineProperty(exports, "isOptionalProd", { enumerable: true, get: function () { return helpers_1.isOptionalProd; } });
Object.defineProperty(exports, "isBranchingProd", { enumerable: true, get: function () { return helpers_1.isBranchingProd; } });
Object.defineProperty(exports, "isSequenceProd", { enumerable: true, get: function () { return helpers_1.isSequenceProd; } });
//# sourceMappingURL=api.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/api.ts"],"names":[],"mappings":";;;AAAA,iCAagB;AAZd,6FAAA,IAAI,OAAA;AACJ,iGAAA,QAAQ,OAAA;AACR,oGAAA,WAAW,OAAA;AACX,+FAAA,MAAM,OAAA;AACN,mGAAA,UAAU,OAAA;AACV,4GAAA,mBAAmB,OAAA;AACnB,yHAAA,gCAAgC,OAAA;AAChC,gHAAA,uBAAuB,OAAA;AACvB,oGAAA,WAAW,OAAA;AACX,oGAAA,WAAW,OAAA;AACX,yGAAA,gBAAgB,OAAA;AAChB,4GAAA,mBAAmB,OAAA;AAGrB,qCAAuC;AAA9B,sGAAA,WAAW,OAAA;AAEpB,qCAKkB;AAJhB,+GAAA,oBAAoB,OAAA;AACpB,yGAAA,cAAc,OAAA;AACd,0GAAA,eAAe,OAAA;AACf,yGAAA,cAAc,OAAA"}

10
_node_modules/@chevrotain/gast/lib/src/helpers.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import { NonTerminal } from "./model";
import { IProduction, IProductionWithOccurrence } from "@chevrotain/types";
export declare function isSequenceProd(prod: IProduction): prod is {
definition: IProduction[];
} & IProduction;
export declare function isOptionalProd(prod: IProduction, alreadyVisited?: NonTerminal[]): boolean;
export declare function isBranchingProd(prod: IProduction): prod is {
definition: IProduction[];
} & IProduction;
export declare function getProductionDslName(prod: IProductionWithOccurrence): string;

View File

@@ -0,0 +1,91 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getProductionDslName = exports.isBranchingProd = exports.isOptionalProd = exports.isSequenceProd = void 0;
var some_1 = __importDefault(require("lodash/some"));
var every_1 = __importDefault(require("lodash/every"));
var includes_1 = __importDefault(require("lodash/includes"));
var model_1 = require("./model");
function isSequenceProd(prod) {
return (prod instanceof model_1.Alternative ||
prod instanceof model_1.Option ||
prod instanceof model_1.Repetition ||
prod instanceof model_1.RepetitionMandatory ||
prod instanceof model_1.RepetitionMandatoryWithSeparator ||
prod instanceof model_1.RepetitionWithSeparator ||
prod instanceof model_1.Terminal ||
prod instanceof model_1.Rule);
}
exports.isSequenceProd = isSequenceProd;
function isOptionalProd(prod, alreadyVisited) {
if (alreadyVisited === void 0) { alreadyVisited = []; }
var isDirectlyOptional = prod instanceof model_1.Option ||
prod instanceof model_1.Repetition ||
prod instanceof model_1.RepetitionWithSeparator;
if (isDirectlyOptional) {
return true;
}
// note that this can cause infinite loop if one optional empty TOP production has a cyclic dependency with another
// empty optional top rule
// may be indirectly optional ((A?B?C?) | (D?E?F?))
if (prod instanceof model_1.Alternation) {
// for OR its enough for just one of the alternatives to be optional
return (0, some_1.default)(prod.definition, function (subProd) {
return isOptionalProd(subProd, alreadyVisited);
});
}
else if (prod instanceof model_1.NonTerminal && (0, includes_1.default)(alreadyVisited, prod)) {
// avoiding stack overflow due to infinite recursion
return false;
}
else if (prod instanceof model_1.AbstractProduction) {
if (prod instanceof model_1.NonTerminal) {
alreadyVisited.push(prod);
}
return (0, every_1.default)(prod.definition, function (subProd) {
return isOptionalProd(subProd, alreadyVisited);
});
}
else {
return false;
}
}
exports.isOptionalProd = isOptionalProd;
function isBranchingProd(prod) {
return prod instanceof model_1.Alternation;
}
exports.isBranchingProd = isBranchingProd;
function getProductionDslName(prod) {
/* istanbul ignore else */
if (prod instanceof model_1.NonTerminal) {
return "SUBRULE";
}
else if (prod instanceof model_1.Option) {
return "OPTION";
}
else if (prod instanceof model_1.Alternation) {
return "OR";
}
else if (prod instanceof model_1.RepetitionMandatory) {
return "AT_LEAST_ONE";
}
else if (prod instanceof model_1.RepetitionMandatoryWithSeparator) {
return "AT_LEAST_ONE_SEP";
}
else if (prod instanceof model_1.RepetitionWithSeparator) {
return "MANY_SEP";
}
else if (prod instanceof model_1.Repetition) {
return "MANY";
}
else if (prod instanceof model_1.Terminal) {
return "CONSUME";
}
else {
throw Error("non exhaustive match");
}
}
exports.getProductionDslName = getProductionDslName;
//# sourceMappingURL=helpers.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/helpers.ts"],"names":[],"mappings":";;;;;;AAAA,qDAA8B;AAC9B,uDAAgC;AAEhC,6DAAsC;AACtC,iCAYgB;AAIhB,SAAgB,cAAc,CAC5B,IAAiB;IAEjB,OAAO,CACL,IAAI,YAAY,mBAAW;QAC3B,IAAI,YAAY,cAAM;QACtB,IAAI,YAAY,kBAAU;QAC1B,IAAI,YAAY,2BAAmB;QACnC,IAAI,YAAY,wCAAgC;QAChD,IAAI,YAAY,+BAAuB;QACvC,IAAI,YAAY,gBAAQ;QACxB,IAAI,YAAY,YAAI,CACrB,CAAA;AACH,CAAC;AAbD,wCAaC;AAED,SAAgB,cAAc,CAC5B,IAAiB,EACjB,cAAkC;IAAlC,+BAAA,EAAA,mBAAkC;IAElC,IAAM,kBAAkB,GACtB,IAAI,YAAY,cAAM;QACtB,IAAI,YAAY,kBAAU;QAC1B,IAAI,YAAY,+BAAuB,CAAA;IACzC,IAAI,kBAAkB,EAAE;QACtB,OAAO,IAAI,CAAA;KACZ;IAED,mHAAmH;IACnH,0BAA0B;IAC1B,mDAAmD;IACnD,IAAI,IAAI,YAAY,mBAAW,EAAE;QAC/B,oEAAoE;QACpE,OAAO,IAAA,cAAI,EAAe,IAAK,CAAC,UAAU,EAAE,UAAC,OAAoB;YAC/D,OAAO,cAAc,CAAC,OAAO,EAAE,cAAc,CAAC,CAAA;QAChD,CAAC,CAAC,CAAA;KACH;SAAM,IAAI,IAAI,YAAY,mBAAW,IAAI,IAAA,kBAAQ,EAAC,cAAc,EAAE,IAAI,CAAC,EAAE;QACxE,oDAAoD;QACpD,OAAO,KAAK,CAAA;KACb;SAAM,IAAI,IAAI,YAAY,0BAAkB,EAAE;QAC7C,IAAI,IAAI,YAAY,mBAAW,EAAE;YAC/B,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;SAC1B;QACD,OAAO,IAAA,eAAK,EACW,IAAK,CAAC,UAAU,EACrC,UAAC,OAAoB;YACnB,OAAO,cAAc,CAAC,OAAO,EAAE,cAAc,CAAC,CAAA;QAChD,CAAC,CACF,CAAA;KACF;SAAM;QACL,OAAO,KAAK,CAAA;KACb;AACH,CAAC;AApCD,wCAoCC;AAED,SAAgB,eAAe,CAC7B,IAAiB;IAEjB,OAAO,IAAI,YAAY,mBAAW,CAAA;AACpC,CAAC;AAJD,0CAIC;AAED,SAAgB,oBAAoB,CAAC,IAA+B;IAClE,0BAA0B;IAC1B,IAAI,IAAI,YAAY,mBAAW,EAAE;QAC/B,OAAO,SAAS,CAAA;KACjB;SAAM,IAAI,IAAI,YAAY,cAAM,EAAE;QACjC,OAAO,QAAQ,CAAA;KAChB;SAAM,IAAI,IAAI,YAAY,mBAAW,EAAE;QACtC,OAAO,IAAI,CAAA;KACZ;SAAM,IAAI,IAAI,YAAY,2BAAmB,EAAE;QAC9C,OAAO,cAAc,CAAA;KACtB;SAAM,IAAI,IAAI,YAAY,wCAAgC,EAAE;QAC3D,OAAO,kBAAkB,CAAA;KAC1B;SAAM,IAAI,IAAI,YAAY,+BAAuB,EAAE;QAClD,OAAO,UAAU,CAAA;KAClB;SAAM,IAAI,IAAI,YAAY,kBAAU,EAAE;QACrC,OAAO,MAAM,CAAA;KACd;SAAM,IAAI,IAAI,YAAY,gBAAQ,EAAE;QACnC,OAAO,SAAS,CAAA;KACjB;SAAM;QACL,MAAM,KAAK,CAAC,sBAAsB,CAAC,CAAA;KACpC;AACH,CAAC;AArBD,oDAqBC"}

144
_node_modules/@chevrotain/gast/lib/src/model.d.ts generated vendored Normal file
View File

@@ -0,0 +1,144 @@
import { IGASTVisitor, IProduction, IProductionWithOccurrence, ISerializedGast, TokenType } from "@chevrotain/types";
export declare abstract class AbstractProduction<T extends IProduction = IProduction> implements IProduction {
protected _definition: T[];
get definition(): T[];
set definition(value: T[]);
constructor(_definition: T[]);
accept(visitor: IGASTVisitor): void;
}
export declare class NonTerminal extends AbstractProduction implements IProductionWithOccurrence {
nonTerminalName: string;
label?: string;
referencedRule: Rule;
idx: number;
constructor(options: {
nonTerminalName: string;
label?: string;
referencedRule?: Rule;
idx?: number;
});
set definition(definition: IProduction[]);
get definition(): IProduction[];
accept(visitor: IGASTVisitor): void;
}
export declare class Rule extends AbstractProduction {
name: string;
orgText: string;
constructor(options: {
name: string;
definition: IProduction[];
orgText?: string;
});
}
export declare class Alternative extends AbstractProduction {
ignoreAmbiguities: boolean;
constructor(options: {
definition: IProduction[];
ignoreAmbiguities?: boolean;
});
}
export declare class Option extends AbstractProduction implements IProductionWithOccurrence {
idx: number;
maxLookahead?: number;
constructor(options: {
definition: IProduction[];
idx?: number;
maxLookahead?: number;
});
}
export declare class RepetitionMandatory extends AbstractProduction implements IProductionWithOccurrence {
idx: number;
maxLookahead?: number;
constructor(options: {
definition: IProduction[];
idx?: number;
maxLookahead?: number;
});
}
export declare class RepetitionMandatoryWithSeparator extends AbstractProduction implements IProductionWithOccurrence {
separator: TokenType;
idx: number;
maxLookahead?: number;
constructor(options: {
definition: IProduction[];
separator: TokenType;
idx?: number;
});
}
export declare class Repetition extends AbstractProduction implements IProductionWithOccurrence {
separator: TokenType;
idx: number;
maxLookahead?: number;
constructor(options: {
definition: IProduction[];
idx?: number;
maxLookahead?: number;
});
}
export declare class RepetitionWithSeparator extends AbstractProduction implements IProductionWithOccurrence {
separator: TokenType;
idx: number;
maxLookahead?: number;
constructor(options: {
definition: IProduction[];
separator: TokenType;
idx?: number;
});
}
export declare class Alternation extends AbstractProduction<Alternative> implements IProductionWithOccurrence {
idx: number;
ignoreAmbiguities: boolean;
hasPredicates: boolean;
maxLookahead?: number;
get definition(): Alternative[];
set definition(value: Alternative[]);
constructor(options: {
definition: Alternative[];
idx?: number;
ignoreAmbiguities?: boolean;
hasPredicates?: boolean;
maxLookahead?: number;
});
}
export declare class Terminal implements IProductionWithOccurrence {
terminalType: TokenType;
label?: string;
idx: number;
constructor(options: {
terminalType: TokenType;
label?: string;
idx?: number;
});
accept(visitor: IGASTVisitor): void;
}
export interface ISerializedBasic extends ISerializedGast {
type: "Alternative" | "Option" | "RepetitionMandatory" | "Repetition" | "Alternation";
idx?: number;
}
export interface ISerializedGastRule extends ISerializedGast {
type: "Rule";
name: string;
orgText: string;
}
export interface ISerializedNonTerminal extends ISerializedGast {
type: "NonTerminal";
name: string;
label?: string;
idx: number;
}
export interface ISerializedTerminal extends ISerializedGast {
type: "Terminal";
name: string;
terminalLabel?: string;
label?: string;
pattern?: string;
idx: number;
}
export interface ISerializedTerminalWithSeparator extends ISerializedGast {
type: "RepetitionMandatoryWithSeparator" | "RepetitionWithSeparator";
idx: number;
separator: ISerializedTerminal;
}
export type ISerializedGastAny = ISerializedBasic | ISerializedGastRule | ISerializedNonTerminal | ISerializedTerminal | ISerializedTerminalWithSeparator;
export declare function serializeGrammar(topRules: Rule[]): ISerializedGast[];
export declare function serializeProduction(node: IProduction): ISerializedGast;

View File

@@ -0,0 +1,304 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.serializeProduction = exports.serializeGrammar = exports.Terminal = exports.Alternation = exports.RepetitionWithSeparator = exports.Repetition = exports.RepetitionMandatoryWithSeparator = exports.RepetitionMandatory = exports.Option = exports.Alternative = exports.Rule = exports.NonTerminal = exports.AbstractProduction = void 0;
var map_1 = __importDefault(require("lodash/map"));
var forEach_1 = __importDefault(require("lodash/forEach"));
var isString_1 = __importDefault(require("lodash/isString"));
var isRegExp_1 = __importDefault(require("lodash/isRegExp"));
var pickBy_1 = __importDefault(require("lodash/pickBy"));
var assign_1 = __importDefault(require("lodash/assign"));
// TODO: duplicated code to avoid extracting another sub-package -- how to avoid?
function tokenLabel(tokType) {
if (hasTokenLabel(tokType)) {
return tokType.LABEL;
}
else {
return tokType.name;
}
}
// TODO: duplicated code to avoid extracting another sub-package -- how to avoid?
function hasTokenLabel(obj) {
return (0, isString_1.default)(obj.LABEL) && obj.LABEL !== "";
}
var AbstractProduction = /** @class */ (function () {
function AbstractProduction(_definition) {
this._definition = _definition;
}
Object.defineProperty(AbstractProduction.prototype, "definition", {
get: function () {
return this._definition;
},
set: function (value) {
this._definition = value;
},
enumerable: false,
configurable: true
});
AbstractProduction.prototype.accept = function (visitor) {
visitor.visit(this);
(0, forEach_1.default)(this.definition, function (prod) {
prod.accept(visitor);
});
};
return AbstractProduction;
}());
exports.AbstractProduction = AbstractProduction;
var NonTerminal = /** @class */ (function (_super) {
__extends(NonTerminal, _super);
function NonTerminal(options) {
var _this = _super.call(this, []) || this;
_this.idx = 1;
(0, assign_1.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; }));
return _this;
}
Object.defineProperty(NonTerminal.prototype, "definition", {
get: function () {
if (this.referencedRule !== undefined) {
return this.referencedRule.definition;
}
return [];
},
set: function (definition) {
// immutable
},
enumerable: false,
configurable: true
});
NonTerminal.prototype.accept = function (visitor) {
visitor.visit(this);
// don't visit children of a reference, we will get cyclic infinite loops if we do so
};
return NonTerminal;
}(AbstractProduction));
exports.NonTerminal = NonTerminal;
var Rule = /** @class */ (function (_super) {
__extends(Rule, _super);
function Rule(options) {
var _this = _super.call(this, options.definition) || this;
_this.orgText = "";
(0, assign_1.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; }));
return _this;
}
return Rule;
}(AbstractProduction));
exports.Rule = Rule;
var Alternative = /** @class */ (function (_super) {
__extends(Alternative, _super);
function Alternative(options) {
var _this = _super.call(this, options.definition) || this;
_this.ignoreAmbiguities = false;
(0, assign_1.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; }));
return _this;
}
return Alternative;
}(AbstractProduction));
exports.Alternative = Alternative;
var Option = /** @class */ (function (_super) {
__extends(Option, _super);
function Option(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
(0, assign_1.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; }));
return _this;
}
return Option;
}(AbstractProduction));
exports.Option = Option;
var RepetitionMandatory = /** @class */ (function (_super) {
__extends(RepetitionMandatory, _super);
function RepetitionMandatory(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
(0, assign_1.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; }));
return _this;
}
return RepetitionMandatory;
}(AbstractProduction));
exports.RepetitionMandatory = RepetitionMandatory;
var RepetitionMandatoryWithSeparator = /** @class */ (function (_super) {
__extends(RepetitionMandatoryWithSeparator, _super);
function RepetitionMandatoryWithSeparator(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
(0, assign_1.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; }));
return _this;
}
return RepetitionMandatoryWithSeparator;
}(AbstractProduction));
exports.RepetitionMandatoryWithSeparator = RepetitionMandatoryWithSeparator;
var Repetition = /** @class */ (function (_super) {
__extends(Repetition, _super);
function Repetition(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
(0, assign_1.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; }));
return _this;
}
return Repetition;
}(AbstractProduction));
exports.Repetition = Repetition;
var RepetitionWithSeparator = /** @class */ (function (_super) {
__extends(RepetitionWithSeparator, _super);
function RepetitionWithSeparator(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
(0, assign_1.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; }));
return _this;
}
return RepetitionWithSeparator;
}(AbstractProduction));
exports.RepetitionWithSeparator = RepetitionWithSeparator;
var Alternation = /** @class */ (function (_super) {
__extends(Alternation, _super);
function Alternation(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
_this.ignoreAmbiguities = false;
_this.hasPredicates = false;
(0, assign_1.default)(_this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; }));
return _this;
}
Object.defineProperty(Alternation.prototype, "definition", {
get: function () {
return this._definition;
},
set: function (value) {
this._definition = value;
},
enumerable: false,
configurable: true
});
return Alternation;
}(AbstractProduction));
exports.Alternation = Alternation;
var Terminal = /** @class */ (function () {
function Terminal(options) {
this.idx = 1;
(0, assign_1.default)(this, (0, pickBy_1.default)(options, function (v) { return v !== undefined; }));
}
Terminal.prototype.accept = function (visitor) {
visitor.visit(this);
};
return Terminal;
}());
exports.Terminal = Terminal;
function serializeGrammar(topRules) {
return (0, map_1.default)(topRules, serializeProduction);
}
exports.serializeGrammar = serializeGrammar;
function serializeProduction(node) {
function convertDefinition(definition) {
return (0, map_1.default)(definition, serializeProduction);
}
/* istanbul ignore else */
if (node instanceof NonTerminal) {
var serializedNonTerminal = {
type: "NonTerminal",
name: node.nonTerminalName,
idx: node.idx
};
if ((0, isString_1.default)(node.label)) {
serializedNonTerminal.label = node.label;
}
return serializedNonTerminal;
}
else if (node instanceof Alternative) {
return {
type: "Alternative",
definition: convertDefinition(node.definition)
};
}
else if (node instanceof Option) {
return {
type: "Option",
idx: node.idx,
definition: convertDefinition(node.definition)
};
}
else if (node instanceof RepetitionMandatory) {
return {
type: "RepetitionMandatory",
idx: node.idx,
definition: convertDefinition(node.definition)
};
}
else if (node instanceof RepetitionMandatoryWithSeparator) {
return {
type: "RepetitionMandatoryWithSeparator",
idx: node.idx,
separator: (serializeProduction(new Terminal({ terminalType: node.separator }))),
definition: convertDefinition(node.definition)
};
}
else if (node instanceof RepetitionWithSeparator) {
return {
type: "RepetitionWithSeparator",
idx: node.idx,
separator: (serializeProduction(new Terminal({ terminalType: node.separator }))),
definition: convertDefinition(node.definition)
};
}
else if (node instanceof Repetition) {
return {
type: "Repetition",
idx: node.idx,
definition: convertDefinition(node.definition)
};
}
else if (node instanceof Alternation) {
return {
type: "Alternation",
idx: node.idx,
definition: convertDefinition(node.definition)
};
}
else if (node instanceof Terminal) {
var serializedTerminal = {
type: "Terminal",
name: node.terminalType.name,
label: tokenLabel(node.terminalType),
idx: node.idx
};
if ((0, isString_1.default)(node.label)) {
serializedTerminal.terminalLabel = node.label;
}
var pattern = node.terminalType.PATTERN;
if (node.terminalType.PATTERN) {
serializedTerminal.pattern = (0, isRegExp_1.default)(pattern)
? pattern.source
: pattern;
}
return serializedTerminal;
}
else if (node instanceof Rule) {
return {
type: "Rule",
name: node.name,
orgText: node.orgText,
definition: convertDefinition(node.definition)
};
}
else {
throw Error("non exhaustive match");
}
}
exports.serializeProduction = serializeProduction;
//# sourceMappingURL=model.js.map

File diff suppressed because one or more lines are too long

15
_node_modules/@chevrotain/gast/lib/src/visitor.d.ts generated vendored Normal file
View File

@@ -0,0 +1,15 @@
import { Alternation, Alternative, NonTerminal, Option, Repetition, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator, Rule, Terminal } from "./model";
import { IProduction } from "@chevrotain/types";
export declare abstract class GAstVisitor {
visit(node: IProduction): any;
visitNonTerminal(node: NonTerminal): any;
visitAlternative(node: Alternative): any;
visitOption(node: Option): any;
visitRepetition(node: Repetition): any;
visitRepetitionMandatory(node: RepetitionMandatory): any;
visitRepetitionMandatoryWithSeparator(node: RepetitionMandatoryWithSeparator): any;
visitRepetitionWithSeparator(node: RepetitionWithSeparator): any;
visitAlternation(node: Alternation): any;
visitTerminal(node: Terminal): any;
visitRule(node: Rule): any;
}

View File

@@ -0,0 +1,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GAstVisitor = void 0;
var model_1 = require("./model");
var GAstVisitor = /** @class */ (function () {
function GAstVisitor() {
}
GAstVisitor.prototype.visit = function (node) {
var nodeAny = node;
switch (nodeAny.constructor) {
case model_1.NonTerminal:
return this.visitNonTerminal(nodeAny);
case model_1.Alternative:
return this.visitAlternative(nodeAny);
case model_1.Option:
return this.visitOption(nodeAny);
case model_1.RepetitionMandatory:
return this.visitRepetitionMandatory(nodeAny);
case model_1.RepetitionMandatoryWithSeparator:
return this.visitRepetitionMandatoryWithSeparator(nodeAny);
case model_1.RepetitionWithSeparator:
return this.visitRepetitionWithSeparator(nodeAny);
case model_1.Repetition:
return this.visitRepetition(nodeAny);
case model_1.Alternation:
return this.visitAlternation(nodeAny);
case model_1.Terminal:
return this.visitTerminal(nodeAny);
case model_1.Rule:
return this.visitRule(nodeAny);
/* istanbul ignore next */
default:
throw Error("non exhaustive match");
}
};
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
GAstVisitor.prototype.visitNonTerminal = function (node) { };
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
GAstVisitor.prototype.visitAlternative = function (node) { };
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
GAstVisitor.prototype.visitOption = function (node) { };
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
GAstVisitor.prototype.visitRepetition = function (node) { };
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
GAstVisitor.prototype.visitRepetitionMandatory = function (node) { };
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
GAstVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) { };
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
GAstVisitor.prototype.visitRepetitionWithSeparator = function (node) { };
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
GAstVisitor.prototype.visitAlternation = function (node) { };
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
GAstVisitor.prototype.visitTerminal = function (node) { };
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
GAstVisitor.prototype.visitRule = function (node) { };
return GAstVisitor;
}());
exports.GAstVisitor = GAstVisitor;
//# sourceMappingURL=visitor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"visitor.js","sourceRoot":"","sources":["../../src/visitor.ts"],"names":[],"mappings":";;;AAAA,iCAWgB;AAGhB;IAAA;IA6DA,CAAC;IA5DQ,2BAAK,GAAZ,UAAa,IAAiB;QAC5B,IAAM,OAAO,GAAQ,IAAI,CAAA;QACzB,QAAQ,OAAO,CAAC,WAAW,EAAE;YAC3B,KAAK,mBAAW;gBACd,OAAO,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAA;YACvC,KAAK,mBAAW;gBACd,OAAO,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAA;YACvC,KAAK,cAAM;gBACT,OAAO,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAA;YAClC,KAAK,2BAAmB;gBACtB,OAAO,IAAI,CAAC,wBAAwB,CAAC,OAAO,CAAC,CAAA;YAC/C,KAAK,wCAAgC;gBACnC,OAAO,IAAI,CAAC,qCAAqC,CAAC,OAAO,CAAC,CAAA;YAC5D,KAAK,+BAAuB;gBAC1B,OAAO,IAAI,CAAC,4BAA4B,CAAC,OAAO,CAAC,CAAA;YACnD,KAAK,kBAAU;gBACb,OAAO,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,CAAA;YACtC,KAAK,mBAAW;gBACd,OAAO,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAA;YACvC,KAAK,gBAAQ;gBACX,OAAO,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,CAAA;YACpC,KAAK,YAAI;gBACP,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAA;YAChC,0BAA0B;YAC1B;gBACE,MAAM,KAAK,CAAC,sBAAsB,CAAC,CAAA;SACtC;IACH,CAAC;IAED,oFAAoF;IAC7E,sCAAgB,GAAvB,UAAwB,IAAiB,IAAQ,CAAC;IAElD,oFAAoF;IAC7E,sCAAgB,GAAvB,UAAwB,IAAiB,IAAQ,CAAC;IAElD,oFAAoF;IAC7E,iCAAW,GAAlB,UAAmB,IAAY,IAAQ,CAAC;IAExC,oFAAoF;IAC7E,qCAAe,GAAtB,UAAuB,IAAgB,IAAQ,CAAC;IAEhD,oFAAoF;IAC7E,8CAAwB,GAA/B,UAAgC,IAAyB,IAAQ,CAAC;IAElE,oFAAoF;IAC7E,2DAAqC,GAA5C,UACE,IAAsC,IAChC,CAAC;IAET,oFAAoF;IAC7E,kDAA4B,GAAnC,UAAoC,IAA6B,IAAQ,CAAC;IAE1E,oFAAoF;IAC7E,sCAAgB,GAAvB,UAAwB,IAAiB,IAAQ,CAAC;IAElD,oFAAoF;IAC7E,mCAAa,GAApB,UAAqB,IAAc,IAAQ,CAAC;IAE5C,oFAAoF;IAC7E,+BAAS,GAAhB,UAAiB,IAAU,IAAQ,CAAC;IACtC,kBAAC;AAAD,CAAC,AA7DD,IA6DC;AA7DqB,kCAAW"}

View File

@@ -0,0 +1,47 @@
{
"name": "@chevrotain/gast",
"version": "10.5.0",
"description": "Grammar AST structure for Chevrotain Parsers",
"keywords": [],
"bugs": {
"url": "https://github.com/Chevrotain/chevrotain/issues"
},
"license": "Apache-2.0",
"typings": "lib/src/api.d.ts",
"main": "lib/src/api.js",
"files": [
"src/**/*.ts",
"lib/src/**/*.js",
"lib/src/**/*.d.ts",
"lib/src/**/*.js.map",
"api.d.ts"
],
"repository": {
"type": "git",
"url": "git://github.com/Chevrotain/chevrotain.git"
},
"scripts": {
"---------- CI FLOWS --------": "",
"ci": "pnpm run build test",
"build": "npm-run-all clean compile",
"test": "npm-run-all coverage",
"---------- DEV FLOWS --------": "",
"update-snapshots": "node ./scripts/update-snapshots.js",
"---------- BUILD STEPS --------": "",
"clean": "shx rm -rf lib coverage",
"compile:watch": "tsc -w",
"compile": "tsc",
"coverage": "nyc mocha"
},
"dependencies": {
"@chevrotain/types": "10.5.0",
"lodash": "4.17.21"
},
"devDependencies": {
"@types/lodash": "4.14.191"
},
"publishConfig": {
"access": "public"
},
"gitHead": "f5fdf95b8da570c702753252b0a3f7aa34d64f3b"
}

View File

@@ -0,0 +1,23 @@
export {
Rule,
Terminal,
NonTerminal,
Option,
Repetition,
RepetitionMandatory,
RepetitionMandatoryWithSeparator,
RepetitionWithSeparator,
Alternation,
Alternative,
serializeGrammar,
serializeProduction
} from "./model"
export { GAstVisitor } from "./visitor"
export {
getProductionDslName,
isOptionalProd,
isBranchingProd,
isSequenceProd
} from "./helpers"

View File

@@ -0,0 +1,101 @@
import some from "lodash/some"
import every from "lodash/every"
import has from "lodash/has"
import includes from "lodash/includes"
import {
AbstractProduction,
Alternation,
Alternative,
NonTerminal,
Option,
Repetition,
RepetitionMandatory,
RepetitionMandatoryWithSeparator,
RepetitionWithSeparator,
Rule,
Terminal
} from "./model"
import { GAstVisitor } from "./visitor"
import { IProduction, IProductionWithOccurrence } from "@chevrotain/types"
export function isSequenceProd(
prod: IProduction
): prod is { definition: IProduction[] } & IProduction {
return (
prod instanceof Alternative ||
prod instanceof Option ||
prod instanceof Repetition ||
prod instanceof RepetitionMandatory ||
prod instanceof RepetitionMandatoryWithSeparator ||
prod instanceof RepetitionWithSeparator ||
prod instanceof Terminal ||
prod instanceof Rule
)
}
export function isOptionalProd(
prod: IProduction,
alreadyVisited: NonTerminal[] = []
): boolean {
const isDirectlyOptional =
prod instanceof Option ||
prod instanceof Repetition ||
prod instanceof RepetitionWithSeparator
if (isDirectlyOptional) {
return true
}
// note that this can cause infinite loop if one optional empty TOP production has a cyclic dependency with another
// empty optional top rule
// may be indirectly optional ((A?B?C?) | (D?E?F?))
if (prod instanceof Alternation) {
// for OR its enough for just one of the alternatives to be optional
return some((<Alternation>prod).definition, (subProd: IProduction) => {
return isOptionalProd(subProd, alreadyVisited)
})
} else if (prod instanceof NonTerminal && includes(alreadyVisited, prod)) {
// avoiding stack overflow due to infinite recursion
return false
} else if (prod instanceof AbstractProduction) {
if (prod instanceof NonTerminal) {
alreadyVisited.push(prod)
}
return every(
(<AbstractProduction>prod).definition,
(subProd: IProduction) => {
return isOptionalProd(subProd, alreadyVisited)
}
)
} else {
return false
}
}
export function isBranchingProd(
prod: IProduction
): prod is { definition: IProduction[] } & IProduction {
return prod instanceof Alternation
}
export function getProductionDslName(prod: IProductionWithOccurrence): string {
/* istanbul ignore else */
if (prod instanceof NonTerminal) {
return "SUBRULE"
} else if (prod instanceof Option) {
return "OPTION"
} else if (prod instanceof Alternation) {
return "OR"
} else if (prod instanceof RepetitionMandatory) {
return "AT_LEAST_ONE"
} else if (prod instanceof RepetitionMandatoryWithSeparator) {
return "AT_LEAST_ONE_SEP"
} else if (prod instanceof RepetitionWithSeparator) {
return "MANY_SEP"
} else if (prod instanceof Repetition) {
return "MANY"
} else if (prod instanceof Terminal) {
return "CONSUME"
} else {
throw Error("non exhaustive match")
}
}

View File

@@ -0,0 +1,420 @@
import map from "lodash/map"
import forEach from "lodash/forEach"
import isString from "lodash/isString"
import isRegExp from "lodash/isRegExp"
import pickBy from "lodash/pickBy"
import assign from "lodash/assign"
import {
IGASTVisitor,
IProduction,
IProductionWithOccurrence,
ISerializedGast,
TokenType
} from "@chevrotain/types"
// TODO: duplicated code to avoid extracting another sub-package -- how to avoid?
function tokenLabel(tokType: TokenType): string {
if (hasTokenLabel(tokType)) {
return tokType.LABEL
} else {
return tokType.name
}
}
// TODO: duplicated code to avoid extracting another sub-package -- how to avoid?
function hasTokenLabel(
obj: TokenType
): obj is TokenType & Pick<Required<TokenType>, "LABEL"> {
return isString(obj.LABEL) && obj.LABEL !== ""
}
export abstract class AbstractProduction<T extends IProduction = IProduction>
implements IProduction
{
public get definition(): T[] {
return this._definition
}
public set definition(value: T[]) {
this._definition = value
}
constructor(protected _definition: T[]) {}
accept(visitor: IGASTVisitor): void {
visitor.visit(this)
forEach(this.definition, (prod) => {
prod.accept(visitor)
})
}
}
export class NonTerminal
extends AbstractProduction
implements IProductionWithOccurrence
{
public nonTerminalName!: string
public label?: string
public referencedRule!: Rule
public idx: number = 1
constructor(options: {
nonTerminalName: string
label?: string
referencedRule?: Rule
idx?: number
}) {
super([])
assign(
this,
pickBy(options, (v) => v !== undefined)
)
}
set definition(definition: IProduction[]) {
// immutable
}
get definition(): IProduction[] {
if (this.referencedRule !== undefined) {
return this.referencedRule.definition
}
return []
}
accept(visitor: IGASTVisitor): void {
visitor.visit(this)
// don't visit children of a reference, we will get cyclic infinite loops if we do so
}
}
export class Rule extends AbstractProduction {
public name!: string
public orgText: string = ""
constructor(options: {
name: string
definition: IProduction[]
orgText?: string
}) {
super(options.definition)
assign(
this,
pickBy(options, (v) => v !== undefined)
)
}
}
export class Alternative extends AbstractProduction {
public ignoreAmbiguities: boolean = false
constructor(options: {
definition: IProduction[]
ignoreAmbiguities?: boolean
}) {
super(options.definition)
assign(
this,
pickBy(options, (v) => v !== undefined)
)
}
}
export class Option
extends AbstractProduction
implements IProductionWithOccurrence
{
public idx: number = 1
public maxLookahead?: number
constructor(options: {
definition: IProduction[]
idx?: number
maxLookahead?: number
}) {
super(options.definition)
assign(
this,
pickBy(options, (v) => v !== undefined)
)
}
}
export class RepetitionMandatory
extends AbstractProduction
implements IProductionWithOccurrence
{
public idx: number = 1
public maxLookahead?: number
constructor(options: {
definition: IProduction[]
idx?: number
maxLookahead?: number
}) {
super(options.definition)
assign(
this,
pickBy(options, (v) => v !== undefined)
)
}
}
export class RepetitionMandatoryWithSeparator
extends AbstractProduction
implements IProductionWithOccurrence
{
public separator!: TokenType
public idx: number = 1
public maxLookahead?: number
constructor(options: {
definition: IProduction[]
separator: TokenType
idx?: number
}) {
super(options.definition)
assign(
this,
pickBy(options, (v) => v !== undefined)
)
}
}
export class Repetition
extends AbstractProduction
implements IProductionWithOccurrence
{
public separator!: TokenType
public idx: number = 1
public maxLookahead?: number
constructor(options: {
definition: IProduction[]
idx?: number
maxLookahead?: number
}) {
super(options.definition)
assign(
this,
pickBy(options, (v) => v !== undefined)
)
}
}
export class RepetitionWithSeparator
extends AbstractProduction
implements IProductionWithOccurrence
{
public separator!: TokenType
public idx: number = 1
public maxLookahead?: number
constructor(options: {
definition: IProduction[]
separator: TokenType
idx?: number
}) {
super(options.definition)
assign(
this,
pickBy(options, (v) => v !== undefined)
)
}
}
export class Alternation
extends AbstractProduction<Alternative>
implements IProductionWithOccurrence
{
public idx: number = 1
public ignoreAmbiguities: boolean = false
public hasPredicates: boolean = false
public maxLookahead?: number
public get definition(): Alternative[] {
return this._definition
}
public set definition(value: Alternative[]) {
this._definition = value
}
constructor(options: {
definition: Alternative[]
idx?: number
ignoreAmbiguities?: boolean
hasPredicates?: boolean
maxLookahead?: number
}) {
super(options.definition)
assign(
this,
pickBy(options, (v) => v !== undefined)
)
}
}
export class Terminal implements IProductionWithOccurrence {
public terminalType!: TokenType
public label?: string
public idx: number = 1
constructor(options: {
terminalType: TokenType
label?: string
idx?: number
}) {
assign(
this,
pickBy(options, (v) => v !== undefined)
)
}
accept(visitor: IGASTVisitor): void {
visitor.visit(this)
}
}
export interface ISerializedBasic extends ISerializedGast {
type:
| "Alternative"
| "Option"
| "RepetitionMandatory"
| "Repetition"
| "Alternation"
idx?: number
}
export interface ISerializedGastRule extends ISerializedGast {
type: "Rule"
name: string
orgText: string
}
export interface ISerializedNonTerminal extends ISerializedGast {
type: "NonTerminal"
name: string
label?: string
idx: number
}
export interface ISerializedTerminal extends ISerializedGast {
type: "Terminal"
name: string
terminalLabel?: string
label?: string
pattern?: string
idx: number
}
export interface ISerializedTerminalWithSeparator extends ISerializedGast {
type: "RepetitionMandatoryWithSeparator" | "RepetitionWithSeparator"
idx: number
separator: ISerializedTerminal
}
export type ISerializedGastAny =
| ISerializedBasic
| ISerializedGastRule
| ISerializedNonTerminal
| ISerializedTerminal
| ISerializedTerminalWithSeparator
export function serializeGrammar(topRules: Rule[]): ISerializedGast[] {
return map(topRules, serializeProduction)
}
export function serializeProduction(node: IProduction): ISerializedGast {
function convertDefinition(definition: IProduction[]): ISerializedGast[] {
return map(definition, serializeProduction)
}
/* istanbul ignore else */
if (node instanceof NonTerminal) {
const serializedNonTerminal: ISerializedNonTerminal = {
type: "NonTerminal",
name: node.nonTerminalName,
idx: node.idx
}
if (isString(node.label)) {
serializedNonTerminal.label = node.label
}
return serializedNonTerminal
} else if (node instanceof Alternative) {
return <ISerializedBasic>{
type: "Alternative",
definition: convertDefinition(node.definition)
}
} else if (node instanceof Option) {
return <ISerializedBasic>{
type: "Option",
idx: node.idx,
definition: convertDefinition(node.definition)
}
} else if (node instanceof RepetitionMandatory) {
return <ISerializedBasic>{
type: "RepetitionMandatory",
idx: node.idx,
definition: convertDefinition(node.definition)
}
} else if (node instanceof RepetitionMandatoryWithSeparator) {
return <ISerializedTerminalWithSeparator>{
type: "RepetitionMandatoryWithSeparator",
idx: node.idx,
separator: <ISerializedTerminal>(
serializeProduction(new Terminal({ terminalType: node.separator }))
),
definition: convertDefinition(node.definition)
}
} else if (node instanceof RepetitionWithSeparator) {
return <ISerializedTerminalWithSeparator>{
type: "RepetitionWithSeparator",
idx: node.idx,
separator: <ISerializedTerminal>(
serializeProduction(new Terminal({ terminalType: node.separator }))
),
definition: convertDefinition(node.definition)
}
} else if (node instanceof Repetition) {
return <ISerializedBasic>{
type: "Repetition",
idx: node.idx,
definition: convertDefinition(node.definition)
}
} else if (node instanceof Alternation) {
return <ISerializedBasic>{
type: "Alternation",
idx: node.idx,
definition: convertDefinition(node.definition)
}
} else if (node instanceof Terminal) {
const serializedTerminal = <ISerializedTerminal>{
type: "Terminal",
name: node.terminalType.name,
label: tokenLabel(node.terminalType),
idx: node.idx
}
if (isString(node.label)) {
serializedTerminal.terminalLabel = node.label
}
const pattern = node.terminalType.PATTERN
if (node.terminalType.PATTERN) {
serializedTerminal.pattern = isRegExp(pattern)
? (<any>pattern).source
: pattern
}
return serializedTerminal
} else if (node instanceof Rule) {
return <ISerializedGastRule>{
type: "Rule",
name: node.name,
orgText: node.orgText,
definition: convertDefinition(node.definition)
}
} else {
throw Error("non exhaustive match")
}
}

View File

@@ -0,0 +1,76 @@
import {
Alternation,
Alternative,
NonTerminal,
Option,
Repetition,
RepetitionMandatory,
RepetitionMandatoryWithSeparator,
RepetitionWithSeparator,
Rule,
Terminal
} from "./model"
import { IProduction } from "@chevrotain/types"
export abstract class GAstVisitor {
public visit(node: IProduction): any {
const nodeAny: any = node
switch (nodeAny.constructor) {
case NonTerminal:
return this.visitNonTerminal(nodeAny)
case Alternative:
return this.visitAlternative(nodeAny)
case Option:
return this.visitOption(nodeAny)
case RepetitionMandatory:
return this.visitRepetitionMandatory(nodeAny)
case RepetitionMandatoryWithSeparator:
return this.visitRepetitionMandatoryWithSeparator(nodeAny)
case RepetitionWithSeparator:
return this.visitRepetitionWithSeparator(nodeAny)
case Repetition:
return this.visitRepetition(nodeAny)
case Alternation:
return this.visitAlternation(nodeAny)
case Terminal:
return this.visitTerminal(nodeAny)
case Rule:
return this.visitRule(nodeAny)
/* istanbul ignore next */
default:
throw Error("non exhaustive match")
}
}
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
public visitNonTerminal(node: NonTerminal): any {}
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
public visitAlternative(node: Alternative): any {}
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
public visitOption(node: Option): any {}
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
public visitRepetition(node: Repetition): any {}
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
public visitRepetitionMandatory(node: RepetitionMandatory): any {}
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
public visitRepetitionMandatoryWithSeparator(
node: RepetitionMandatoryWithSeparator
): any {}
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
public visitRepetitionWithSeparator(node: RepetitionWithSeparator): any {}
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
public visitAlternation(node: Alternation): any {}
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
public visitTerminal(node: Terminal): any {}
/* istanbul ignore next - testing the fact a NOOP function exists is non-trivial */
public visitRule(node: Rule): any {}
}

View File

@@ -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.

2788
_node_modules/@chevrotain/types/api.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,44 @@
{
"name": "@chevrotain/types",
"version": "10.5.0",
"description": "Type Signatures and API Website for Chevrotain",
"keywords": [],
"bugs": {
"url": "https://github.com/Chevrotain/chevrotain/issues"
},
"license": "Apache-2.0",
"author": {
"name": "Shahar Soel"
},
"files": [
"api.d.ts",
"README.md",
"LICENSE.TXT"
],
"repository": {
"type": "git",
"url": "git://github.com/Chevrotain/chevrotain.git"
},
"homepage": "https://chevrotain.io/documentation/",
"scripts": {
"---------- CI FLOWS --------": "",
"ci": "pnpm run build",
"build": "npm-run-all clean compile api-site:build",
"postversion": "npm-run-all api-site:build api-site:upload",
"---------- BUILD STEPS --------": "",
"clean": "shx rm -rf dev lib",
"compile:watch": "tsc -w",
"compile": "tsc",
"api-site:build": "typedoc api.d.ts --out dev/docs --excludeExternals --excludePrivate",
"api-site:upload": "./scripts/api-site-upload.sh"
},
"devDependencies": {
"typedoc": "0.23.23",
"typescript": "4.9.4"
},
"typings": "api.d.ts",
"publishConfig": {
"access": "public"
},
"gitHead": "f5fdf95b8da570c702753252b0a3f7aa34d64f3b"
}

View File

@@ -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.

3
_node_modules/@chevrotain/utils/lib/src/api.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
export { PRINT_WARNING, PRINT_ERROR } from "./print";
export { timer } from "./timer";
export { toFastProperties } from "./to-fast-properties";

View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toFastProperties = exports.timer = exports.PRINT_ERROR = exports.PRINT_WARNING = void 0;
var print_1 = require("./print");
Object.defineProperty(exports, "PRINT_WARNING", { enumerable: true, get: function () { return print_1.PRINT_WARNING; } });
Object.defineProperty(exports, "PRINT_ERROR", { enumerable: true, get: function () { return print_1.PRINT_ERROR; } });
var timer_1 = require("./timer");
Object.defineProperty(exports, "timer", { enumerable: true, get: function () { return timer_1.timer; } });
var to_fast_properties_1 = require("./to-fast-properties");
Object.defineProperty(exports, "toFastProperties", { enumerable: true, get: function () { return to_fast_properties_1.toFastProperties; } });
//# sourceMappingURL=api.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/api.ts"],"names":[],"mappings":";;;AAAA,iCAAoD;AAA3C,sGAAA,aAAa,OAAA;AAAE,oGAAA,WAAW,OAAA;AACnC,iCAA+B;AAAtB,8FAAA,KAAK,OAAA;AACd,2DAAuD;AAA9C,sHAAA,gBAAgB,OAAA"}

2
_node_modules/@chevrotain/utils/lib/src/print.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export declare function PRINT_ERROR(msg: string): void;
export declare function PRINT_WARNING(msg: string): void;

View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PRINT_WARNING = exports.PRINT_ERROR = void 0;
function PRINT_ERROR(msg) {
/* istanbul ignore else - can't override global.console in node.js */
if (console && console.error) {
console.error("Error: ".concat(msg));
}
}
exports.PRINT_ERROR = PRINT_ERROR;
function PRINT_WARNING(msg) {
/* istanbul ignore else - can't override global.console in node.js*/
if (console && console.warn) {
// TODO: modify docs accordingly
console.warn("Warning: ".concat(msg));
}
}
exports.PRINT_WARNING = PRINT_WARNING;
//# sourceMappingURL=print.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"print.js","sourceRoot":"","sources":["../../src/print.ts"],"names":[],"mappings":";;;AAAA,SAAgB,WAAW,CAAC,GAAW;IACrC,qEAAqE;IACrE,IAAI,OAAO,IAAI,OAAO,CAAC,KAAK,EAAE;QAC5B,OAAO,CAAC,KAAK,CAAC,iBAAU,GAAG,CAAE,CAAC,CAAA;KAC/B;AACH,CAAC;AALD,kCAKC;AAED,SAAgB,aAAa,CAAC,GAAW;IACvC,oEAAoE;IACpE,IAAI,OAAO,IAAI,OAAO,CAAC,IAAI,EAAE;QAC3B,gCAAgC;QAChC,OAAO,CAAC,IAAI,CAAC,mBAAY,GAAG,CAAE,CAAC,CAAA;KAChC;AACH,CAAC;AAND,sCAMC"}

4
_node_modules/@chevrotain/utils/lib/src/timer.d.ts generated vendored Normal file
View File

@@ -0,0 +1,4 @@
export declare function timer<T>(func: () => T): {
time: number;
value: T;
};

View File

@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.timer = void 0;
function timer(func) {
var start = new Date().getTime();
var val = func();
var end = new Date().getTime();
var total = end - start;
return { time: total, value: val };
}
exports.timer = timer;
//# sourceMappingURL=timer.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"timer.js","sourceRoot":"","sources":["../../src/timer.ts"],"names":[],"mappings":";;;AAAA,SAAgB,KAAK,CAAI,IAAa;IACpC,IAAM,KAAK,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAA;IAClC,IAAM,GAAG,GAAG,IAAI,EAAE,CAAA;IAClB,IAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAA;IAChC,IAAM,KAAK,GAAG,GAAG,GAAG,KAAK,CAAA;IACzB,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,CAAA;AACpC,CAAC;AAND,sBAMC"}

View File

@@ -0,0 +1 @@
export declare function toFastProperties(toBecomeFast: any): any;

View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toFastProperties = void 0;
// based on: https://github.com/petkaantonov/bluebird/blob/b97c0d2d487e8c5076e8bd897e0dcd4622d31846/src/util.js#L201-L216
function toFastProperties(toBecomeFast) {
function FakeConstructor() { }
// If our object is used as a constructor it would receive
FakeConstructor.prototype = toBecomeFast;
var fakeInstance = new FakeConstructor();
function fakeAccess() {
return typeof fakeInstance.bar;
}
// help V8 understand this is a "real" prototype by actually using
// the fake instance.
fakeAccess();
fakeAccess();
// Always true condition to suppress the Firefox warning of unreachable
// code after a return statement.
if (1)
return toBecomeFast;
// Eval prevents optimization of this method (even though this is dead code)
/* istanbul ignore next */
// tslint:disable-next-line
eval(toBecomeFast);
}
exports.toFastProperties = toFastProperties;
//# sourceMappingURL=to-fast-properties.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"to-fast-properties.js","sourceRoot":"","sources":["../../src/to-fast-properties.ts"],"names":[],"mappings":";;;AAAA,yHAAyH;AACzH,SAAgB,gBAAgB,CAAC,YAAiB;IAChD,SAAS,eAAe,KAAI,CAAC;IAE7B,0DAA0D;IAC1D,eAAe,CAAC,SAAS,GAAG,YAAY,CAAA;IACxC,IAAM,YAAY,GAAG,IAAK,eAAuB,EAAE,CAAA;IAEnD,SAAS,UAAU;QACjB,OAAO,OAAO,YAAY,CAAC,GAAG,CAAA;IAChC,CAAC;IAED,kEAAkE;IAClE,qBAAqB;IACrB,UAAU,EAAE,CAAA;IACZ,UAAU,EAAE,CAAA;IAEZ,uEAAuE;IACvE,iCAAiC;IACjC,IAAI,CAAC;QAAE,OAAO,YAAY,CAAA;IAE1B,4EAA4E;IAC5E,0BAA0B;IAC1B,2BAA2B;IAC3B,IAAI,CAAC,YAAY,CAAC,CAAA;AACpB,CAAC;AAxBD,4CAwBC"}

View File

@@ -0,0 +1,42 @@
{
"name": "@chevrotain/utils",
"version": "10.5.0",
"description": "common utilities",
"keywords": [],
"bugs": {
"url": "https://github.com/Chevrotain/chevrotain/issues"
},
"license": "Apache-2.0",
"author": {
"name": "Shahar Soel"
},
"typings": "lib/src/api.d.ts",
"main": "lib/src/api.js",
"files": [
"src/**/*.ts",
"lib/src/**/*.js",
"lib/src/**/*.d.ts",
"lib/src/**/*.js.map",
"README.md",
"LICENSE.TXT"
],
"repository": {
"type": "git",
"url": "git://github.com/Chevrotain/chevrotain.git"
},
"scripts": {
"---------- CI FLOWS --------": "",
"ci": "npm-run-all build test",
"build": "npm-run-all clean compile",
"test": "npm-run-all coverage",
"---------- BUILD STEPS --------": "",
"clean": "shx rm -rf lib coverage",
"compile:watch": "tsc -w",
"compile": "tsc",
"coverage": "nyc mocha"
},
"publishConfig": {
"access": "public"
},
"gitHead": "f5fdf95b8da570c702753252b0a3f7aa34d64f3b"
}

View File

@@ -0,0 +1,3 @@
export { PRINT_WARNING, PRINT_ERROR } from "./print"
export { timer } from "./timer"
export { toFastProperties } from "./to-fast-properties"

View File

@@ -0,0 +1,14 @@
export function PRINT_ERROR(msg: string) {
/* istanbul ignore else - can't override global.console in node.js */
if (console && console.error) {
console.error(`Error: ${msg}`)
}
}
export function PRINT_WARNING(msg: string) {
/* istanbul ignore else - can't override global.console in node.js*/
if (console && console.warn) {
// TODO: modify docs accordingly
console.warn(`Warning: ${msg}`)
}
}

View File

@@ -0,0 +1,7 @@
export function timer<T>(func: () => T): { time: number; value: T } {
const start = new Date().getTime()
const val = func()
const end = new Date().getTime()
const total = end - start
return { time: total, value: val }
}

View File

@@ -0,0 +1,26 @@
// based on: https://github.com/petkaantonov/bluebird/blob/b97c0d2d487e8c5076e8bd897e0dcd4622d31846/src/util.js#L201-L216
export function toFastProperties(toBecomeFast: any) {
function FakeConstructor() {}
// If our object is used as a constructor it would receive
FakeConstructor.prototype = toBecomeFast
const fakeInstance = new (FakeConstructor as any)()
function fakeAccess() {
return typeof fakeInstance.bar
}
// help V8 understand this is a "real" prototype by actually using
// the fake instance.
fakeAccess()
fakeAccess()
// Always true condition to suppress the Firefox warning of unreachable
// code after a return statement.
if (1) return toBecomeFast
// Eval prevents optimization of this method (even though this is dead code)
/* istanbul ignore next */
// tslint:disable-next-line
eval(toBecomeFast)
}

View File

@@ -0,0 +1,146 @@
# @electric-sql/pglite-socket
## 0.0.20
### Patch Changes
- 54a4873: allow extensions to be loaded via '-e/--extensions <list>' cmd line parameter'
- 45bff97: added pgcrypto extension
- Updated dependencies [45bff97]
- Updated dependencies [5ec474f]
- @electric-sql/pglite@0.3.15
## 0.0.19
### Patch Changes
- Updated dependencies [8785034]
- Updated dependencies [90cfee8]
- @electric-sql/pglite@0.3.14
## 0.0.18
### Patch Changes
- Updated dependencies [ad3d0d8]
- @electric-sql/pglite@0.3.13
## 0.0.17
### Patch Changes
- Updated dependencies [ce0e74e]
- @electric-sql/pglite@0.3.12
## 0.0.16
### Patch Changes
- Updated dependencies [9a104b9]
- @electric-sql/pglite@0.3.11
## 0.0.15
### Patch Changes
- Updated dependencies [ad765ed]
- @electric-sql/pglite@0.3.10
## 0.0.14
### Patch Changes
- e40ccad: Upgrade emsdk
- Updated dependencies [e40ccad]
- @electric-sql/pglite@0.3.9
## 0.0.13
### Patch Changes
- bd263aa: fix oom; other fixes
- Updated dependencies [f12a582]
- Updated dependencies [bd263aa]
- @electric-sql/pglite@0.3.8
## 0.0.12
### Patch Changes
- Updated dependencies [0936962]
- @electric-sql/pglite@0.3.7
## 0.0.11
### Patch Changes
- Updated dependencies [6898469]
- Updated dependencies [469be18]
- Updated dependencies [64e33c7]
- @electric-sql/pglite@0.3.6
## 0.0.10
### Patch Changes
- Updated dependencies [6653899]
- Updated dependencies [5f007fc]
- @electric-sql/pglite@0.3.5
## 0.0.9
### Patch Changes
- 38a55d0: fix cjs/esm misconfigurations
- Updated dependencies [1fcaa3e]
- Updated dependencies [38a55d0]
- Updated dependencies [aac7003]
- Updated dependencies [8ca254d]
- @electric-sql/pglite@0.3.4
## 0.0.8
### Patch Changes
- Updated dependencies [ea2c7c7]
- @electric-sql/pglite@0.3.3
## 0.0.7
### Patch Changes
- 5a47f4d: better handling of closing the socket
- 6f8dd08: with the `npx pglite-server` command, add the ability to pass a command to run after the server is ready, along with passing a new DATABASE_URL environment variable to the command. This allows for a command like `npx pglite-server -r "npm run dev:inner" --include-database-url` to run a dev server that uses the pglite server as the database.
## 0.0.6
### Patch Changes
- Updated dependencies [e2c654b]
- @electric-sql/pglite@0.3.2
## 0.0.5
### Patch Changes
- f975f77: Updated README
- d9b52d5: allows unix socket connections
## 0.0.4
### Patch Changes
- 027baed: missing shebang
## 0.0.3
### Patch Changes
- 1c2dc84: fix pglite-socket exports
## 0.0.2
### Patch Changes
- Updated dependencies [713364e]
- @electric-sql/pglite@0.3.1

View File

@@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View File

@@ -0,0 +1,265 @@
# pglite-socket
A socket implementation for PGlite enabling remote connections. This package is a simple wrapper around the `net` module to allow PGlite to be used as a PostgreSQL server.
There are two main components to this package:
- [`PGLiteSocketServer`](#pglitesocketserver) - A TCP server that allows PostgreSQL clients to connect to a PGlite database instance.
- [`PGLiteSocketHandler`](#pglitesockethandler) - A low-level handler for a single socket connection to PGlite. This class handles the raw protocol communication between a socket and PGlite, and can be used to create a custom server.
The package also includes a [CLI](#cli-usage) for quickly starting a PGlite socket server.
Note: As PGlite is a single-connection database, it is not possible to have multiple simultaneous connections open. This means that the socket server will only support a single client connection at a time. While a `PGLiteSocketServer` or `PGLiteSocketHandler` are attached to a PGlite instance they hold an exclusive lock preventing any other connections, or queries on the PGlite instance.
## Installation
```bash
npm install @electric-sql/pglite-socket
# or
yarn add @electric-sql/pglite-socket
# or
pnpm add @electric-sql/pglite-socket
```
## Usage
```typescript
import { PGlite } from '@electric-sql/pglite'
import { PGLiteSocketServer } from '@electric-sql/pglite-socket'
// Create a PGlite instance
const db = await PGlite.create()
// Create and start a socket server
const server = new PGLiteSocketServer({
db,
port: 5432,
host: '127.0.0.1',
})
await server.start()
console.log('Server started on 127.0.0.1:5432')
// Handle graceful shutdown
process.on('SIGINT', async () => {
await server.stop()
await db.close()
console.log('Server stopped and database closed')
process.exit(0)
})
```
## API
### PGLiteSocketServer
Creates a TCP server that allows PostgreSQL clients to connect to a PGlite database instance.
#### Options
- `db: PGlite` - The PGlite database instance
- `port?: number` - The port to listen on (default: 5432). Use port 0 to let the OS assign an available port
- `host?: string` - The host to bind to (default: 127.0.0.1)
- `path?: string` - Unix socket path to bind to (takes precedence over host:port)
- `inspect?: boolean` - Print the incoming and outgoing data to the console (default: false)
#### Methods
- `start(): Promise<void>` - Start the socket server
- `stop(): Promise<void>` - Stop the socket server
#### Events
- `listening` - Emitted when the server starts listening
- `connection` - Emitted when a client connects
- `error` - Emitted when an error occurs
- `close` - Emitted when the server is closed
### PGLiteSocketHandler
Low-level handler for a single socket connection to PGlite. This class handles the raw protocol communication between a socket and PGlite.
#### Options
- `db: PGlite` - The PGlite database instance
- `closeOnDetach?: boolean` - Whether to close the socket when detached (default: false)
- `inspect?: boolean` - Print the incoming and outgoing data to the console in hex and ascii (default: false)
#### Methods
- `attach(socket: Socket): Promise<PGLiteSocketHandler>` - Attach a socket to this handler
- `detach(close?: boolean): PGLiteSocketHandler` - Detach the current socket from this handler
- `isAttached: boolean` - Check if a socket is currently attached
#### Events
- `data` - Emitted when data is processed through the handler
- `error` - Emitted when an error occurs
- `close` - Emitted when the socket is closed
#### Example
```typescript
import { PGlite } from '@electric-sql/pglite'
import { PGLiteSocketHandler } from '@electric-sql/pglite-socket'
import { createServer, Socket } from 'net'
// Create a PGlite instance
const db = await PGlite.create()
// Create a handler
const handler = new PGLiteSocketHandler({
db,
closeOnDetach: true,
inspect: false,
})
// Create a server that uses the handler
const server = createServer(async (socket: Socket) => {
try {
await handler.attach(socket)
console.log('Client connected')
} catch (err) {
console.error('Error attaching socket', err)
socket.end()
}
})
server.listen(5432, '127.0.0.1')
```
## Examples
See the [examples directory](./examples) for more usage examples.
## CLI Usage
This package provides a command-line interface for quickly starting a PGlite socket server.
```bash
# Install globally
npm install -g @electric-sql/pglite-socket
# Start a server with default settings (in-memory database, port 5432)
pglite-server
# Start a server with custom options
pglite-server --db=/path/to/database --port=5433 --host=0.0.0.0 --debug=1
# Using short options
pglite-server -d /path/to/database -p 5433 -h 0.0.0.0 -v 1
# Show help
pglite-server --help
```
### CLI Options
- `-d, --db=PATH` - Database path (default: memory://)
- `-p, --port=PORT` - Port to listen on (default: 5432). Use 0 to let the OS assign an available port
- `-h, --host=HOST` - Host to bind to (default: 127.0.0.1)
- `-u, --path=UNIX` - Unix socket to bind to (takes precedence over host:port)
- `-v, --debug=LEVEL` - Debug level 0-5 (default: 0)
- `-e, --extensions=LIST` - Comma-separated list of extensions to load (e.g., vector,pgcrypto)
- `-r, --run=COMMAND` - Command to run after server starts
- `--include-database-url` - Include DATABASE_URL in subprocess environment
- `--shutdown-timeout=MS` - Timeout for graceful subprocess shutdown in ms (default: 5000)
### Development Server Integration
The `--run` option is particularly useful for development workflows where you want to use PGlite as a drop-in replacement for PostgreSQL. This allows you to wrap your development server and automatically provide it with a DATABASE_URL pointing to your PGlite instance.
```bash
# Start your Next.js dev server with PGlite
pglite-server --run "npm run dev" --include-database-url
# Start a Node.js app with PGlite
pglite-server --db=./dev-db --run "node server.js" --include-database-url
# Start multiple services (using a process manager like concurrently)
pglite-server --run "npx concurrently 'npm run dev' 'npm run worker'" --include-database-url
```
When using `--run` with `--include-database-url`, the subprocess will receive a `DATABASE_URL` environment variable with the correct connection string for your PGlite server. This enables seamless integration with applications that expect a PostgreSQL connection string.
### Using in npm scripts
You can add the CLI to your package.json scripts for convenient execution:
```json
{
"scripts": {
"db:start": "pglite-server --db=./data/mydb --port=5433",
"db:dev": "pglite-server --db=memory:// --debug=1",
"dev": "pglite-server --db=./dev-db --run 'npm run start:dev' --include-database-url",
"dev:clean": "pglite-server --run 'npm run start:dev' --include-database-url"
}
}
```
Then run with:
```bash
npm run dev # Start with persistent database
npm run dev:clean # Start with in-memory database
```
### Unix Socket Support
For better performance in local development, you can use Unix sockets instead of TCP:
```bash
# Start server on a Unix socket
pglite-server --path=/tmp/pglite.sock --run "npm run dev" --include-database-url
# The DATABASE_URL will be: postgresql://postgres:postgres@/postgres?host=/tmp
```
### Connecting to the server
Once the server is running, you can connect to it using any PostgreSQL client:
#### Using psql
```bash
PGSSLMODE=disable psql -h localhost -p 5432 -d template1
```
#### Using Node.js clients
```javascript
// Using node-postgres
import pg from 'pg'
const client = new pg.Client({
host: 'localhost',
port: 5432,
database: 'template1'
})
await client.connect()
// Using postgres.js
import postgres from 'postgres'
const sql = postgres({
host: 'localhost',
port: 5432,
database: 'template1'
})
// Using environment variable (when using --include-database-url)
const sql = postgres(process.env.DATABASE_URL)
```
### Limitations and Tips
- Remember that PGlite only supports one connection at a time. If you're unable to connect, make sure no other client is currently connected.
- For development purposes, using an in-memory database (`--db=memory://`) is fastest but data won't persist after the server is stopped.
- For persistent storage, specify a file path for the database (e.g., `--db=./data/mydb`).
- When using debug mode (`--debug=1` or higher), additional protocol information will be displayed in the console.
- To allow connections from other machines, set the host to `0.0.0.0` with `--host=0.0.0.0`.
- SSL connections are **NOT** supported. For `psql`, set env var `PGSSLMODE=disable`.
- When using `--run`, the server will automatically shut down if the subprocess exits with a non-zero code.
- Use `--shutdown-timeout` to adjust how long to wait for graceful subprocess termination (default: 5 seconds).
## License
Apache 2.0

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,160 @@
import { PGlite } from '@electric-sql/pglite';
import { Socket } from 'net';
declare const CONNECTION_QUEUE_TIMEOUT = 60000;
/**
* Options for creating a PGLiteSocketHandler
*/
interface PGLiteSocketHandlerOptions {
/** The PGlite database instance */
db: PGlite;
/** Whether to close the socket when detached (default: false) */
closeOnDetach?: boolean;
/** Print the incoming and outgoing data to the console in hex and ascii */
inspect?: boolean;
/** Enable debug logging of method calls */
debug?: boolean;
}
/**
* Low-level handler for a single socket connection to PGLite
* Handles the raw protocol communication between a socket and PGLite
*/
declare class PGLiteSocketHandler extends EventTarget {
readonly db: PGlite;
private socket;
private active;
private closeOnDetach;
private resolveLock?;
private rejectLock?;
private inspect;
private debug;
private readonly id;
private static nextHandlerId;
/**
* Create a new PGLiteSocketHandler
* @param options Options for the handler
*/
constructor(options: PGLiteSocketHandlerOptions);
/**
* Get the unique ID of this handler
*/
get handlerId(): number;
/**
* Log a message if debug is enabled
* @private
*/
private log;
/**
* Attach a socket to this handler
* @param socket The socket to attach
* @returns this handler instance
* @throws Error if a socket is already attached
*/
attach(socket: Socket): Promise<PGLiteSocketHandler>;
/**
* Detach the current socket from this handler
* @param close Whether to close the socket when detaching (overrides constructor option)
* @returns this handler instance
*/
detach(close?: boolean): PGLiteSocketHandler;
/**
* Check if a socket is currently attached
*/
get isAttached(): boolean;
/**
* Handle incoming data from the socket
*/
private handleData;
/**
* Handle errors from the socket
*/
private handleError;
/**
* Handle socket close event
*/
private handleClose;
/**
* Print data in hex and ascii to the console
*/
private inspectData;
}
/**
* Options for creating a PGLiteSocketServer
*/
interface PGLiteSocketServerOptions {
/** The PGlite database instance */
db: PGlite;
/** The port to listen on (default: 5432) */
port?: number;
/** The host to bind to (default: 127.0.0.1) */
host?: string;
/** Unix socket path to bind to (default: undefined). If specified, takes precedence over host:port */
path?: string;
/** Print the incoming and outgoing data to the console in hex and ascii */
inspect?: boolean;
/** Connection queue timeout in milliseconds (default: 10000) */
connectionQueueTimeout?: number;
/** Enable debug logging of method calls */
debug?: boolean;
}
/**
* High-level server that manages socket connections to PGLite
* Creates and manages a TCP server and handles client connections
*/
declare class PGLiteSocketServer extends EventTarget {
readonly db: PGlite;
private server;
private port?;
private host?;
private path?;
private active;
private inspect;
private debug;
private connectionQueueTimeout;
private activeHandler;
private connectionQueue;
private handlerCount;
/**
* Create a new PGLiteSocketServer
* @param options Options for the server
*/
constructor(options: PGLiteSocketServerOptions);
/**
* Log a message if debug is enabled
* @private
*/
private log;
/**
* Start the socket server
* @returns Promise that resolves when the server is listening
*/
start(): Promise<void>;
getServerConn(): string;
/**
* Stop the socket server
* @returns Promise that resolves when the server is closed
*/
stop(): Promise<void>;
/**
* Get the active handler ID, or null if no active handler
*/
private get activeHandlerId();
/**
* Handle a new client connection
*/
private handleConnection;
/**
* Add a connection to the queue
*/
private enqueueConnection;
/**
* Process the next connection in the queue
*/
private processNextInQueue;
/**
* Attach a socket to a new handler
*/
private attachSocketToNewHandler;
}
export { CONNECTION_QUEUE_TIMEOUT, PGLiteSocketHandler, type PGLiteSocketHandlerOptions, PGLiteSocketServer, type PGLiteSocketServerOptions };

View File

@@ -0,0 +1,160 @@
import { PGlite } from '@electric-sql/pglite';
import { Socket } from 'net';
declare const CONNECTION_QUEUE_TIMEOUT = 60000;
/**
* Options for creating a PGLiteSocketHandler
*/
interface PGLiteSocketHandlerOptions {
/** The PGlite database instance */
db: PGlite;
/** Whether to close the socket when detached (default: false) */
closeOnDetach?: boolean;
/** Print the incoming and outgoing data to the console in hex and ascii */
inspect?: boolean;
/** Enable debug logging of method calls */
debug?: boolean;
}
/**
* Low-level handler for a single socket connection to PGLite
* Handles the raw protocol communication between a socket and PGLite
*/
declare class PGLiteSocketHandler extends EventTarget {
readonly db: PGlite;
private socket;
private active;
private closeOnDetach;
private resolveLock?;
private rejectLock?;
private inspect;
private debug;
private readonly id;
private static nextHandlerId;
/**
* Create a new PGLiteSocketHandler
* @param options Options for the handler
*/
constructor(options: PGLiteSocketHandlerOptions);
/**
* Get the unique ID of this handler
*/
get handlerId(): number;
/**
* Log a message if debug is enabled
* @private
*/
private log;
/**
* Attach a socket to this handler
* @param socket The socket to attach
* @returns this handler instance
* @throws Error if a socket is already attached
*/
attach(socket: Socket): Promise<PGLiteSocketHandler>;
/**
* Detach the current socket from this handler
* @param close Whether to close the socket when detaching (overrides constructor option)
* @returns this handler instance
*/
detach(close?: boolean): PGLiteSocketHandler;
/**
* Check if a socket is currently attached
*/
get isAttached(): boolean;
/**
* Handle incoming data from the socket
*/
private handleData;
/**
* Handle errors from the socket
*/
private handleError;
/**
* Handle socket close event
*/
private handleClose;
/**
* Print data in hex and ascii to the console
*/
private inspectData;
}
/**
* Options for creating a PGLiteSocketServer
*/
interface PGLiteSocketServerOptions {
/** The PGlite database instance */
db: PGlite;
/** The port to listen on (default: 5432) */
port?: number;
/** The host to bind to (default: 127.0.0.1) */
host?: string;
/** Unix socket path to bind to (default: undefined). If specified, takes precedence over host:port */
path?: string;
/** Print the incoming and outgoing data to the console in hex and ascii */
inspect?: boolean;
/** Connection queue timeout in milliseconds (default: 10000) */
connectionQueueTimeout?: number;
/** Enable debug logging of method calls */
debug?: boolean;
}
/**
* High-level server that manages socket connections to PGLite
* Creates and manages a TCP server and handles client connections
*/
declare class PGLiteSocketServer extends EventTarget {
readonly db: PGlite;
private server;
private port?;
private host?;
private path?;
private active;
private inspect;
private debug;
private connectionQueueTimeout;
private activeHandler;
private connectionQueue;
private handlerCount;
/**
* Create a new PGLiteSocketServer
* @param options Options for the server
*/
constructor(options: PGLiteSocketServerOptions);
/**
* Log a message if debug is enabled
* @private
*/
private log;
/**
* Start the socket server
* @returns Promise that resolves when the server is listening
*/
start(): Promise<void>;
getServerConn(): string;
/**
* Stop the socket server
* @returns Promise that resolves when the server is closed
*/
stop(): Promise<void>;
/**
* Get the active handler ID, or null if no active handler
*/
private get activeHandlerId();
/**
* Handle a new client connection
*/
private handleConnection;
/**
* Add a connection to the queue
*/
private enqueueConnection;
/**
* Process the next connection in the queue
*/
private processNextInQueue;
/**
* Attach a socket to a new handler
*/
private attachSocketToNewHandler;
}
export { CONNECTION_QUEUE_TIMEOUT, PGLiteSocketHandler, type PGLiteSocketHandlerOptions, PGLiteSocketServer, type PGLiteSocketServerOptions };

View File

@@ -0,0 +1,2 @@
import{a,b,c}from"./chunk-F6KLIXM7.js";export{a as CONNECTION_QUEUE_TIMEOUT,b as PGLiteSocketHandler,c as PGLiteSocketServer};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
#!/usr/bin/env node

View File

@@ -0,0 +1 @@
#!/usr/bin/env node

View File

@@ -0,0 +1,19 @@
#!/usr/bin/env node
import{c as d}from"../chunk-F6KLIXM7.js";import{PGlite as h}from"@electric-sql/pglite";import{parseArgs as u}from"node:util";import{spawn as p}from"node:child_process";var r=u({options:{db:{type:"string",short:"d",default:"memory://",help:"Database path (relative or absolute). Use memory:// for in-memory database."},port:{type:"string",short:"p",default:"5432",help:"Port to listen on"},host:{type:"string",short:"h",default:"127.0.0.1",help:"Host to bind to"},path:{type:"string",short:"u",default:void 0,help:"unix socket to bind to. Takes precedence over host:port"},debug:{type:"string",short:"v",default:"0",help:"Debug level (0-5)"},extensions:{type:"string",short:"e",default:void 0,help:"Comma-separated list of extensions to load (e.g., vector,pgcrypto)"},run:{type:"string",short:"r",default:void 0,help:"Command to run after server starts"},"include-database-url":{type:"boolean",default:!1,help:"Include DATABASE_URL in the environment of the subprocess"},"shutdown-timeout":{type:"string",default:"5000",help:"Timeout in milliseconds for graceful subprocess shutdown (default: 5000)"},help:{type:"boolean",short:"?",default:!1,help:"Show help"}}}),g=`PGlite Socket Server
Usage: pglite-server [options]
Options:
-d, --db=PATH Database path (default: memory://)
-p, --port=PORT Port to listen on (default: 5432)
-h, --host=HOST Host to bind to (default: 127.0.0.1)
-u, --path=UNIX Unix socket to bind to (default: undefined). Takes precedence over host:port
-v, --debug=LEVEL Debug level 0-5 (default: 0)
-e, --extensions=LIST Comma-separated list of extensions to load
Formats: vector, pgcrypto (built-in/contrib)
@org/package/path:exportedName (npm package)
-r, --run=COMMAND Command to run after server starts
--include-database-url Include DATABASE_URL in subprocess environment
--shutdown-timeout=MS Timeout for graceful subprocess shutdown in ms (default: 5000)
`,l=class{constructor(e){this.db=null;this.server=null;this.subprocessManager=null;this.config=e}static parseConfig(){let e=r.values.extensions;return{dbPath:r.values.db,port:parseInt(r.values.port,10),host:r.values.host,path:r.values.path,debugLevel:parseInt(r.values.debug,10),extensionNames:e?e.split(",").map(o=>o.trim()):void 0,runCommand:r.values.run,includeDatabaseUrl:r.values["include-database-url"],shutdownTimeout:parseInt(r.values["shutdown-timeout"],10)}}createDatabaseUrl(){let{host:e,port:o,path:t}=this.config;if(t){let s=t.endsWith("/.s.PGSQL.5432")?t.slice(0,-13):t;return`postgresql://postgres:postgres@/postgres?host=${encodeURIComponent(s)}`}else return`postgresql://postgres:postgres@${e}:${o}/postgres`}async importExtensions(){if(!this.config.extensionNames?.length)return;let e={},o=["vector","live","pg_hashids","pg_ivm","pg_uuidv7","pgtap"];for(let t of this.config.extensionNames){let s=null;try{if(t.includes(":")){let[i,n]=t.split(":");if(!i||!n)throw new Error(`Invalid extension format '${t}'. Expected: package/path:exportedName`);s=(await import(i))[n],s&&(e[n]=s,console.log(`Imported extension '${n}' from '${i}'`))}else if(o.includes(t))s=(await import(`@electric-sql/pglite/${t}`))[t],s&&(e[t]=s,console.log(`Imported extension: ${t}`));else{try{s=(await import(`@electric-sql/pglite/contrib/${t}`))[t]}catch{s=(await import(`@electric-sql/pglite-${t}`))[t]}s&&(e[t]=s,console.log(`Imported extension: ${t}`))}}catch(i){throw console.error(`Failed to import extension '${t}':`,i),new Error(`Failed to import extension '${t}'`)}}return Object.keys(e).length>0?e:void 0}async initializeDatabase(){console.log(`Initializing PGLite with database: ${this.config.dbPath}`),console.log(`Debug level: ${this.config.debugLevel}`);let e=await this.importExtensions();this.db=new h(this.config.dbPath,{debug:this.config.debugLevel,extensions:e}),await this.db.waitReady,console.log("PGlite database initialized")}setupServerEventHandlers(){if(!this.server||!this.subprocessManager)throw new Error("Server or subprocess manager not initialized");this.server.addEventListener("listening",e=>{let o=e.detail;if(console.log(`PGLiteSocketServer listening on ${JSON.stringify(o)}`),this.config.runCommand&&this.subprocessManager){let t=this.createDatabaseUrl();this.subprocessManager.spawn(this.config.runCommand,t,this.config.includeDatabaseUrl)}}),this.server.addEventListener("connection",e=>{let{clientAddress:o,clientPort:t}=e.detail;console.log(`Client connected from ${o}:${t}`)}),this.server.addEventListener("error",e=>{let o=e.detail;console.error("Socket server error:",o)})}setupSignalHandlers(){process.on("SIGINT",()=>this.shutdown()),process.on("SIGTERM",()=>this.shutdown())}async start(){try{if(await this.initializeDatabase(),!this.db)throw new Error("Database initialization failed");this.server=new d({db:this.db,port:this.config.port,host:this.config.host,path:this.config.path,inspect:this.config.debugLevel>0}),this.subprocessManager=new c(e=>{this.shutdown(e)}),this.setupServerEventHandlers(),this.setupSignalHandlers(),await this.server.start()}catch(e){throw console.error("Failed to start PGLiteSocketServer:",e),e}}async shutdown(e=0){console.log(`
Shutting down PGLiteSocketServer...`),this.subprocessManager&&this.subprocessManager.terminate(this.config.shutdownTimeout),this.server&&await this.server.stop(),this.db&&await this.db.close(),console.log("Server stopped"),process.exit(e)}},c=class{constructor(e){this.childProcess=null;this.onExit=e}get process(){return this.childProcess}spawn(e,o,t){console.log(`Running command: ${e}`);let s={...process.env};t&&(s.DATABASE_URL=o,console.log(`Setting DATABASE_URL=${o}`));let i=e.trim().split(/\s+/);this.childProcess=p(i[0],i.slice(1),{env:s,stdio:"inherit"}),this.childProcess.on("error",n=>{console.error("Error running command:",n),console.log("Subprocess failed to start, shutting down..."),this.onExit(1)}),this.childProcess.on("close",n=>{console.log(`Command exited with code ${n}`),this.childProcess=null,n!==null&&n!==0&&(console.log(`Child process failed with exit code ${n}, shutting down...`),this.onExit(n))})}terminate(e){this.childProcess&&(console.log("Terminating child process..."),this.childProcess.kill("SIGTERM"),setTimeout(()=>{this.childProcess&&!this.childProcess.killed&&(console.log("Force killing child process..."),this.childProcess.kill("SIGKILL"))},e))}};async function m(){r.values.help&&(console.log(g),process.exit(0));try{let a=l.parseConfig();await new l(a).start()}catch(a){console.error("Unhandled error:",a),process.exit(1)}}m();
//# sourceMappingURL=server.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,29 @@
import globals from 'globals'
import rootConfig from '../../eslint.config.js'
export default [
...rootConfig,
{
ignores: ['release/**/*', 'examples/**/*', 'dist/**/*'],
},
{
languageOptions: {
globals: {
...globals.browser,
...globals.node,
},
},
rules: {
...rootConfig.rules,
'@typescript-eslint/no-explicit-any': 'off',
},
},
{
files: ['tests/targets/deno/**/*.js'],
languageOptions: {
globals: {
Deno: false,
},
},
},
]

View File

@@ -0,0 +1,76 @@
import { PGLiteSocketServer } from '../src'
import { PGlite, DebugLevel } from '@electric-sql/pglite'
/*
* This is a basic example of how to use the PGLiteSocketServer class.
* It creates a PGlite instance and a PGLiteSocketServer instance and starts the server.
* It also handles SIGINT to stop the server and close the database.
* You can run this example with the following command:
*
* ```bash
* pnpm tsx examples/basic-server.ts
* ```
* or with the handy script:
* ```bash
* pnpm example:basic-server
* ```
*
* You can set the host and port with the following environment variables:
*
* ```bash
* HOST=127.0.0.1 PORT=5432 DEBUG=1 pnpm tsx examples/basic-server.ts
* ```
*
* Debug level can be set to 0, 1, 2, 3, or 4.
*
* ```bash
* DEBUG=1 pnpm tsx examples/basic-server.ts
* ```
* You can also use a UNIX socket instead of the host:port
*
* ```bash
* UNIX=/tmp/.s.PGSQL.5432 DEBUG=1 pnpm tsx examples/basic-server.ts
* ```
*/
const UNIX = process.env.UNIX
const PORT = process.env.PORT ? parseInt(process.env.PORT) : 5432
const HOST = process.env.HOST ?? '127.0.0.1'
const DEBUG = process.env.DEBUG
? (parseInt(process.env.DEBUG) as DebugLevel)
: 0
// Create a PGlite instance
const db = await PGlite.create({
debug: DEBUG,
})
// Check if the database is working
console.log(await db.query('SELECT version()'))
// Create a PGLiteSocketServer instance
const server = new PGLiteSocketServer({
db,
port: PORT,
host: HOST,
path: UNIX,
inspect: !!DEBUG, // Print the incoming and outgoing data to the console
})
server.addEventListener('listening', (event) => {
const detail = (
event as CustomEvent<{ port: number; host: string } | { host: string }>
).detail
console.log(`Server listening on ${JSON.stringify(detail)}`)
})
// Start the server
await server.start()
// Handle SIGINT to stop the server and close the database
process.on('SIGINT', async () => {
await server.stop()
await db.close()
console.log('Server stopped and database closed')
process.exit(0)
})

Some files were not shown because too many files have changed in this diff Show More