Compare commits

...
4 Commits
Author SHA1 Message Date
floriano d137fec731 W pełni działające ulubione (do zrobienia wyszukiwanie) 2026-11-06 13:29:03 +01:00
aplikacje b3be59a011 Cars project 3 do dokończenia 2026-11-05 10:50:57 +01:00
aplikacje 3b96ac1be8 Cars cz. 2 2026-10-29 10:50:30 +01:00
aplikacje d60f8a91a7 Lekcja 08 projekt auta cz1 2026-10-22 10:52:16 +02:00
1575 changed files with 262062 additions and 0 deletions

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
{"ubezpieczony":"NIE","benzyna":"NIE","uszkodzony":"TAK","naped4x4":"NIE","model":"Ford Fiesta","_id":"2gdpmzYo0D3kQPWu"}
{"ubezpieczony":"NIE","benzyna":"TAK","uszkodzony":"TAK","naped4x4":"TAK","model":"Volvo V70","_id":"35rdbizIq28p0PwO"}
{"ubezpieczony":"TAK","benzyna":"NIE","uszkodzony":"NIE","naped4x4":"NIE","model":"Volvo S60","_id":"DxpP3rVTymsW4Zsd"}
{"ubezpieczony":"TAK","benzyna":"NIE","uszkodzony":"NIE","naped4x4":"NIE","model":"Volvo S60","_id":"ILJYjEqkiMuIqjWL"}
{"ubezpieczony":"NIE","benzyna":"TAK","uszkodzony":"TAK","naped4x4":"NIE","model":"Fiat Siesta","_id":"MZjzNBYD8klZGOwy"}
{"ubezpieczony":"NIE","benzyna":"NIE","uszkodzony":"NIE","naped4x4":"NIE","model":"Ford Fiesta","_id":"VKKPOAVqTuz84yEa"}
{"ubezpieczony":"TAK","benzyna":"NIE","uszkodzony":"TAK","naped4x4":"TAK","model":"Volkswagen Polo","_id":"rpO881mPXDqGMLFX"}
+5
View File
@@ -0,0 +1,5 @@
{"user_id":2,"car_id":"2gdpmzYo0D3kQPWu","_id":"3mhqPX3J4yZDDYvN"}
{"user_id":2,"car_id":"ILJYjEqkiMuIqjWL","_id":"HJ7xXCTl8hyNP3W5"}
{"user_id":2,"car_id":"DxpP3rVTymsW4Zsd","_id":"JUTgHyLKjrj8eihk"}
{"user_id":2,"car_id":"rpO881mPXDqGMLFX","_id":"nQArHJx10blxgheV"}
{"user_id":1,"car_id":"2gdpmzYo0D3kQPWu","_id":"q9Fb66vM1I3B47yg"}
+354
View File
@@ -0,0 +1,354 @@
const DS = require('@seald-io/nedb');
const express = require('express');
const { create } = require('express-handlebars');
const path = require('path');
const cookie_parser = require('cookie-parser');
const cookie_secret_key = 'SprzedamOplaZaDwaZlote';
const app = express();
const PORT = 3000;
const DB = new DS({
filename: 'data/cars.db',
autoload: true
});
const favDB = new DS({
filename: 'data/favourites.db',
autoload: true
});
const hbs = create({
defaultLayout: 'main.hbs',
extname: '.hbs',
helpers: {
equ(p, q) {
return p == q;
},
gte(p, q) {
return p >= q;
}
}
});
app.engine('.hbs', hbs.engine);
app.set('view engine', '.hbs');
app.set('views', path.join(__dirname, 'views'));
app.use(cookie_parser(cookie_secret_key));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
const users = [
{
id: 1,
username: 'admin',
unsafe_password: '123',
privilege_level: 2
},
{
id: 2,
username: 'user',
unsafe_password: '123',
privilege_level: 1
}
];
const model = [
"Ford Fiesta",
"Fiat Siesta",
"Volkswagen Polo",
"Volvo V70",
"Volvo S60",
"Newag Impuls"
];
// logowanie i walidacja użytkownika
const get_privileges = function (req, res, next) {
let privilege_level = 0;
if (req.signedCookies.user) {
let userIndex = users.findIndex(user => user.id == req.signedCookies.user.id);
privilege_level = users[userIndex].privilege_level;
}
req.privilege_level = privilege_level;
next();
};
app.post("/login", function (req, res) {
let user = users.find(user => user.username == req.body.login);
if (user && user.unsafe_password == req.body.password) {
res.cookie("user",
{
"id": user.id,
"username": user.username,
"privilege_level": user.privilege_level
},
{ signed: true, maxAge: 1000 * 60 * 60 * 24 * 30 }
)
} else {
return res.redirect("/login?badcreds=true");
}
res.redirect("/");
});
app.get("/login", get_privileges, function (req, res) {
let ctx = {
privilege_level: req.privilege_level
};
if (req.query.badcreds) {
ctx.badcreds = true;
}
res.render("login.hbs", ctx);
});
app.get("/logout", function (req, res) {
res.clearCookie("user");
res.redirect("/");
});
/// routingi
app.get("/", get_privileges, function (req, res) {
let ctx = {
privilege_level: req.privilege_level
};
res.render('index.hbs', ctx);
});
app.post("/add", get_privileges, function (req, res) {
if (req.privilege_level < 2) {
return res.redirect("/");
}
let doc = {
ubezpieczony: req.body.ubezpieczony ? "TAK" : "NIE",
benzyna: req.body.benzyna ? "TAK" : "NIE",
uszkodzony: req.body.uszkodzony ? "TAK" : "NIE",
naped4x4: req.body.naped4x4 ? "TAK" : "NIE",
model: req.body.model
};
DB.insert(doc, function (err, new_doc) {
// ok
res.redirect(`/add?model=${doc.model}&id=${new_doc._id}`);
});
});
app.get("/add", get_privileges, function (req, res) {
if (req.privilege_level < 2) {
return res.redirect("/");
}
let r_model = model[Math.floor(Math.random() * model.length)]
let ctx = {
privilege_level: req.privilege_level,
"model": r_model
};
if (req.query.model && req.query.id) {
ctx.added_model = req.query.model
ctx.added_id = req.query.id
}
res.render("add.hbs", ctx);
});
app.get("/list", get_privileges, function (req, res) {
DB.find({}, function (err, docs) {
let ctx = {
privilege_level: req.privilege_level,
car: []
};
// sprawdz czy id jest w faworytach dla danego userid
favDB.find({ user_id: req.signedCookies.user.id }, function (f_err, f_docs) {
docs.forEach(doc => {
const n_doc = doc;
if(f_docs.find(f_doc => f_doc.car_id == doc._id)) {
n_doc.inFavs = true;
}
ctx.car.push(n_doc);
});
res.render('list.hbs', ctx);
});
});
});
app.get("/favourites", get_privileges, function (req, res) {
if (req.privilege_level < 1) {
return res.redirect("/");
}
let ctx = {
privilege_level: req.privilege_level
};
favDB.find({
user_id: req.signedCookies.user.id,
}, function (err, docs) {
let ids = [];
docs.forEach(doc => {
ids.push(doc.car_id);
})
DB.find({ _id: { $in: ids } }, function (err2, docs2) {
ctx.car = docs2;
res.render("favourites.hbs", ctx);
});
});
});
app.get("/fav", get_privileges, function (req, res) {
if (req.privilege_level < 1) {
return res.redirect("/");
}
let doc = {
user_id: req.signedCookies.user.id,
car_id: req.query.id
};
favDB.insert(doc, function (err, new_doc) {
res.redirect("/list");
});
});
app.get("/unfav", get_privileges, function (req, res) {
if (req.privilege_level < 1) {
return res.redirect("/");
}
favDB.remove({ car_id: req.query.id, user_id: req.signedCookies.user.id }, {}, function(err, numRemoved) {
console.log("odfaworytowano " + numRemoved);
if(req.query.return == 'favourites') {
return res.redirect("/favourites")
}
res.redirect("/list");
});
})
app.post("/delete", get_privileges, function (req, res) {
if (req.privilege_level < 2) {
return res.redirect("/");
}
console.log(req.body);
if (req.body.deletions) {
const deletions = [req.body.deletions].flat();
console.log(deletions);
deletions.forEach(deletion_id => {
DB.remove({ _id: deletion_id }, {}, function (err, numRemoved) {
console.log("Usunięto " + numRemoved + " dokument.");
});
});
}
res.redirect("/delete");
});
app.get("/delete", get_privileges, function (req, res) {
if (req.privilege_level < 2) {
return res.redirect("/");
}
DB.find({}, function (err, docs) {
let ctx = {
privilege_level: req.privilege_level,
car: docs
};
res.render('delete.hbs', ctx);
});
});
app.get("/deleteSpecific", get_privileges, function (req, res) {
if (req.privilege_level < 2) {
return res.redirect("/");
}
if (req.query.id) {
DB.remove({ _id: req.query.id }, {}, function (err, numRemoved) {
console.log("Usunięto " + numRemoved + " dokument.");
});
}
res.redirect("/delete");
});
app.get("/deleteAll", get_privileges, function (req, res) {
if (req.privilege_level < 2) {
return res.redirect("/");
}
DB.remove({}, { multi: true }, function (err, numRemoved) {
console.log("usunięto dokumentów: " + numRemoved);
});
res.redirect("/delete");
});
app.post("/edit", get_privileges, function (req, res) {
if (req.privilege_level < 2) {
return res.redirect("/");
}
DB.update({ _id: req.body._id }, { $set: req.body }, {}, function (err, numUpdated) {
console.log('Zaktualizowano ' + numUpdated + ' dokumentów.');
});
res.redirect("/edit");
});
app.get("/edit", get_privileges, function (req, res) {
if (req.privilege_level < 2) {
return res.redirect("/");
}
DB.find({}, function (err, docs) {
let ctx = {
privilege_level: req.privilege_level,
car: []
};
docs.forEach(doc => {
if (doc._id == req.query.id) {
doc.edycja = true;
}
ctx.car.push(doc);
})
res.render('edit.hbs', ctx);
});
});
app.post("/search", function (req, res) {
console.log(req.body);
// do dokończenia tutaj
});
app.get("/search", get_privileges, function (req, res) {
DB.find({}, function (err, docs) {
let ctx = {
privilege_level: req.privilege_level,
car: docs
};
res.render('search.hbs', ctx);
});
})
/// --------
app.use(express.static('static'))
app.listen(PORT, function () {
console.log(`Listening on ${PORT}`)
})
+16
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/../handlebars/bin/handlebars" "$@"
else
exec node "$basedir/../handlebars/bin/handlebars" "$@"
fi
+17
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%\..\handlebars\bin\handlebars" %*
+28
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/../handlebars/bin/handlebars" $args
} else {
& "$basedir/node$exe" "$basedir/../handlebars/bin/handlebars" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../handlebars/bin/handlebars" $args
} else {
& "node$exe" "$basedir/../handlebars/bin/handlebars" $args
}
$ret=$LASTEXITCODE
}
exit $ret
+16
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/../uglify-js/bin/uglifyjs" "$@"
else
exec node "$basedir/../uglify-js/bin/uglifyjs" "$@"
fi
+17
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%\..\uglify-js\bin\uglifyjs" %*
+28
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/../uglify-js/bin/uglifyjs" $args
} else {
& "$basedir/node$exe" "$basedir/../uglify-js/bin/uglifyjs" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../uglify-js/bin/uglifyjs" $args
} else {
& "node$exe" "$basedir/../uglify-js/bin/uglifyjs" $args
}
$ret=$LASTEXITCODE
}
exit $ret
+1342
View File
File diff suppressed because it is too large. Load diff
+55
View File
@@ -0,0 +1,55 @@
# Blue Oak Model License
Version 1.0.0
## Purpose
This license gives everyone as much permission to work with
this software as possible, while protecting contributors
from liability.
## Acceptance
In order to receive this license, you must agree to its
rules. The rules of this license are both obligations
under that agreement and conditions to your license.
You must not do anything with this software that triggers
a rule that you cannot or will not follow.
## Copyright
Each contributor licenses you to do everything with this
software that would otherwise infringe that contributor's
copyright in it.
## Notices
You must ensure that everyone who gets a copy of
any part of this software from you, with or without
changes, also gets the text of this license or a link to
<https://blueoakcouncil.org/license/1.0.0>.
## Excuse
If anyone notifies you in writing that you have not
complied with [Notices](#notices), you can keep your
license by taking all practical steps to comply within 30
days after the notice. If you do not do so, your license
ends immediately.
## Patent
Each contributor licenses you to do everything with this
software that would otherwise infringe any patent claims
they can license or become able to license.
## Reliability
No contributor can revoke this license.
## No Liability
***As far as the law allows, this software comes as is,
without any warranty or condition, and no contributor
will be liable to anyone for any damages related to this
software or this license, under any kind of legal claim.***
+333
View File
@@ -0,0 +1,333 @@
# @isaacs/nonrecursive-glob-match
This is a glob matcher that can be applied to a single path
portion (ie, not `/`), which completes in polynomial time because
it doesn't compile to Regular Expressions or any other
backtrack-dependent algorithm.
## USAGE
```ts
import { Matcher } from '@isaacs/nonrecursive-glob-match'
const m = new Matcher('a*a!(y|z)')
console.log(m.test('abcay')) // false
console.log(m.test('abcax')) // true
console.log(m.test('aa')) // true
```
The pattern and the tested string must be a single path portion.
If either one contains a `/` character, the matcher throws an
error.
If you already split a path on `/`, use `m.testUnchecked(s)`. It
gives the same result as `m.test(s)`, but it does not check `s`
for a `/` character. This can make it faster, because some
patterns, such as `*.js`, then do not need to look at each
character. If `s` has a `/`, the result is not defined.
## Why
Patterns like this frustrate most glob matchers: `a*a*a*a*a*a*a`.
They can be used to take down servers if applied to untrusted
input. Fixing these vulns is like playing whack-a-mole with the
whole internet.
If compiled to a regular expression like
`/^a[^/]*a[^/]*a[^/]*a[^/]*a[^/]*a[^/]*a$/`, and then applied to
a path portion like `aaaaaaaaaaaaaaaaaaab`, the engine must check
every possible path through the pattern, constantly rewinding
back to the first character each time and trying a different
number of `a` characters matched against the `[^/]*` to see if it
matches. Because nothing matches, it must test every possible
path before ultimately giving up.
In contrast, the algorithm presented here is based on the
Thompson NFA paper from 1968, which tests every possible path
through the string at the same time, so that it only has to walk
the string one time. This algorithm is also implemented in the
RegExp engines used by `egrep` and `awk`, which is why those
tools are so fast, even when matching complicated RegExps against
extremely large strings.
The `Matcher` objects have a `test` method which takes a string,
just like a `RegExp` object, and can be a drop-in replacement for
the regular expressions used in minimatch and other matchers.
However, they are _not_ a complete drop-in replacement for a
RegExp, so be careful when replacing one with the other. (For
example, they do not capture, do not track match indexes, no
fancy RegExp features, etc.)
## Patterns Supported
Here are the patterns supported, and their effective state
machines drawn in lovely ASCII diagrams.
### `*` 0 or more of any character, not starting with `.`
```
--+-------------------+->
v ^
+<------------------+
v ^
+-->any character-->+
```
### `?`
```
-->any character-->
```
### `[<set>]`
```
-->character in set-->
```
This covers named posix sets like `[[:alpha:]]` as well as
character classes like `[a-b]`. (In this case, a regular
expression actually is compiled, but it's not subject to ReDoS,
becuase it's just a `/[a-z]/` style pattern tested against one
character at a time.)
### `@(e1|e2|...)`
"One" extglob.
```
--+--> e1 -->+-->
v ^
+--> e2 -->+
v ^
+--> e3 -->+
v ... ^
```
### `?(e1|e2|...)`
"Zero or one" extglob.
```
--+--------->+-->
v ^
+--> e1 -->+
v ^
+--> e2 -->+
v ^
+--> e3 -->+
v ... ^
```
### `*(e1|e2|...)`
"Zero or more" extglob.
```
--+--------->+-->
v ^
+<---------+
v ^
+--> e1 -->+
v ^
+--> e2 -->+
v ^
+--> e3 -->+
v ... ^
```
### `+(e1|e2|...)`
"One or more" extglob.
```
+<---------+
v ^
--+--> e1 -->+-->
v ^
+--> e2 -->+
v ^
+--> e3 -->+
v ... ^
```
### `!(e1|e2|...)`
"Negative" extglob.
The challenge with negation is that it opens the door to a whole
heap of edge cases. Especially, _any_ expression can be nested
inside the negation, and it needs to match anything at all, as
long as it _doesn't_ match one of the supplied patterns. This is
where it gets complicated, and past attempts have run into
problems.
We handle this by starting a "Run" that technically does recurse,
and thus can push the performance out from `O(n * m)` to
`O(n * m * r)` where `n` is the string length, `m` is the pattern
length, and `r` is the number of negative extglob portions it
contains. In practice, this is limited by the pattern length, and
still doesn't allow ReDOS-style explosive recursive backtracking,
so this is fine.
## Unicode Normalization
A char such as `é` can be one code point (U+00E9), or `e`
followed by a combining accent (U+0301). Some file systems, such
as on macOS, can give file names in the second form. These two
forms do not match by default.
Set the `normalize` option to normalize the pattern and each
tested string to the same form. Use `'NFC'`, `'NFD'`, `'NFKC'`,
or `'NFKD'`. `true` means `'NFC'`.
```ts
const m = new Matcher('café', { normalize: true })
m.test('café') // true
```
- Use NFC if you are not sure. With NFD and NFKD, `é` is two
code points. Then `?` does not match `é`, and `[é]` can not
match it.
- NFKC and NFKD also fold compatibility chars. For example, `fi`
matches `fi`, and full-width `A` matches `A`.
- Syntax is parsed before normalization. So, a char that
normalizes to a syntax char stays a literal. For example, with
NFKC, full-width `*` matches only `*` or `*`, and it is not a
wildcard.
- Each run of literal chars normalizes as one string. Each member
of a `[...]` class normalizes on its own, and stays as it is if
its normal form is more than one code point.
- A combining mark after a wildcard is its own literal, and does
not compose with the char that the wildcard matches. So, with
NFC, `?́` does not match `é`. With NFD, it does match,
because `é` is also two code points in the string. Patterns
match code points, not grapheme clusters.
- With `nocase`, normalization comes first, then case folding.
- The `/` check uses the strings as given. So, full-width `/`
does not cause an error.
## Differences from Bash
Bash 5 is the reference for this module, with two known
deviations.
### Dotfiles
If `dot` is not set, a string that starts with `.` only matches
if a literal `.` in the pattern matches that first character.
Extglobs before that `.` can match the empty string, and the
pattern can still match. For example, `!(.a|js)@(.*)` matches
`.a`, `.a.js`, and `.js`, because `!(.a|js)` matches the empty
string, and `@(.*)` matches the rest. Bash does not match these
dotfiles. See [this bug
report](https://lists.gnu.org/archive/html/bug-bash/2026-03/msg00034.html).
A `*` can never match at the start of a dotfile, even if it
matches the empty string. So, `*.js` does not match `.js`, as in
Bash.
### Case-insensitive matching
Bash compares chars with the case functions of the C library for
the current locale. So, the results can change with the locale
and the platform.
With `nocase`, this module uses Unicode simple case folding, one
code point at a time. This is the same folding that a JavaScript
RegExp uses with the `iu` flags. It does not change with the
locale, and literals, `[...]` classes, and ranges all use it.
- `Σ`, `σ`, and final sigma `ς` all match each other.
- The micro sign `µ` matches `μ` and `Μ`. The Kelvin sign `K`
matches `k`. The Angstrom sign `Å` matches `å`.
- `ẞ` matches `ß`, but `ß` does not match `ss`. A fold never
changes the number of chars, so ligatures such as `fi` do not
match `fi`.
- There are no Turkish rules. `I` matches `i`, but dotted `İ`
and dotless `ı` only match themselves.
## Algorithm
A glob pattern is parsed and compiled into a series of attached
state machines.
For example, the glob patttern `*(a|[c-d]|+(x|y|z))z` would
compile to a state machine something like the following flow
diagram:
```
-->+----------------------->+-->8 LITERAL(z)-->9 end
v ^
+<-----------------------6
v ^
0-->LITERAL(a)---------->|
v |
1-->CLASS(c-d)---------->|
v |
2-->+<---------------+-->+
v ^
3-->LITERAL(x)-->7
v |
4-->LITERAL(y)-->|
v |
5-->LITERAL(z)-->+
```
Then, for each character in the string, we walk through the
resulting graph until we find a test node.
These test nodes are all executed on the current character, and
for any tests pass, their output nodes are added to the walk, and
we proceed to walk until hitting a test node again.
Because all routes eventually get to the exit, which only passes
when the string is at its last character, we are guaranteed to
eventually either fail (and have no more states to process), or
exit with a match.
At each branching point, effectively we increase the memory usage
by a tiny bit to track which nodes are being processed, but
importantly, we _don't_ have to try all the way to the exit and
then backtrack recursively, storing multiple states of the string
in an exponential explosion.
A pattern like `a*a*a*a*a*a*a*a*a*a*a`, which could be naively
converted into a Regular Expression
`^a.*a.*a.*a.*a.*a.*a.*a.*a.*a.*a$`, would take over 33 seconds
to match the string `'a'.repeat(50) + 'b'` using standard
JavaScript regular expressions, because it must attempt every
possible grouping of characters, backtracking after each failure.
By contrast, this implementation can solve this match for either
a pass or failure in roughly the same amount of time, which
is bound by `C * N`, where `C` is the number of states in the
machine, and `N` is the length of the string, finishing both
failure and success cases in polynomial time.
Even on the first rather naive implementation in JavaScript, with
no optimizations for repeated `*` or other common tweaks, this
finishes in 300-400 µs for the pathological case described, and
as the numbers increase, this time rises roughly linearly.
That's somewhat worse than RegExp's performance in the _success_
case, which is around 40µs, but as it's around 100,000x faster in
the failure case, this is already quite promising. And, future
iterations of this can likely bring that performance closer to
the native RegExp implementation.
## Acknowledgement
The algorithm and ideas in this implementation are inspired,
borrowed, and at times outright stolen from [Russ
Cox](https://research.swtch.com)'s explanation of Ken Thompson's
work in [Regular Expression Matching Can Be Simple And
Fast](https://swtch.com/~rsc/regexp/regexp1.html). I am both
impressed by and grateful for their work.
The code here in this library was written entirely by me, [Isaac
Z. Schlueter](https://izs.me), and so you should not blame either
of them (or anyone else) for any problems it might have. You
should also not blame me. It's open source, after all, no
warrantees express or implied, etc.
@@ -0,0 +1,114 @@
import { type Form } from './parse-class.js';
export type { Form };
export type MatcherOptions = {
/** perform a case-insensitive match */
nocase?: boolean;
/** do not treat strings starting with `.` specially */
dot?: boolean;
/** do not match extglobs (treat them as normal strings) */
noext?: boolean;
/**
* normalize unicode in the pattern and the tested strings, with
* this form. `true` means `'NFC'`.
*/
normalize?: boolean | Form;
};
export type Item = {
t: 'lit';
ch: string;
} | {
t: 'any' | 'star';
} | {
t: 'class';
re: RegExp;
} | {
t: 'ext';
type: string;
alts: Item[][];
};
export type Token = Item | {
t: 'open';
type: string;
} | {
t: 'bar';
} | {
t: 'close';
};
export type NegNode = {
t: 'neg';
id: number;
sub: Node;
next: Node;
};
export type SplitNode = {
t: 'split';
id: number;
out: Node[];
};
export type Node = ({
t: 'lit';
id: number;
next: Node;
} & Lit) | {
t: 'any' | 'star';
id: number;
next: Node;
} | {
t: 'class';
id: number;
re: RegExp;
next: Node;
} | SplitNode | NegNode | {
t: 'match';
id: number;
};
/**
* A literal char. With `nocase:true`, `re` folds case, and `ascii`
* holds its results for ASCII chars, by char code: 1 for a match,
* and 2 for not.
*/
export type Lit = {
ch: string;
re?: RegExp;
ascii?: Uint8Array;
};
/**
* For each node id, the gen of the last state that has the node as
* a thread, and of the last state that walked through it. A state is
* built to the end before the states around it go on, and the nodes
* of a negated sub-pattern are only in its states (other than the
* match node, which is never marked). So one mark for each node is
* enough to know if the state being built has it. The Sims of a
* matcher never run at the same time, so they share one Marks.
*/
export type Marks = {
has: Float64Array;
seen: Float64Array;
gen: number;
};
/**
* A node in a graph with no splits or negations. Such a graph is a
* chain of nodes that each match one char, or a `*`.
*/
export type LinearNode = Exclude<Node, SplitNode | NegNode | {
t: 'match';
}>;
export declare class Matcher {
#private;
pattern: string;
options: MatcherOptions;
constructor(pattern: string, options?: MatcherOptions);
test(s: string): boolean;
/**
* The same as {@link Matcher#test}, but the string is not checked
* for `/` chars, so the result for a string that has one is not
* defined. Only use it for a string that is known to be one path
* portion, such as a part of a path that was split on `/`. It can
* be faster, because some patterns do not need to look at each char
* of the string.
*/
testUnchecked(s: string): boolean;
/** a readable listing of the state machine */
toString(): string;
}
//# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,IAAI,EAAc,MAAM,kBAAkB,CAAA;AAExD,YAAY,EAAE,IAAI,EAAE,CAAA;AAEpB,MAAM,MAAM,cAAc,GAAG;IAC3B,uCAAuC;IACvC,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,uDAAuD;IACvD,GAAG,CAAC,EAAE,OAAO,CAAA;IACb,2DAA2D;IAC3D,KAAK,CAAC,EAAE,OAAO,CAAA;IACf;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,GAAG,IAAI,CAAA;CAC3B,CAAA;AAGD,MAAM,MAAM,IAAI,GACZ;IAAE,CAAC,EAAE,KAAK,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GACxB;IAAE,CAAC,EAAE,KAA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;GAIG;AACH,MAAM,MAAM,GAAG,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,UAAU,CAAA;CAAE,CAAA;AAgPjE;;;;;;;;GAQG;AACH,MAAM,MAAM,KAAK,GAAG;IAAE,GAAG,EAAE,YAAY,CAAC;IAAC,IAAI,EAAE,YAAY,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAAA;AA8P1E;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,OAAO,CAC9B,IAAI,EACJ,SAAS,GAAG,OAAO,GAAG;IAAE,CAAC,EAAE,OAAO,CAAA;CAAE,CACrC,CAAA;AA8GD,qBAAa,OAAO;;IAClB,OAAO,EAAE,MAAM,CAAA;IACf,OAAO,EAAE,cAAc,CAAA;gBAmCX,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB;IAuDzD,IAAI,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO;IAexB;;;;;;;OAOG;IACH,aAAa,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO;IAwFjC,8CAA8C;IAC9C,QAAQ,IAAI,MAAM;CAGnB"}
@@ -0,0 +1,762 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Matcher = void 0;
const parse_class_js_1 = require("./parse-class.js");
// the end of the pattern, or of a negated sub-pattern
const MATCH = { t: 'match', id: 0 };
const extTypes = '!?+*@';
const lit = (ch) => ({ t: 'lit', ch });
const reEscape = (s) => s.replace(/[\\^$.*+?()[\]{}|/]/g, '\\$&');
// a RegExp that only matches `s`, with unicode case folding
const newFoldRe = (s) => new RegExp(`^${reEscape(s)}$`, 'iu');
// foldRe for one literal char. The same chars are in most patterns,
// so keep them. A RegExp without the `g` or `y` flag has no state to
// share.
const foldCache = new Map();
const foldRe = (ch) => {
let re = foldCache.get(ch);
if (!re) {
re = newFoldRe(ch);
if (foldCache.size >= 1000)
foldCache.clear();
foldCache.set(ch, re);
}
return re;
};
const litMatch = (l, c) => {
if (c === l.ch)
return true;
if (!l.re)
return false;
const code = c.charCodeAt(0);
if (code >= 128)
return l.re.test(c);
const ascii = (l.ascii ??= new Uint8Array(128));
ascii[code] ||= l.re.test(c) ? 1 : 2;
return ascii[code] === 1;
};
const tokenize = (p, nocase, noext, form) => {
const toks = [];
for (let i = 0; i < p.length;) {
const c = String.fromCodePoint(p.codePointAt(i));
if (c === '\\') {
// a trailing \ is a literal \
const e = p.codePointAt(i + 1);
const ch = e === undefined ? c : String.fromCodePoint(e);
toks.push(lit(ch));
i += 1 + ch.length;
continue;
}
if (c === '[') {
const [re, consumed] = (0, parse_class_js_1.parseClass)(p, i, nocase, form);
if (consumed) {
toks.push({ t: 'class', re });
i += consumed;
continue;
}
}
if (!noext && extTypes.includes(c) && p[i + 1] === '(') {
toks.push({ t: 'open', type: c });
i += 2;
continue;
}
toks.push(!noext && c === '|' ? { t: 'bar' }
: !noext && c === ')' ? { t: 'close' }
: c === '*' ? { t: 'star' }
: c === '?' ? { t: 'any' }
: lit(c));
i += c.length;
}
return toks;
};
// map each open token index to the index of its close token
const pair = (toks) => {
const pairs = new Map();
const stack = [];
toks.forEach((tok, i) => {
if (tok.t === 'open')
stack.push(i);
else if (tok.t === 'close' && stack.length)
pairs.set(stack.pop(), i);
});
return pairs;
};
// build the alternatives between start and end. An open token that
// is not closed is never inside a closed extglob, so bar and close
// tokens are only literal at the top level.
const build = (toks, pairs, start, end, top) => {
let seq = [];
const alts = [seq];
for (let i = start; i < end; i++) {
const tok = toks[i];
const close = pairs.get(i);
if (tok.t === 'open' && close !== undefined) {
const sub = build(toks, pairs, i + 1, close, false);
seq.push({ t: 'ext', type: tok.type, alts: sub });
i = close;
}
else if (tok.t === 'bar' && !top) {
alts.push((seq = []));
}
else if (tok.t === 'open') {
seq.push(lit(tok.type), lit('('));
}
else if (tok.t === 'bar') {
seq.push(lit('|'));
}
else if (tok.t === 'close') {
seq.push(lit(')'));
}
else {
seq.push(tok);
}
}
return alts;
};
// normalize each run of literal chars as one string, so that a char
// and the combining marks after it compose (or decompose) together.
// Syntax is already parsed, so a char that normalizes to a syntax
// char (such as full-width `*` in NFKC) stays a literal.
const normalize = (items, form) => {
const out = [];
let run = '';
const flush = () => {
for (const ch of run.normalize(form))
out.push(lit(ch));
run = '';
};
for (const it of items) {
if (it.t === 'lit') {
run += it.ch;
continue;
}
flush();
out.push(it.t === 'ext' ?
{ ...it, alts: it.alts.map(a => normalize(a, form)) }
: it);
}
flush();
return out;
};
// the start node, and the number of node ids. Ids are dense, from 0
// for the match node.
const compile = (items, nocase) => {
let id = 1;
const split = (out) => ({ t: 'split', id: id++, out });
const seq = (items, next) => items.reduceRight((next, it) => item(it, next), next);
const item = (it, next) => {
switch (it.t) {
case 'lit':
const re = nocase ? foldRe(it.ch) : undefined;
return { t: 'lit', id: id++, ch: it.ch, re, next };
case 'any':
case 'star':
return { t: it.t, id: id++, next };
case 'class':
return { t: 'class', id: id++, re: it.re, next };
}
const alts = (next) => it.alts.map(a => seq(a, next));
switch (it.type) {
case '@':
return split(alts(next));
case '?':
return split([next, ...alts(next)]);
case '!':
return { t: 'neg', id: id++, sub: split(alts(MATCH)), next };
}
// * and +, loop back after each match
const after = split([]);
const entry = split(alts(after));
after.out.push(next, entry);
return it.type === '*' ? after : entry;
};
const start = seq(items, MATCH);
return [start, id];
};
// one line per node, in the order that a walk from the start
// reaches them. Edges point to node ids. The nodes of a negated
// sub-pattern are indented under their negation.
const show = (start) => {
const lines = [];
const seen = new Set();
const ref = (n) => (n.t === 'match' ? 'match' : String(n.id));
const walk = (n, indent) => {
if (n.t === 'match' || seen.has(n))
return;
seen.add(n);
const line = (desc) => lines.push(`${indent}${n.id}: ${desc}`);
switch (n.t) {
case 'split':
line(`split -> ${n.out.map(ref).join(', ')}`);
for (const o of n.out)
walk(o, indent);
return;
case 'neg':
line(`!(${ref(n.sub)}) -> ${ref(n.next)}`);
walk(n.sub, indent + ' ');
return walk(n.next, indent);
case 'lit':
line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`);
break;
case 'class':
line(`${n.re} -> ${ref(n.next)}`);
break;
default:
line(`${n.t === 'any' ? '?' : '*'} -> ${ref(n.next)}`);
}
walk(n.next, indent);
};
walk(start, '');
return [`start -> ${ref(start)}`, ...lines].join('\n');
};
// The threads at one position in the string. Each node thread is
// only kept once, and runs with the same state are only kept once,
// so that identical threads merge. The match node is not in
// `threads`, because it can not step. It sets `match` instead.
class State {
// set by the Sim, to mark the nodes that this state has
gen;
threads = [];
match = false;
runs = [];
// the sorted ids of the threads, with 0 for a match, once the
// state is done
ids = [];
constructor(gen) {
this.gen = gen;
}
// no threads, so nothing more can match
get dead() {
return !this.threads.length && !this.match && !this.runs.length;
}
}
// true if the two states hold the same threads
const sameState = (a, b) => {
if (a.ids.length !== b.ids.length)
return false;
if (a.runs.length !== b.runs.length)
return false;
if (a.ids.some((id, i) => id !== b.ids[i]))
return false;
return a.runs.every(r => b.runs.some(o => o.neg === r.neg && sameState(o.state, r.state)));
};
const marks = (size) => ({
has: new Float64Array(size),
seen: new Float64Array(size),
gen: 0,
});
class Sim {
// `.` and `..` only match literal dots, even with `dot:true`
dots;
// the string starts with `.`, and `dot:true` is not set
dotStart;
#marks;
constructor(dots, dotStart, marks) {
this.dots = dots;
this.dotStart = dotStart;
this.#marks = marks;
}
state() {
return new State(++this.#marks.gen);
}
// sort the ids of a state, once it has all of its threads
done(state) {
state.ids = state.threads.map(n => n.id).sort((a, b) => a - b);
if (state.match)
state.ids.unshift(MATCH.id);
return state;
}
// true the first time that the state walks through the node, so
// that loops in the graph stop
#visit(state, node) {
const { seen } = this.#marks;
if (seen[node.id] === state.gen)
return false;
seen[node.id] = state.gen;
return true;
}
#addThread(state, node) {
const { has } = this.#marks;
if (has[node.id] === state.gen)
return false;
has[node.id] = state.gen;
state.threads.push(node);
return true;
}
// wildcards only match a leading dot if `dot:true`. In a negated
// sub-pattern, this does not apply, because the negation itself
// can not match a leading dot.
restricted(i, top) {
return top && (this.dots || (this.dotStart && i === 0));
}
add(state, node, i, top) {
switch (node.t) {
case 'split':
if (!this.#visit(state, node))
return;
for (const o of node.out)
this.add(state, o, i, top);
return;
case 'neg':
if (!this.#visit(state, node))
return;
const sub = this.state();
this.add(sub, node.sub, i, false);
this.done(sub);
return this.addRun(state, { t: 'run', neg: node, state: sub }, i, top);
case 'star':
// a * can not start a dotfile, even if it matches nothing
if (this.restricted(i, top))
return;
if (this.#addThread(state, node))
this.add(state, node.next, i, top);
return;
case 'match':
state.match = true;
return;
default:
this.#addThread(state, node);
}
}
addRun(state, run, i, top) {
for (const r of state.runs) {
if (r.neg === run.neg && sameState(r.state, run.state))
return;
}
state.runs.push(run);
if (!run.state.match) {
this.add(state, run.neg.next, i, top);
}
}
// the threads after char `c`, at index `i`
step(state, c, i, top) {
const next = this.state();
for (const th of state.threads) {
switch (th.t) {
case 'lit':
if (litMatch(th, c)) {
this.add(next, th.next, i + 1, top);
}
break;
case 'any':
if (!this.restricted(i, top))
this.add(next, th.next, i + 1, top);
break;
case 'class':
if (!this.restricted(i, top) && th.re.test(c)) {
this.add(next, th.next, i + 1, top);
}
break;
case 'star':
if (!this.restricted(i, top))
this.add(next, th, i + 1, top);
}
}
if (!this.restricted(i, top)) {
for (const run of state.runs) {
// a sub-pattern with no threads can not match again, so the
// run stays the same
if (run.state.dead) {
this.addRun(next, run, i + 1, top);
continue;
}
const sub = this.step(run.state, c, i, false);
this.addRun(next, { t: 'run', neg: run.neg, state: sub }, i + 1, top);
}
}
return this.done(next);
}
}
// A canonical key for the threads in a state. States with the same
// key hold the same threads, so they match the same strings.
const stateKey = (state) => {
const ids = state.ids.join();
if (!state.runs.length)
return ids;
const runs = state.runs.map(r => `${r.neg.id}(${stateKey(r.state)})`);
return `${ids}|${runs.sort().join('|')}`;
};
// The cache can hold about this many chars of state keys and
// transitions. When it is full, it is cleared, so that a pattern
// can not use an unbounded amount of memory.
const DFA_BUDGET = 1 << 18;
// A cache of the states that the simulation reaches, built as the
// matcher is used. Each char of a string is then one Map lookup,
// once the states that it leads to are known.
//
// The dot rules only restrict the first char of a dotfile (strings
// that are only `.` or `..` do not use the cache). So a dotfile
// starts at its own state, which takes its first step with the
// restriction, and every other state takes steps without it.
class Dfa {
#start;
#states = new Map();
#size = 0;
#plain;
#dotStart;
#sim;
#dotSim;
constructor(start, marks) {
this.#start = start;
this.#sim = new Sim(false, false, marks);
this.#dotSim = new Sim(false, true, marks);
}
#make(state) {
return {
state,
match: state.match,
dead: state.dead,
next: new Map(),
};
}
#intern(state) {
const key = stateKey(state);
const found = this.#states.get(key);
if (found)
return found;
if (this.#size > DFA_BUDGET)
this.#clear();
const d = this.#make(state);
this.#states.set(key, d);
this.#size += key.length + 1;
return d;
}
#clear() {
this.#states.clear();
this.#size = 0;
this.#plain = undefined;
this.#dotStart = undefined;
}
start(dotStart) {
if (dotStart) {
if (this.#dotStart)
return this.#dotStart;
const state = this.#dotSim.state();
this.#dotSim.add(state, this.#start, 0, true);
return (this.#dotStart = this.#make(this.#dotSim.done(state)));
}
if (this.#plain)
return this.#plain;
const state = this.#sim.state();
this.#sim.add(state, this.#start, 0, true);
return (this.#plain = this.#intern(this.#sim.done(state)));
}
// the next state, after a miss in `d.ascii`
next(d, c) {
const code = c.charCodeAt(0);
const found = code < 128 ? undefined : d.next.get(c);
if (found)
return found;
// the dotfile start is not in the cache, so it is never shared
const n = d === this.#dotStart ?
this.#intern(this.#dotSim.step(d.state, c, 0, true))
: this.#intern(this.#sim.step(d.state, c, 1, true));
if (code < 128) {
if (!d.ascii) {
d.ascii = new Array(128);
this.#size += 128;
}
d.ascii[code] = n;
}
else {
d.next.set(c, n);
}
this.#size++;
return n;
}
}
// the nodes in order, if the graph is a single chain
const linear = (start) => {
const nodes = [];
for (let n = start; n.t !== 'match'; n = n.next) {
if (n.t === 'split' || n.t === 'neg')
return undefined;
nodes.push(n);
}
return nodes;
};
// Match a chain of nodes. Each node other than `*` matches exactly
// one char, so on a failure it is enough to go back to the last `*`
// and let it match one more char. This takes at most
// nodes.length * chars.length steps.
const testLinear = (nodes, chars, start, end) => {
let ni = 0;
let ci = start;
let starNi = -1;
let starCi = 0;
while (ci < end) {
const n = nodes[ni];
if (n?.t === 'star') {
starNi = ni++;
starCi = ci;
continue;
}
const c = chars[ci];
if (n &&
(n.t === 'any' ||
(n.t === 'lit' && litMatch(n, c)) ||
(n.t === 'class' && n.re.test(c)))) {
ni++;
ci++;
continue;
}
if (starNi === -1)
return false;
ni = starNi + 1;
ci = ++starCi;
}
while (nodes[ni]?.t === 'star')
ni++;
return ni === nodes.length;
};
// The least and most chars that the items can match. These are only
// bounds: a negation can match a string of any length, so it counts
// as 0 to Infinity.
const lengths = (items) => {
let min = 0;
let max = 0;
for (const it of items) {
const [lo, hi] = itemLengths(it);
min += lo;
max += hi;
}
return [min, max];
};
const itemLengths = (it) => {
if (it.t === 'star')
return [0, Infinity];
if (it.t !== 'ext')
return [1, 1];
if (it.type === '!')
return [0, Infinity];
const alts = it.alts.map(lengths);
const min = Math.min(...alts.map(a => a[0]));
const max = Math.max(...alts.map(a => a[1]));
// a loop of alternatives that only match the empty string is empty
const loop = max === 0 ? 0 : Infinity;
return (it.type === '@' ? [min, max]
: it.type === '?' ? [0, max]
: it.type === '*' ? [0, loop]
: [min, loop]);
};
// true if the chars from `start` match the literals
const hasAffix = (lits, chars, start) => {
for (let j = 0; j < lits.length; j++) {
if (!litMatch(lits[j], chars[start + j]))
return false;
}
return true;
};
// a `/`, or half of a surrogate pair
const slashOrSurrogate = /[/\ud800-\udfff]/;
const surrogate = /[\ud800-\udfff]/;
// a string can be indexed by code point, unless it has surrogate
// pairs
const codePoints = (s) => surrogate.test(s) ? [...s] : s;
const noSlash = (s) => {
if (s.includes('/')) {
throw new Error('can only match a single path portion, got: ' + s);
}
};
class Matcher {
pattern;
options;
#start;
// the number of node ids
#size;
#marks;
// the Sim for strings that are only `.` or `..`
#dotsSim;
// the string to compare, if the pattern has no magic. With
// `nocase:true`, the RegExp that folds case is made when it is
// first used.
#literal;
#literalFold = false;
#literalRe;
// the nodes between the prefix and suffix, if the graph is a
// single chain
#linear;
// the linear nodes are only `*` and `?`, so the length bounds and
// the prefix and suffix decide the match
#wild = false;
// the least and most chars that a match can have
#min = 0;
#max = Infinity;
// the literals that a match must start and end with. Each one
// matches exactly one char, and they are distinct items in the
// pattern, so a string that does not have them can not match.
#prefix = [];
#suffix = [];
// the prefix and suffix as strings, if they do not fold case
#prefixStr;
#suffixStr;
// there is a prefix or suffix to check
#affix = false;
#dfa;
#form;
constructor(pattern, options = {}) {
if (pattern.includes('/')) {
throw new Error('can only match a single path portion, got pattern: ' + pattern);
}
this.pattern = pattern;
this.options = options;
const { nocase = false, noext = false, normalize: n } = options;
this.#form = n === true ? 'NFC' : n || undefined;
// a pattern that is only an empty extglob is a literal string,
// except for `!()`, which matches any non-empty string
const literal = /^[?*+@]\(\)$/.test(pattern);
const toks = tokenize(pattern, nocase, noext || literal, this.#form);
let [items] = build(toks, pair(toks), 0, toks.length, true);
if (this.#form)
items = normalize(items, this.#form);
const [start, size] = compile(items, nocase);
this.#start = start;
this.#size = size;
if (items.every(it => it.t === 'lit')) {
this.#literal = items.map(it => it.ch).join('');
this.#literalFold = nocase;
}
else {
const lit = (it) => it.t !== 'lit' ? undefined
: nocase ? { ch: it.ch, re: foldRe(it.ch) }
: { ch: it.ch };
for (const it of items) {
const l = lit(it);
if (!l)
break;
this.#prefix.push(l);
}
for (let j = items.length - 1; j >= 0; j--) {
const l = lit(items[j]);
if (!l)
break;
this.#suffix.unshift(l);
}
this.#affix = !!(this.#prefix.length || this.#suffix.length);
if (!nocase) {
this.#prefixStr = this.#prefix.map(l => l.ch).join('');
this.#suffixStr = this.#suffix.map(l => l.ch).join('');
}
this.#linear = linear(this.#start)?.slice(this.#prefix.length, -this.#suffix.length || undefined);
this.#wild = !!this.#linear?.every(n => n.t === 'star' || n.t === 'any');
const [min, max] = lengths(items);
this.#min = min;
this.#max = max;
}
}
test(s) {
// The `/` check uses the string as given, so with normalization it
// is a separate step. Otherwise, one scan finds both a `/` and the
// surrogate pairs that stop the string being indexed by code point.
if (this.#form) {
noSlash(s);
return this.#test(s.normalize(this.#form));
}
if (slashOrSurrogate.test(s)) {
noSlash(s);
return this.#test(s, [...s]);
}
return this.#test(s, s);
}
/**
* The same as {@link Matcher#test}, but the string is not checked
* for `/` chars, so the result for a string that has one is not
* defined. Only use it for a string that is known to be one path
* portion, such as a part of a path that was split on `/`. It can
* be faster, because some patterns do not need to look at each char
* of the string.
*/
testUnchecked(s) {
return this.#test(this.#form ? s.normalize(this.#form) : s);
}
// Test a string that has no `/`. `chars` indexes it by code point.
// If it is not given, it is only found if a step needs it.
#test(s, chars) {
if (this.#literal !== undefined) {
return this.#literalFold ?
(this.#literalRe ??= newFoldRe(this.#literal)).test(s)
: s === this.#literal;
}
// the length check means that the prefix and suffix do not
// overlap. Without the chars, the length in code points is from
// half of the UTF-16 length (if each one is a surrogate pair) to
// all of it, which is often enough to know.
const min = this.#min;
const max = this.#max;
if (chars === undefined) {
const most = s.length;
const least = (most + 1) >> 1;
if (most < min || least > max)
return false;
if (least < min || most > max)
chars = codePoints(s);
}
if (chars !== undefined &&
(chars.length < min || chars.length > max)) {
return false;
}
const prefix = this.#prefix.length;
if (this.#affix) {
if (this.#prefixStr !== undefined && this.#suffixStr !== undefined) {
if (!s.startsWith(this.#prefixStr) ||
!s.endsWith(this.#suffixStr)) {
return false;
}
}
else {
chars ??= codePoints(s);
const end = chars.length - this.#suffix.length;
if (!hasAffix(this.#prefix, chars, 0) ||
!hasAffix(this.#suffix, chars, end)) {
return false;
}
}
}
const dotStart = !this.options.dot && s.startsWith('.');
if (this.#linear) {
// `.` and `..` only match literal dots, even with `dot:true`
if (s === '.' || s === '..')
return false;
// only a literal can match the leading dot. A `*` can not
// start a dotfile, even if it matches nothing.
if (dotStart && !prefix)
return false;
if (this.#wild)
return true;
chars ??= codePoints(s);
const end = chars.length - this.#suffix.length;
return testLinear(this.#linear, chars, prefix, end);
}
chars ??= codePoints(s);
if (s === '.' || s === '..') {
this.#marks ??= marks(this.#size);
const sim = (this.#dotsSim ??= new Sim(true, false, this.#marks));
const start = sim.state();
sim.add(start, this.#start, 0, true);
let state = sim.done(start);
for (let i = 0; i < chars.length; i++) {
state = sim.step(state, chars[i], i, true);
}
return state.match;
}
this.#marks ??= marks(this.#size);
const dfa = (this.#dfa ??= new Dfa(this.#start, this.#marks));
let d = dfa.start(dotStart);
// read char codes from the string, so that a one-char string is
// only made for a cache miss
const str = chars === s;
for (let i = 0; i < chars.length; i++) {
if (d.dead)
return false;
const code = str ? s.charCodeAt(i) : chars[i].charCodeAt(0);
d = d.ascii?.[code] ?? dfa.next(d, chars[i]);
}
return d.match;
}
/** a readable listing of the state machine */
toString() {
return show(this.#start);
}
}
exports.Matcher = Matcher;
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,qDAAwD;AAyCxD,sDAAsD;AACtD,MAAM,KAAK,GAAS,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,EAAE,CAAA;AAEzC,MAAM,QAAQ,GAAG,OAAO,CAAA;AAExB,MAAM,GAAG,GAAG,CAAC,EAAU,EAAQ,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAA;AAEpD,MAAM,QAAQ,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,sBAAsB,EAAE,MAAM,CAAC,CAAA;AAEzE,4DAA4D;AAC5D,MAAM,SAAS,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,IAAI,MAAM,CAAC,IAAI,QAAQ,CAAC,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,CAAA;AAErE,oEAAoE;AACpE,qEAAqE;AACrE,SAAS;AACT,MAAM,SAAS,GAAG,IAAI,GAA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IACD,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,oEAAoE;AACpE,oEAAoE;AACpE,kEAAkE;AAClE,yDAAyD;AACzD,MAAM,SAAS,GAAG,CAAC,KAAa,EAAE,IAAU,EAAU,EAAE;IACtD,MAAM,GAAG,GAAW,EAAE,CAAA;IACtB,IAAI,GAAG,GAAG,EAAE,CAAA;IACZ,MAAM,KAAK,GAAG,GAAG,EAAELine truncated
@@ -0,0 +1,3 @@
"use strict";var D=(i,t)=>()=>{try{return t||i((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}};var E=D(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.parseClass=void 0;var G={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}"],"[:alpha:]":["\\p{L}\\p{Nl}"],"[:ascii:]":["\\x00-\\x7f"],"[:blank:]":["\\p{Zs}\\t"],"[:cntrl:]":["\\p{Cc}"],"[:digit:]":["\\p{Nd}"],"[:graph:]":["\\p{Z}\\p{C}",!0],"[:lower:]":["\\p{Ll}"],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}\\p{S}"],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f"],"[:upper:]":["\\p{Lu}"],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}"],"[:xdigit:]":["A-Fa-f0-9"]},x=i=>i.replace(/[[\]\\-]/g,"\\$&"),A=/$./,H=(i,t,e=!1,s)=>{let h=p=>{let m=s?p.normalize(s):p;return[...m].length===1?m:p},n=t;if(i.charAt(n)!=="[")throw new Error("not in a brace expression");let o=[],a=[],r=n+1,l=!1,c=!1,u=!1,g=n,d="";t:for(;r<i.length;){let p=String.fromCodePoint(i.codePointAt(r));if((p==="!"||p==="^")&&r===n+1){u=!0,r++;continue}if(p==="]"&&l&&!c){g=r+1;break}if(l=!0,p==="\\"&&!c){c=!0,r++;continue}if(p==="["&&!c){for(let[R,[v,B]]of Object.entries(G))if(i.startsWith(R,r)){if(d)return[A,i.length-n];r+=R.length,B?a.push(v):o.push(v);continue t}}c=!1;let m=h(p);if(d){m.codePointAt(0)>d.codePointAt(0)?o.push(x(d)+"-"+x(m)):m===d&&o.push(x(m)),d="",r+=p.length;continue}if(i.startsWith("-]",r+p.length)){o.push(x(m+"-")),r+=p.length+1;continue}if(i.startsWith("-",r+p.length)){d=m,r+=p.length+1;continue}o.push(x(m)),r+=p.length}if(g<r)return[A,0];if(!o.length&&!a.length)return[A,i.length-n];let f="["+(u?"^":"")+o.join("")+"]",w="["+(u?"":"^")+a.join("")+"]",Z="^"+(o.length&&a.length?"("+f+"|"+w+")":o.length?f:w);return[new RegExp(Z,e?"iu":"u"),g-n]};S.parseClass=H});Object.defineProperty(exports,"__esModule",{value:!0});exports.Matcher=void 0;var J=E(),b={t:"match",id:0},K="!?+*@",y=i=>({t:"lit",ch:i}),Q=i=>i.replace(/[\\^$.*+?()[\]{}|/]/g,"\\$&"),L=i=>new RegExp(`^${Q(i)}$`,"iu"),C=new Map,W=i=>{let t=C.get(i);return t||(t=L(i),C.size>=1e3&&C.clear(),C.set(i,t)),t},z=(i,t)=>{if(t===i.ch)return!0;if(!i.re)return!1;let e=t.charCodeAt(0);if(e>=128)return i.re.test(t);let s=i.ascii??=new Uint8Array(128);return s[e]||=i.re.test(t)?1:2,s[e]===1},V=(i,t,e,s)=>{let h=[];for(let n=0;n<i.length;){let o=String.fromCodePoint(i.codePointAt(n));if(o==="\\"){let a=i.codePointAt(n+1),r=a===void 0?o:String.fromCodePoint(a);h.push(y(r)),n+=1+r.length;continue}if(o==="["){let[a,r]=(0,J.parseClass)(i,n,t,s);if(r){h.push({t:"class",re:a}),n+=r;continue}}if(!e&&K.includes(o)&&i[n+1]==="("){h.push({t:"open",type:o}),n+=2;continue}h.push(!e&&o==="|"?{t:"bar"}:!e&&o===")"?{t:"close"}:o==="*"?{t:"star"}:o==="?"?{t:"any"}:y(o)),n+=o.length}return h},X=i=>{let t=new Map,e=[];return i.forEach((s,h)=>{s.t==="open"?e.push(h):s.t==="close"&&e.length&&t.set(e.pop(),h)}),t},O=(i,t,e,s,h)=>{let n=[],o=[n];for(let a=e;a<s;a++){let r=i[a],l=t.get(a);if(r.t==="open"&&l!==void 0){let c=O(i,t,a+1,l,!1);n.push({t:"ext",type:r.type,alts:c}),a=l}else r.t==="bar"&&!h?o.push(n=[]):r.t==="open"?n.push(y(r.type),y("(")):r.t==="bar"?n.push(y("|")):r.t==="close"?n.push(y(")")):n.push(r)}return o},I=(i,t)=>{let e=[],s="",h=()=>{for(let n of s.normalize(t))e.push(y(n));s=""};for(let n of i){if(n.t==="lit"){s+=n.ch;continue}h(),e.push(n.t==="ext"?{...n,alts:n.alts.map(o=>I(o,t))}:n)}return h(),e},Y=(i,t)=>{let e=1,s=a=>({t:"split",id:e++,out:a}),h=(a,r)=>a.reduceRight((l,c)=>n(c,l),r),n=(a,r)=>{switch(a.t){case"lit":let g=t?W(a.ch):void 0;return{t:"lit",id:e++,ch:a.ch,re:g,next:r};case"any":case"star":return{t:a.t,id:e++,next:r};case"class":return{t:"class",id:e++,re:a.re,next:r}}let l=g=>a.alts.map(d=>h(d,g));switch(a.type){case"@":return s(l(r));case"?":return s([r,...l(r)]);case"!":return{t:"neg",id:e++,sub:s(l(b)),next:r}}let c=s([]),u=s(l(c));return c.out.push(r,u),a.type==="*"?c:u};return[h(i,b),e]},tt=i=>{let t=[],e=new Set,s=n=>n.t==="match"?"match":String(n.id),h=(n,o)=>{if(n.t==="match"||e.has(n))return;e.add(n);let a=r=>t.push(`${o}${n.id}: ${r}`);switch(n.t){case"split":a(`split -> ${n.out.map(s).join(", ")}`);for(let r of n.out)h(r,o);return;case"neg":return a(`!(${s(n.sub)}) -> ${s(n.next)}`),h(n.sub,o+" "),h(n.next,o);case"lit":a(`${JSON.stringify(n.ch)} -> ${s(n.next)}`);break;case"class":a(`${n.re} -> ${s(n.next)}`);break;default:a(`${n.t==="any"?"?":"*"} -> ${s(n.next)}`)}h(n.next,o)};return h(i,""),[`start -> ${s(i)}`,...t].join(`
`)},j=class{gen;threads=[];match=!1;runs=[];ids=[];constructor(t){this.gen=t}get dead(){return!this.threads.length&&!this.match&&!this.runs.length}},T=(i,t)=>i.ids.length!==t.ids.length||i.runs.length!==t.runs.length||i.ids.some((e,s)=>e!==t.ids[s])?!1:i.runs.every(e=>t.runs.some(s=>s.neg===e.neg&&T(s.state,e.state))),N=i=>({has:new Float64Array(i),seen:new Float64Array(i),gen:0}),$=class{dots;dotStart;#t;constructor(t,e,s){this.dots=t,this.dotStart=e,this.#t=s}state(){return new j(++this.#t.gen)}done(t){return t.ids=t.threads.map(e=>e.id).sort((e,s)=>e-s),t.match&&t.ids.unshift(b.id),t}#s(t,e){let{seen:s}=this.#t;return s[e.id]===t.gen?!1:(s[e.id]=t.gen,!0)}#e(t,e){let{has:s}=this.#t;return s[e.id]===t.gen?!1:(s[e.id]=t.gen,t.threads.push(e),!0)}restricted(t,e){return e&&(this.dots||this.dotStart&&t===0)}add(t,e,s,h){switch(e.t){case"split":if(!this.#s(t,e))return;for(let o of e.out)this.add(t,o,s,h);return;case"neg":if(!this.#s(t,e))return;let n=this.state();return this.add(n,e.sub,s,!1),this.done(n),this.addRun(t,{t:"run",neg:e,state:n},s,h);case"star":if(this.restricted(s,h))return;this.#e(t,e)&&this.add(t,e.next,s,h);return;case"match":t.match=!0;return;default:this.#e(t,e)}}addRun(t,e,s,h){for(let n of t.runs)if(n.neg===e.neg&&T(n.state,e.state))return;t.runs.push(e),e.state.match||this.add(t,e.neg.next,s,h)}step(t,e,s,h){let n=this.state();for(let o of t.threads)switch(o.t){case"lit":z(o,e)&&this.add(n,o.next,s+1,h);break;case"any":this.restricted(s,h)||this.add(n,o.next,s+1,h);break;case"class":!this.restricted(s,h)&&o.re.test(e)&&this.add(n,o.next,s+1,h);break;case"star":this.restricted(s,h)||this.add(n,o,s+1,h)}if(!this.restricted(s,h))for(let o of t.runs){if(o.state.dead){this.addRun(n,o,s+1,h);continue}let a=this.step(o.state,e,s,!1);this.addRun(n,{t:"run",neg:o.neg,state:a},s+1,h)}return this.done(n)}},q=i=>{let t=i.ids.join();if(!i.runs.length)return t;let e=i.runs.map(s=>`${s.neg.id}(${q(s.state)})`);return`${t}|${e.sort().join("|")}`},et=1<<18,P=class{#t;#s=new Map;#e=0;#c;#n;#i;#h;constructor(t,e){this.#t=t,this.#i=new $(!1,!1,e),this.#h=new $(!1,!0,e)}#o(t){return{state:t,match:t.match,dead:t.dead,next:new Map}}#u(t){let e=q(t),s=this.#s.get(e);if(s)return s;this.#e>et&&this.#f();let h=this.#o(t);return this.#s.set(e,h),this.#e+=e.length+1,h}#f(){this.#s.clear(),this.#e=0,this.#c=void 0,this.#n=void 0}start(t){if(t){if(this.#n)return this.#n;let s=this.#h.state();return this.#h.add(s,this.#t,0,!0),this.#n=this.#o(this.#h.done(s))}if(this.#c)return this.#c;let e=this.#i.state();return this.#i.add(e,this.#t,0,!0),this.#c=this.#u(this.#i.done(e))}next(t,e){let s=e.charCodeAt(0),h=s<128?void 0:t.next.get(e);if(h)return h;let n=t===this.#n?this.#u(this.#h.step(t.state,e,0,!0)):this.#u(this.#i.step(t.state,e,1,!0));return s<128?(t.ascii||(t.ascii=new Array(128),this.#e+=128),t.ascii[s]=n):t.next.set(e,n),this.#e++,n}},st=i=>{let t=[];for(let e=i;e.t!=="match";e=e.next){if(e.t==="split"||e.t==="neg")return;t.push(e)}return t},nt=(i,t,e,s)=>{let h=0,n=e,o=-1,a=0;for(;n<s;){let r=i[h];if(r?.t==="star"){o=h++,a=n;continue}let l=t[n];if(r&&(r.t==="any"||r.t==="lit"&&z(r,l)||r.t==="class"&&r.re.test(l))){h++,n++;continue}if(o===-1)return!1;h=o+1,n=++a}for(;i[h]?.t==="star";)h++;return h===i.length},U=i=>{let t=0,e=0;for(let s of i){let[h,n]=it(s);t+=h,e+=n}return[t,e]},it=i=>{if(i.t==="star")return[0,1/0];if(i.t!=="ext")return[1,1];if(i.type==="!")return[0,1/0];let t=i.alts.map(U),e=Math.min(...t.map(n=>n[0])),s=Math.max(...t.map(n=>n[1])),h=s===0?0:1/0;return i.type==="@"?[e,s]:i.type==="?"?[0,s]:i.type==="*"?[0,h]:[e,h]},_=(i,t,e)=>{for(let s=0;s<i.length;s++)if(!z(i[s],t[e+s]))return!1;return!0},rt=/[/\ud800-\udfff]/,ht=/[\ud800-\udfff]/,k=i=>ht.test(i)?[...i]:i,F=i=>{if(i.includes("/"))throw new Error("can only match a single path portion, got: "+i)},M=class{pattern;options;#t;#s;#e;#c;#n;#i=!1;#h;#o;#u=!1;#f=0;#m=1/0;#l=[];#a=[];#p;#g;#w=!1;#y;#r;constructor(t,e={}){if(t.includes("/"))throw new Error("can only match a single path portion, got pattern: "+t);this.pattern=t,this.options=e;let{nocase:s=!1,noext:h=!1,normalize:n}=e;this.#r=n===!0?"NFC":n||void 0;let o=/^[?*+@]\(\)$/.test(t),a=V(t,s,h||o,this.#r),[r]=O(a,X(a),0,a.length,!0);this.#r&&(r=I(r,this.#r));let[l,c]=Y(r,s);if(this.#t=l,this.#s=c,r.every(u=>u.t==="lit"))this.#n=r.map(u=>u.ch).join(""),this.#i=s;else{let u=f=>f.t!=="lit"?void 0:s?{ch:f.ch,re:W(f.ch)}:{ch:f.ch};for(let f of r){let w=u(f);if(!w)break;this.#l.push(w)}for(let f=r.length-1;f>=0;f--){let w=u(r[f]);if(!w)break;this.#a.unshift(w)}this.#w=!!(this.#l.length||this.#a.length),s||(this.#p=this.#l.map(f=>f.ch).join(""),this.#g=this.#a.map(f=>f.ch).join("")),this.#o=st(this.#t)?.slice(this.#l.length,-this.#a.length||void 0),this.#u=!!this.#o?.every(f=>f.t==="star"||f.t==="any");let[g,d]=U(r);this.#f=g,this.#m=d}}test(t){return this.#r?(F(t),this.#d(t.normalize(this.#r))):rt.test(t)?(F(t),this.#d(t,[...t])):this.#d(t,t)}testUnchecked(t){return this.#d(this.#r?t.normalize(this. Line truncated
//# sourceMappingURL=index.min.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../src/parse-class.ts", "../../src/index.ts"],
"sourcesContent": ["// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { <posix class>: [<translation>, negated]\nconst posixClasses: { [k: string]: [e: string, n?: boolean] } = {\n '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}'],\n '[:alpha:]': ['\\\\p{L}\\\\p{Nl}'],\n '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f'],\n '[:blank:]': ['\\\\p{Zs}\\\\t'],\n '[:cntrl:]': ['\\\\p{Cc}'],\n '[:digit:]': ['\\\\p{Nd}'],\n '[:graph:]': ['\\\\p{Z}\\\\p{C}', true],\n '[:lower:]': ['\\\\p{Ll}'],\n '[:print:]': ['\\\\p{C}', true],\n '[:punct:]': ['\\\\p{P}\\\\p{S}'],\n '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f'],\n '[:upper:]': ['\\\\p{Lu}'],\n '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}'],\n '[:xdigit:]': ['A-Fa-f0-9'],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n\nexport type ParseClassResult = [re: RegExp, consumed: number]\n\nexport type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD'\n\nconst noMatch = /$./\n\n// Takes a glob string at a posix brace expression. Returns a RegExp\n// that tests one character, and the number of glob chars consumed.\n// If the class is not closed, consumed is 0, and the `[` must be\n// treated as a literal character.\n// Out of order ranges are removed. If nothing is left, the RegExp\n// is `/$./`, and the rest of the glob is consumed, so that the\n// whole glob cannot match.\nexport const parseClass = (\n glob: string,\n position: number,\n nocase: boolean = false,\n form?: Form,\n): ParseClassResult => {\n // normalize one class member, if it stays one code point\n const norm = (c: string) => {\n const n = form ? c.normalize(form) : c\n return [...n].length === 1 ? n : c\n }\n const pos = position\n /* c8 ignore start */\n if (glob.charAt(pos) !== '[') {\n throw new Error('not in a brace expression')\n }\n /* c8 ignore stop */\n const ranges: string[] = []\n const negs: string[] = []\n\n let i = pos + 1\n let sawStart = false\n let escaping = false\n let negate = false\n let endPos = pos\n let rangeStart = ''\n WHILE: while (i < glob.length) {\n const c = String.fromCodePoint(glob.codePointAt(i)!)\n if ((c === '!' || c === '^') && i === pos + 1) {\n negate = true\n i++\n continue\n }\n\n if (c === ']' && sawStart && !escaping) {\n endPos = i + 1\n break\n }\n\n sawStart = true\n if (c === '\\\\') {\n if (!escaping) {\n escaping = true\n i++\n continue\n }\n // escaped \\ char, fall through and treat like normal char\n }\n if (c === '[' && !escaping) {\n // either a posix class, a collation equivalent, or just a [\n for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n // invalid, [a-[] is fine, but not [a-[:alpha]]\n if (rangeStart) {\n return [noMatch, glob.length - pos]\n }\n i += cls.length\n if (neg) negs.push(unip)\n else ranges.push(unip)\n continue WHILE\n }\n }\n }\n\n // now it's just a normal character, effectively\n escaping = false\n const n = norm(c)\n if (rangeStart) {\n // throw this range away if it's not valid, but others\n // can still match.\n if (n.codePointAt(0)! > rangeStart.codePointAt(0)!) {\n ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n))\n } else if (n === rangeStart) {\n ranges.push(braceEscape(n))\n }\n rangeStart = ''\n i += c.length\n continue\n }\n\n // now might be the start of a range.\n // can be either c-d or c-] or c<more...>] or c] at this point\n if (glob.startsWith('-]', i + c.length)) {\n ranges.push(braceEscape(n + '-'))\n i += c.length + 1\n continue\n }\n if (glob.startsWith('-', i + c.length)) {\n rangeStart = n\n i += c.length + 1\n continue\n }\n\n // not the start of a range, just a single character\n ranges.push(braceEscape(n))\n i += c.length\n }\n\n if (endPos < i) {\n // didn't see the end of the class, not a valid class,\n // but might still be valid as a literal match.\n return [noMatch, 0]\n }\n\n // if we got no ranges and no negates, then we have a range that\n // cannot possibly match anything, and that poisons the whole glob\n if (!ranges.length && !negs.length) {\n return [noMatch, glob.length - pos]\n }\n\n const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']'\n const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']'\n const comb =\n '^' +\n (ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'\n : ranges.length ? sranges\n : snegs)\n\n return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos]\n}\n", "import { type Form, parseClass } from './parse-class.js'\nLine truncated
"mappings": "0MAIA,IAAMA,EAA0D,CAC9D,YAAa,CAAC,sBAAsB,EACpC,YAAa,CAAC,eAAe,EAC7B,YAAa,CAAC,aAAuB,EACrC,YAAa,CAAC,YAAY,EAC1B,YAAa,CAAC,SAAS,EACvB,YAAa,CAAC,SAAS,EACvB,YAAa,CAAC,eAAgB,EAAI,EAClC,YAAa,CAAC,SAAS,EACvB,YAAa,CAAC,SAAU,EAAI,EAC5B,YAAa,CAAC,cAAc,EAC5B,YAAa,CAAC,uBAAuB,EACrC,YAAa,CAAC,SAAS,EACvB,WAAY,CAAC,6BAA6B,EAC1C,aAAc,CAAC,WAAW,GAKtBC,EAAeC,GAAcA,EAAE,QAAQ,YAAa,MAAM,EAM1DC,EAAU,KASHC,EAAa,CACxBC,EACAC,EACAC,EAAkB,GAClBC,IACoB,CAEpB,IAAMC,EAAQC,GAAa,CACzB,IAAMC,EAAIH,EAAOE,EAAE,UAAUF,CAAI,EAAIE,EACrC,MAAO,CAAC,GAAGC,CAAC,EAAE,SAAW,EAAIA,EAAID,CACnC,EACME,EAAMN,EAEZ,GAAID,EAAK,OAAOO,CAAG,IAAM,IACvB,MAAM,IAAI,MAAM,2BAA2B,EAG7C,IAAMC,EAAmB,CAAA,EACnBC,EAAiB,CAAA,EAEnBC,EAAIH,EAAM,EACVI,EAAW,GACXC,EAAW,GACXC,EAAS,GACTC,EAASP,EACTQ,EAAa,GACjBC,EAAO,KAAON,EAAIV,EAAK,QAAQ,CAC7B,IAAMK,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", "position", "nocase", "form", "norm", "c", "n", "pos", "ranges", "negs", "i", "sawStart", "escaping", "negate", "endPos", "rangeStart", "WHILE", "cls", "unip", "neg", "sranges", "snegs", "comb", "exports", "parse_class_js_1", "MATCH", "extTypes", "lit", "ch", "reEscape", "s", "newFoldRe", "foldCache", "foldRe", "re", "litMatch", "l", "c", "code", "ascii", "tokenize", "p", "nocase", "noext", "form", "toks", "i", "e", "consumed", "pair", "pairs", "stack", "tok", "build", "start", "end", "top", "seq", "alts", "close", "sub", "normalize", "items", "out", "run", "flush", "it", "a", "compile", "id", "split", "next", "item", "after", "entry", "show", "lines", "seen", "ref", "walk", "indent", "line", "desc", "o", "State", "gen", "sameState", "b", "r", "marks", "size", "Sim", "#marks", "dots", "dotStart", "state", "n", "#visit", "node", "#addThread", "has", "th", "stateKey", "ids", "runs", "DFA_BUDGET", "Dfa", "#start", "#states", "#size", "#plain", "#dotStart", "#sim", "#dotSim", "#make", "#intern", "key", "found", "#clear", "d", "linear", "nodes", "testLinear", "chars", "ni", "ci", "starNi", "starCi", "lengths", "min", "max", "lo", "hi", "itemLengths", "loop", "hasAffix", "lits", "j", "slashOrSurrogate", "surrogate", "codePoints", "noSlash", "Matcher", "#dotsSim", "#literal", "#literalFold", "#literalRe", "#linear", "#wild", "#min", "#max", "#prefix", "#suffix", "#prefixStr", "#suffixStr", "#affix", "#dfa", "#form", "pattern", "options", "literal", "#test", "most", "least", "prefix", "sim", "dfa", "str"]
}
@@ -0,0 +1,3 @@
{
"type": "commonjs"
}
@@ -0,0 +1,4 @@
export type ParseClassResult = [re: RegExp, consumed: number];
export type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD';
export declare const parseClass: (glob: string, position: number, nocase?: boolean, form?: Form) => ParseClassResult;
//# sourceMappingURL=parse-class.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"parse-class.d.ts","sourceRoot":"","sources":["../../src/parse-class.ts"],"names":[],"mappings":"AAyBA,MAAM,MAAM,gBAAgB,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;AAE7D,MAAM,MAAM,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,CAAA;AAWlD,eAAO,MAAM,UAAU,GACrB,MAAM,MAAM,EACZ,UAAU,MAAM,EAChB,SAAQ,OAAe,EACvB,OAAO,IAAI,KACV,gBAkHF,CAAA"}
@@ -0,0 +1,142 @@
"use strict";
// translate the various posix character classes into unicode properties
// this works across all unicode locales
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseClass = void 0;
// { <posix class>: [<translation>, negated]
const posixClasses = {
'[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}'],
'[:alpha:]': ['\\p{L}\\p{Nl}'],
'[:ascii:]': ['\\x' + '00-\\x' + '7f'],
'[:blank:]': ['\\p{Zs}\\t'],
'[:cntrl:]': ['\\p{Cc}'],
'[:digit:]': ['\\p{Nd}'],
'[:graph:]': ['\\p{Z}\\p{C}', true],
'[:lower:]': ['\\p{Ll}'],
'[:print:]': ['\\p{C}', true],
'[:punct:]': ['\\p{P}\\p{S}'],
'[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f'],
'[:upper:]': ['\\p{Lu}'],
'[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}'],
'[:xdigit:]': ['A-Fa-f0-9'],
};
// only need to escape a few things inside of brace expressions
// escapes: [ \ ] -
const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
const noMatch = /$./;
// Takes a glob string at a posix brace expression. Returns a RegExp
// that tests one character, and the number of glob chars consumed.
// If the class is not closed, consumed is 0, and the `[` must be
// treated as a literal character.
// Out of order ranges are removed. If nothing is left, the RegExp
// is `/$./`, and the rest of the glob is consumed, so that the
// whole glob cannot match.
const parseClass = (glob, position, nocase = false, form) => {
// normalize one class member, if it stays one code point
const norm = (c) => {
const n = form ? c.normalize(form) : c;
return [...n].length === 1 ? n : c;
};
const pos = position;
/* c8 ignore start */
if (glob.charAt(pos) !== '[') {
throw new Error('not in a brace expression');
}
/* c8 ignore stop */
const ranges = [];
const negs = [];
let i = pos + 1;
let sawStart = false;
let escaping = false;
let negate = false;
let endPos = pos;
let rangeStart = '';
WHILE: while (i < glob.length) {
const c = String.fromCodePoint(glob.codePointAt(i));
if ((c === '!' || c === '^') && i === pos + 1) {
negate = true;
i++;
continue;
}
if (c === ']' && sawStart && !escaping) {
endPos = i + 1;
break;
}
sawStart = true;
if (c === '\\') {
if (!escaping) {
escaping = true;
i++;
continue;
}
// escaped \ char, fall through and treat like normal char
}
if (c === '[' && !escaping) {
// either a posix class, a collation equivalent, or just a [
for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {
if (glob.startsWith(cls, i)) {
// invalid, [a-[] is fine, but not [a-[:alpha]]
if (rangeStart) {
return [noMatch, glob.length - pos];
}
i += cls.length;
if (neg)
negs.push(unip);
else
ranges.push(unip);
continue WHILE;
}
}
}
// now it's just a normal character, effectively
escaping = false;
const n = norm(c);
if (rangeStart) {
// throw this range away if it's not valid, but others
// can still match.
if (n.codePointAt(0) > rangeStart.codePointAt(0)) {
ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n));
}
else if (n === rangeStart) {
ranges.push(braceEscape(n));
}
rangeStart = '';
i += c.length;
continue;
}
// now might be the start of a range.
// can be either c-d or c-] or c<more...>] or c] at this point
if (glob.startsWith('-]', i + c.length)) {
ranges.push(braceEscape(n + '-'));
i += c.length + 1;
continue;
}
if (glob.startsWith('-', i + c.length)) {
rangeStart = n;
i += c.length + 1;
continue;
}
// not the start of a range, just a single character
ranges.push(braceEscape(n));
i += c.length;
}
if (endPos < i) {
// didn't see the end of the class, not a valid class,
// but might still be valid as a literal match.
return [noMatch, 0];
}
// if we got no ranges and no negates, then we have a range that
// cannot possibly match anything, and that poisons the whole glob
if (!ranges.length && !negs.length) {
return [noMatch, glob.length - pos];
}
const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']';
const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']';
const comb = '^' +
(ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
: ranges.length ? sranges
: snegs);
return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos];
};
exports.parseClass = parseClass;
//# sourceMappingURL=parse-class.js.map
@@ -0,0 +1 @@
{"version":3,"file":"parse-class.js","sourceRoot":"","sources":["../../src/parse-class.ts"],"names":[],"mappings":";AAAA,wEAAwE;AACxE,wCAAwC;;;AAExC,4CAA4C;AAC5C,MAAM,YAAY,GAA8C;IAC9D,WAAW,EAAE,CAAC,sBAAsB,CAAC;IACrC,WAAW,EAAE,CAAC,eAAe,CAAC;IAC9B,WAAW,EAAE,CAAC,KAAK,GAAG,QAAQ,GAAG,IAAI,CAAC;IACtC,WAAW,EAAE,CAAC,YAAY,CAAC;IAC3B,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,WAAW,EAAE,CAAC,cAAc,EAAE,IAAI,CAAC;IACnC,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,WAAW,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC;IAC7B,WAAW,EAAE,CAAC,cAAc,CAAC;IAC7B,WAAW,EAAE,CAAC,uBAAuB,CAAC;IACtC,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,UAAU,EAAE,CAAC,6BAA6B,CAAC;IAC3C,YAAY,EAAE,CAAC,WAAW,CAAC;CAC5B,CAAA;AAED,+DAA+D;AAC/D,mBAAmB;AACnB,MAAM,WAAW,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,MAAM,CAAC,CAAA;AAMjE,MAAM,OAAO,GAAG,IAAI,CAAA;AAEpB,oEAAoE;AACpE,mEAAmE;AACnE,iEAAiE;AACjE,kCAAkC;AAClC,kEAAkE;AAClE,+DAA+D;AAC/D,2BAA2B;AACpB,MAAM,UAAU,GAAG,CACxB,IAAY,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CAAC,MAAM,GAAG,GAAG,CAAC,CAAA;IACrC,CAAC;IAED,MAAM,OAAO,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,GAAG,CAAA;IACjE,MAAM,KAAK,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,GAAG,CAAA;IAC7D,MAAM,IAAI,GACR,GAAG;QACH,CAAC,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,GAAG,KAAK,GAAG,GAAG;YACjE,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO;gBACzB,CAAC,CAAC,KAAK,CAAC,CAAA;IAEV,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC,CAAA;AAC9D,CAAC,CAAA;AAvHY,QAAA,UAAU,cAuHtB","sourcesContent":["// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { <posix class>: [<translation>, negated]\nconst posixClasses: { [k: string]: [e: string, n?: boolLine truncated
@@ -0,0 +1,114 @@
import { type Form } from './parse-class.js';
export type { Form };
export type MatcherOptions = {
/** perform a case-insensitive match */
nocase?: boolean;
/** do not treat strings starting with `.` specially */
dot?: boolean;
/** do not match extglobs (treat them as normal strings) */
noext?: boolean;
/**
* normalize unicode in the pattern and the tested strings, with
* this form. `true` means `'NFC'`.
*/
normalize?: boolean | Form;
};
export type Item = {
t: 'lit';
ch: string;
} | {
t: 'any' | 'star';
} | {
t: 'class';
re: RegExp;
} | {
t: 'ext';
type: string;
alts: Item[][];
};
export type Token = Item | {
t: 'open';
type: string;
} | {
t: 'bar';
} | {
t: 'close';
};
export type NegNode = {
t: 'neg';
id: number;
sub: Node;
next: Node;
};
export type SplitNode = {
t: 'split';
id: number;
out: Node[];
};
export type Node = ({
t: 'lit';
id: number;
next: Node;
} & Lit) | {
t: 'any' | 'star';
id: number;
next: Node;
} | {
t: 'class';
id: number;
re: RegExp;
next: Node;
} | SplitNode | NegNode | {
t: 'match';
id: number;
};
/**
* A literal char. With `nocase:true`, `re` folds case, and `ascii`
* holds its results for ASCII chars, by char code: 1 for a match,
* and 2 for not.
*/
export type Lit = {
ch: string;
re?: RegExp;
ascii?: Uint8Array;
};
/**
* For each node id, the gen of the last state that has the node as
* a thread, and of the last state that walked through it. A state is
* built to the end before the states around it go on, and the nodes
* of a negated sub-pattern are only in its states (other than the
* match node, which is never marked). So one mark for each node is
* enough to know if the state being built has it. The Sims of a
* matcher never run at the same time, so they share one Marks.
*/
export type Marks = {
has: Float64Array;
seen: Float64Array;
gen: number;
};
/**
* A node in a graph with no splits or negations. Such a graph is a
* chain of nodes that each match one char, or a `*`.
*/
export type LinearNode = Exclude<Node, SplitNode | NegNode | {
t: 'match';
}>;
export declare class Matcher {
#private;
pattern: string;
options: MatcherOptions;
constructor(pattern: string, options?: MatcherOptions);
test(s: string): boolean;
/**
* The same as {@link Matcher#test}, but the string is not checked
* for `/` chars, so the result for a string that has one is not
* defined. Only use it for a string that is known to be one path
* portion, such as a part of a path that was split on `/`. It can
* be faster, because some patterns do not need to look at each char
* of the string.
*/
testUnchecked(s: string): boolean;
/** a readable listing of the state machine */
toString(): string;
}
//# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,IAAI,EAAc,MAAM,kBAAkB,CAAA;AAExD,YAAY,EAAE,IAAI,EAAE,CAAA;AAEpB,MAAM,MAAM,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C,GAC5C;IAAE,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,IAAI,CAAA;CAAE,GAC7C;IAAE,CAAC,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,IAAI,CAAA;CAAE,GAClD,SAAS,GACT,OAAO,GACP;IAAE,CAAC,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAA;AA4B9B;;;;GAIG;AACH,MAAM,MAAM,GAAG,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,UAAU,CAAA;CAAE,CAAA;AAgPjE;;;;;;;;GAQG;AACH,MAAM,MAAM,KAAK,GAAG;IAAE,GAAG,EAAE,YAAY,CAAC;IAAC,IAAI,EAAE,YAAY,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAAA;AA8P1E;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,OAAO,CAC9B,IAAI,EACJ,SAAS,GAAG,OAAO,GAAG;IAAE,CAAC,EAAE,OAAO,CAAA;CAAE,CACrC,CAAA;AA8GD,qBAAa,OAAO;;IAClB,OAAO,EAAE,MAAM,CAAA;IACf,OAAO,EAAE,cAAc,CAAA;gBAmCX,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB;IAuDzD,IAAI,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO;IAexB;;;;;;;OAOG;IACH,aAAa,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO;IAwFjC,8CAA8C;IAC9C,QAAQ,IAAI,MAAM;CAGnB"}
@@ -0,0 +1,758 @@
import { parseClass } from './parse-class.js';
// the end of the pattern, or of a negated sub-pattern
const MATCH = { t: 'match', id: 0 };
const extTypes = '!?+*@';
const lit = (ch) => ({ t: 'lit', ch });
const reEscape = (s) => s.replace(/[\\^$.*+?()[\]{}|/]/g, '\\$&');
// a RegExp that only matches `s`, with unicode case folding
const newFoldRe = (s) => new RegExp(`^${reEscape(s)}$`, 'iu');
// foldRe for one literal char. The same chars are in most patterns,
// so keep them. A RegExp without the `g` or `y` flag has no state to
// share.
const foldCache = new Map();
const foldRe = (ch) => {
let re = foldCache.get(ch);
if (!re) {
re = newFoldRe(ch);
if (foldCache.size >= 1000)
foldCache.clear();
foldCache.set(ch, re);
}
return re;
};
const litMatch = (l, c) => {
if (c === l.ch)
return true;
if (!l.re)
return false;
const code = c.charCodeAt(0);
if (code >= 128)
return l.re.test(c);
const ascii = (l.ascii ??= new Uint8Array(128));
ascii[code] ||= l.re.test(c) ? 1 : 2;
return ascii[code] === 1;
};
const tokenize = (p, nocase, noext, form) => {
const toks = [];
for (let i = 0; i < p.length;) {
const c = String.fromCodePoint(p.codePointAt(i));
if (c === '\\') {
// a trailing \ is a literal \
const e = p.codePointAt(i + 1);
const ch = e === undefined ? c : String.fromCodePoint(e);
toks.push(lit(ch));
i += 1 + ch.length;
continue;
}
if (c === '[') {
const [re, consumed] = parseClass(p, i, nocase, form);
if (consumed) {
toks.push({ t: 'class', re });
i += consumed;
continue;
}
}
if (!noext && extTypes.includes(c) && p[i + 1] === '(') {
toks.push({ t: 'open', type: c });
i += 2;
continue;
}
toks.push(!noext && c === '|' ? { t: 'bar' }
: !noext && c === ')' ? { t: 'close' }
: c === '*' ? { t: 'star' }
: c === '?' ? { t: 'any' }
: lit(c));
i += c.length;
}
return toks;
};
// map each open token index to the index of its close token
const pair = (toks) => {
const pairs = new Map();
const stack = [];
toks.forEach((tok, i) => {
if (tok.t === 'open')
stack.push(i);
else if (tok.t === 'close' && stack.length)
pairs.set(stack.pop(), i);
});
return pairs;
};
// build the alternatives between start and end. An open token that
// is not closed is never inside a closed extglob, so bar and close
// tokens are only literal at the top level.
const build = (toks, pairs, start, end, top) => {
let seq = [];
const alts = [seq];
for (let i = start; i < end; i++) {
const tok = toks[i];
const close = pairs.get(i);
if (tok.t === 'open' && close !== undefined) {
const sub = build(toks, pairs, i + 1, close, false);
seq.push({ t: 'ext', type: tok.type, alts: sub });
i = close;
}
else if (tok.t === 'bar' && !top) {
alts.push((seq = []));
}
else if (tok.t === 'open') {
seq.push(lit(tok.type), lit('('));
}
else if (tok.t === 'bar') {
seq.push(lit('|'));
}
else if (tok.t === 'close') {
seq.push(lit(')'));
}
else {
seq.push(tok);
}
}
return alts;
};
// normalize each run of literal chars as one string, so that a char
// and the combining marks after it compose (or decompose) together.
// Syntax is already parsed, so a char that normalizes to a syntax
// char (such as full-width `*` in NFKC) stays a literal.
const normalize = (items, form) => {
const out = [];
let run = '';
const flush = () => {
for (const ch of run.normalize(form))
out.push(lit(ch));
run = '';
};
for (const it of items) {
if (it.t === 'lit') {
run += it.ch;
continue;
}
flush();
out.push(it.t === 'ext' ?
{ ...it, alts: it.alts.map(a => normalize(a, form)) }
: it);
}
flush();
return out;
};
// the start node, and the number of node ids. Ids are dense, from 0
// for the match node.
const compile = (items, nocase) => {
let id = 1;
const split = (out) => ({ t: 'split', id: id++, out });
const seq = (items, next) => items.reduceRight((next, it) => item(it, next), next);
const item = (it, next) => {
switch (it.t) {
case 'lit':
const re = nocase ? foldRe(it.ch) : undefined;
return { t: 'lit', id: id++, ch: it.ch, re, next };
case 'any':
case 'star':
return { t: it.t, id: id++, next };
case 'class':
return { t: 'class', id: id++, re: it.re, next };
}
const alts = (next) => it.alts.map(a => seq(a, next));
switch (it.type) {
case '@':
return split(alts(next));
case '?':
return split([next, ...alts(next)]);
case '!':
return { t: 'neg', id: id++, sub: split(alts(MATCH)), next };
}
// * and +, loop back after each match
const after = split([]);
const entry = split(alts(after));
after.out.push(next, entry);
return it.type === '*' ? after : entry;
};
const start = seq(items, MATCH);
return [start, id];
};
// one line per node, in the order that a walk from the start
// reaches them. Edges point to node ids. The nodes of a negated
// sub-pattern are indented under their negation.
const show = (start) => {
const lines = [];
const seen = new Set();
const ref = (n) => (n.t === 'match' ? 'match' : String(n.id));
const walk = (n, indent) => {
if (n.t === 'match' || seen.has(n))
return;
seen.add(n);
const line = (desc) => lines.push(`${indent}${n.id}: ${desc}`);
switch (n.t) {
case 'split':
line(`split -> ${n.out.map(ref).join(', ')}`);
for (const o of n.out)
walk(o, indent);
return;
case 'neg':
line(`!(${ref(n.sub)}) -> ${ref(n.next)}`);
walk(n.sub, indent + ' ');
return walk(n.next, indent);
case 'lit':
line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`);
break;
case 'class':
line(`${n.re} -> ${ref(n.next)}`);
break;
default:
line(`${n.t === 'any' ? '?' : '*'} -> ${ref(n.next)}`);
}
walk(n.next, indent);
};
walk(start, '');
return [`start -> ${ref(start)}`, ...lines].join('\n');
};
// The threads at one position in the string. Each node thread is
// only kept once, and runs with the same state are only kept once,
// so that identical threads merge. The match node is not in
// `threads`, because it can not step. It sets `match` instead.
class State {
// set by the Sim, to mark the nodes that this state has
gen;
threads = [];
match = false;
runs = [];
// the sorted ids of the threads, with 0 for a match, once the
// state is done
ids = [];
constructor(gen) {
this.gen = gen;
}
// no threads, so nothing more can match
get dead() {
return !this.threads.length && !this.match && !this.runs.length;
}
}
// true if the two states hold the same threads
const sameState = (a, b) => {
if (a.ids.length !== b.ids.length)
return false;
if (a.runs.length !== b.runs.length)
return false;
if (a.ids.some((id, i) => id !== b.ids[i]))
return false;
return a.runs.every(r => b.runs.some(o => o.neg === r.neg && sameState(o.state, r.state)));
};
const marks = (size) => ({
has: new Float64Array(size),
seen: new Float64Array(size),
gen: 0,
});
class Sim {
// `.` and `..` only match literal dots, even with `dot:true`
dots;
// the string starts with `.`, and `dot:true` is not set
dotStart;
#marks;
constructor(dots, dotStart, marks) {
this.dots = dots;
this.dotStart = dotStart;
this.#marks = marks;
}
state() {
return new State(++this.#marks.gen);
}
// sort the ids of a state, once it has all of its threads
done(state) {
state.ids = state.threads.map(n => n.id).sort((a, b) => a - b);
if (state.match)
state.ids.unshift(MATCH.id);
return state;
}
// true the first time that the state walks through the node, so
// that loops in the graph stop
#visit(state, node) {
const { seen } = this.#marks;
if (seen[node.id] === state.gen)
return false;
seen[node.id] = state.gen;
return true;
}
#addThread(state, node) {
const { has } = this.#marks;
if (has[node.id] === state.gen)
return false;
has[node.id] = state.gen;
state.threads.push(node);
return true;
}
// wildcards only match a leading dot if `dot:true`. In a negated
// sub-pattern, this does not apply, because the negation itself
// can not match a leading dot.
restricted(i, top) {
return top && (this.dots || (this.dotStart && i === 0));
}
add(state, node, i, top) {
switch (node.t) {
case 'split':
if (!this.#visit(state, node))
return;
for (const o of node.out)
this.add(state, o, i, top);
return;
case 'neg':
if (!this.#visit(state, node))
return;
const sub = this.state();
this.add(sub, node.sub, i, false);
this.done(sub);
return this.addRun(state, { t: 'run', neg: node, state: sub }, i, top);
case 'star':
// a * can not start a dotfile, even if it matches nothing
if (this.restricted(i, top))
return;
if (this.#addThread(state, node))
this.add(state, node.next, i, top);
return;
case 'match':
state.match = true;
return;
default:
this.#addThread(state, node);
}
}
addRun(state, run, i, top) {
for (const r of state.runs) {
if (r.neg === run.neg && sameState(r.state, run.state))
return;
}
state.runs.push(run);
if (!run.state.match) {
this.add(state, run.neg.next, i, top);
}
}
// the threads after char `c`, at index `i`
step(state, c, i, top) {
const next = this.state();
for (const th of state.threads) {
switch (th.t) {
case 'lit':
if (litMatch(th, c)) {
this.add(next, th.next, i + 1, top);
}
break;
case 'any':
if (!this.restricted(i, top))
this.add(next, th.next, i + 1, top);
break;
case 'class':
if (!this.restricted(i, top) && th.re.test(c)) {
this.add(next, th.next, i + 1, top);
}
break;
case 'star':
if (!this.restricted(i, top))
this.add(next, th, i + 1, top);
}
}
if (!this.restricted(i, top)) {
for (const run of state.runs) {
// a sub-pattern with no threads can not match again, so the
// run stays the same
if (run.state.dead) {
this.addRun(next, run, i + 1, top);
continue;
}
const sub = this.step(run.state, c, i, false);
this.addRun(next, { t: 'run', neg: run.neg, state: sub }, i + 1, top);
}
}
return this.done(next);
}
}
// A canonical key for the threads in a state. States with the same
// key hold the same threads, so they match the same strings.
const stateKey = (state) => {
const ids = state.ids.join();
if (!state.runs.length)
return ids;
const runs = state.runs.map(r => `${r.neg.id}(${stateKey(r.state)})`);
return `${ids}|${runs.sort().join('|')}`;
};
// The cache can hold about this many chars of state keys and
// transitions. When it is full, it is cleared, so that a pattern
// can not use an unbounded amount of memory.
const DFA_BUDGET = 1 << 18;
// A cache of the states that the simulation reaches, built as the
// matcher is used. Each char of a string is then one Map lookup,
// once the states that it leads to are known.
//
// The dot rules only restrict the first char of a dotfile (strings
// that are only `.` or `..` do not use the cache). So a dotfile
// starts at its own state, which takes its first step with the
// restriction, and every other state takes steps without it.
class Dfa {
#start;
#states = new Map();
#size = 0;
#plain;
#dotStart;
#sim;
#dotSim;
constructor(start, marks) {
this.#start = start;
this.#sim = new Sim(false, false, marks);
this.#dotSim = new Sim(false, true, marks);
}
#make(state) {
return {
state,
match: state.match,
dead: state.dead,
next: new Map(),
};
}
#intern(state) {
const key = stateKey(state);
const found = this.#states.get(key);
if (found)
return found;
if (this.#size > DFA_BUDGET)
this.#clear();
const d = this.#make(state);
this.#states.set(key, d);
this.#size += key.length + 1;
return d;
}
#clear() {
this.#states.clear();
this.#size = 0;
this.#plain = undefined;
this.#dotStart = undefined;
}
start(dotStart) {
if (dotStart) {
if (this.#dotStart)
return this.#dotStart;
const state = this.#dotSim.state();
this.#dotSim.add(state, this.#start, 0, true);
return (this.#dotStart = this.#make(this.#dotSim.done(state)));
}
if (this.#plain)
return this.#plain;
const state = this.#sim.state();
this.#sim.add(state, this.#start, 0, true);
return (this.#plain = this.#intern(this.#sim.done(state)));
}
// the next state, after a miss in `d.ascii`
next(d, c) {
const code = c.charCodeAt(0);
const found = code < 128 ? undefined : d.next.get(c);
if (found)
return found;
// the dotfile start is not in the cache, so it is never shared
const n = d === this.#dotStart ?
this.#intern(this.#dotSim.step(d.state, c, 0, true))
: this.#intern(this.#sim.step(d.state, c, 1, true));
if (code < 128) {
if (!d.ascii) {
d.ascii = new Array(128);
this.#size += 128;
}
d.ascii[code] = n;
}
else {
d.next.set(c, n);
}
this.#size++;
return n;
}
}
// the nodes in order, if the graph is a single chain
const linear = (start) => {
const nodes = [];
for (let n = start; n.t !== 'match'; n = n.next) {
if (n.t === 'split' || n.t === 'neg')
return undefined;
nodes.push(n);
}
return nodes;
};
// Match a chain of nodes. Each node other than `*` matches exactly
// one char, so on a failure it is enough to go back to the last `*`
// and let it match one more char. This takes at most
// nodes.length * chars.length steps.
const testLinear = (nodes, chars, start, end) => {
let ni = 0;
let ci = start;
let starNi = -1;
let starCi = 0;
while (ci < end) {
const n = nodes[ni];
if (n?.t === 'star') {
starNi = ni++;
starCi = ci;
continue;
}
const c = chars[ci];
if (n &&
(n.t === 'any' ||
(n.t === 'lit' && litMatch(n, c)) ||
(n.t === 'class' && n.re.test(c)))) {
ni++;
ci++;
continue;
}
if (starNi === -1)
return false;
ni = starNi + 1;
ci = ++starCi;
}
while (nodes[ni]?.t === 'star')
ni++;
return ni === nodes.length;
};
// The least and most chars that the items can match. These are only
// bounds: a negation can match a string of any length, so it counts
// as 0 to Infinity.
const lengths = (items) => {
let min = 0;
let max = 0;
for (const it of items) {
const [lo, hi] = itemLengths(it);
min += lo;
max += hi;
}
return [min, max];
};
const itemLengths = (it) => {
if (it.t === 'star')
return [0, Infinity];
if (it.t !== 'ext')
return [1, 1];
if (it.type === '!')
return [0, Infinity];
const alts = it.alts.map(lengths);
const min = Math.min(...alts.map(a => a[0]));
const max = Math.max(...alts.map(a => a[1]));
// a loop of alternatives that only match the empty string is empty
const loop = max === 0 ? 0 : Infinity;
return (it.type === '@' ? [min, max]
: it.type === '?' ? [0, max]
: it.type === '*' ? [0, loop]
: [min, loop]);
};
// true if the chars from `start` match the literals
const hasAffix = (lits, chars, start) => {
for (let j = 0; j < lits.length; j++) {
if (!litMatch(lits[j], chars[start + j]))
return false;
}
return true;
};
// a `/`, or half of a surrogate pair
const slashOrSurrogate = /[/\ud800-\udfff]/;
const surrogate = /[\ud800-\udfff]/;
// a string can be indexed by code point, unless it has surrogate
// pairs
const codePoints = (s) => surrogate.test(s) ? [...s] : s;
const noSlash = (s) => {
if (s.includes('/')) {
throw new Error('can only match a single path portion, got: ' + s);
}
};
export class Matcher {
pattern;
options;
#start;
// the number of node ids
#size;
#marks;
// the Sim for strings that are only `.` or `..`
#dotsSim;
// the string to compare, if the pattern has no magic. With
// `nocase:true`, the RegExp that folds case is made when it is
// first used.
#literal;
#literalFold = false;
#literalRe;
// the nodes between the prefix and suffix, if the graph is a
// single chain
#linear;
// the linear nodes are only `*` and `?`, so the length bounds and
// the prefix and suffix decide the match
#wild = false;
// the least and most chars that a match can have
#min = 0;
#max = Infinity;
// the literals that a match must start and end with. Each one
// matches exactly one char, and they are distinct items in the
// pattern, so a string that does not have them can not match.
#prefix = [];
#suffix = [];
// the prefix and suffix as strings, if they do not fold case
#prefixStr;
#suffixStr;
// there is a prefix or suffix to check
#affix = false;
#dfa;
#form;
constructor(pattern, options = {}) {
if (pattern.includes('/')) {
throw new Error('can only match a single path portion, got pattern: ' + pattern);
}
this.pattern = pattern;
this.options = options;
const { nocase = false, noext = false, normalize: n } = options;
this.#form = n === true ? 'NFC' : n || undefined;
// a pattern that is only an empty extglob is a literal string,
// except for `!()`, which matches any non-empty string
const literal = /^[?*+@]\(\)$/.test(pattern);
const toks = tokenize(pattern, nocase, noext || literal, this.#form);
let [items] = build(toks, pair(toks), 0, toks.length, true);
if (this.#form)
items = normalize(items, this.#form);
const [start, size] = compile(items, nocase);
this.#start = start;
this.#size = size;
if (items.every(it => it.t === 'lit')) {
this.#literal = items.map(it => it.ch).join('');
this.#literalFold = nocase;
}
else {
const lit = (it) => it.t !== 'lit' ? undefined
: nocase ? { ch: it.ch, re: foldRe(it.ch) }
: { ch: it.ch };
for (const it of items) {
const l = lit(it);
if (!l)
break;
this.#prefix.push(l);
}
for (let j = items.length - 1; j >= 0; j--) {
const l = lit(items[j]);
if (!l)
break;
this.#suffix.unshift(l);
}
this.#affix = !!(this.#prefix.length || this.#suffix.length);
if (!nocase) {
this.#prefixStr = this.#prefix.map(l => l.ch).join('');
this.#suffixStr = this.#suffix.map(l => l.ch).join('');
}
this.#linear = linear(this.#start)?.slice(this.#prefix.length, -this.#suffix.length || undefined);
this.#wild = !!this.#linear?.every(n => n.t === 'star' || n.t === 'any');
const [min, max] = lengths(items);
this.#min = min;
this.#max = max;
}
}
test(s) {
// The `/` check uses the string as given, so with normalization it
// is a separate step. Otherwise, one scan finds both a `/` and the
// surrogate pairs that stop the string being indexed by code point.
if (this.#form) {
noSlash(s);
return this.#test(s.normalize(this.#form));
}
if (slashOrSurrogate.test(s)) {
noSlash(s);
return this.#test(s, [...s]);
}
return this.#test(s, s);
}
/**
* The same as {@link Matcher#test}, but the string is not checked
* for `/` chars, so the result for a string that has one is not
* defined. Only use it for a string that is known to be one path
* portion, such as a part of a path that was split on `/`. It can
* be faster, because some patterns do not need to look at each char
* of the string.
*/
testUnchecked(s) {
return this.#test(this.#form ? s.normalize(this.#form) : s);
}
// Test a string that has no `/`. `chars` indexes it by code point.
// If it is not given, it is only found if a step needs it.
#test(s, chars) {
if (this.#literal !== undefined) {
return this.#literalFold ?
(this.#literalRe ??= newFoldRe(this.#literal)).test(s)
: s === this.#literal;
}
// the length check means that the prefix and suffix do not
// overlap. Without the chars, the length in code points is from
// half of the UTF-16 length (if each one is a surrogate pair) to
// all of it, which is often enough to know.
const min = this.#min;
const max = this.#max;
if (chars === undefined) {
const most = s.length;
const least = (most + 1) >> 1;
if (most < min || least > max)
return false;
if (least < min || most > max)
chars = codePoints(s);
}
if (chars !== undefined &&
(chars.length < min || chars.length > max)) {
return false;
}
const prefix = this.#prefix.length;
if (this.#affix) {
if (this.#prefixStr !== undefined && this.#suffixStr !== undefined) {
if (!s.startsWith(this.#prefixStr) ||
!s.endsWith(this.#suffixStr)) {
return false;
}
}
else {
chars ??= codePoints(s);
const end = chars.length - this.#suffix.length;
if (!hasAffix(this.#prefix, chars, 0) ||
!hasAffix(this.#suffix, chars, end)) {
return false;
}
}
}
const dotStart = !this.options.dot && s.startsWith('.');
if (this.#linear) {
// `.` and `..` only match literal dots, even with `dot:true`
if (s === '.' || s === '..')
return false;
// only a literal can match the leading dot. A `*` can not
// start a dotfile, even if it matches nothing.
if (dotStart && !prefix)
return false;
if (this.#wild)
return true;
chars ??= codePoints(s);
const end = chars.length - this.#suffix.length;
return testLinear(this.#linear, chars, prefix, end);
}
chars ??= codePoints(s);
if (s === '.' || s === '..') {
this.#marks ??= marks(this.#size);
const sim = (this.#dotsSim ??= new Sim(true, false, this.#marks));
const start = sim.state();
sim.add(start, this.#start, 0, true);
let state = sim.done(start);
for (let i = 0; i < chars.length; i++) {
state = sim.step(state, chars[i], i, true);
}
return state.match;
}
this.#marks ??= marks(this.#size);
const dfa = (this.#dfa ??= new Dfa(this.#start, this.#marks));
let d = dfa.start(dotStart);
// read char codes from the string, so that a one-char string is
// only made for a cache miss
const str = chars === s;
for (let i = 0; i < chars.length; i++) {
if (d.dead)
return false;
const code = str ? s.charCodeAt(i) : chars[i].charCodeAt(0);
d = d.ascii?.[code] ?? dfa.next(d, chars[i]);
}
return d.match;
}
/** a readable listing of the state machine */
toString() {
return show(this.#start);
}
}
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAyCxD,sDAAsD;AACtD,MAAM,KAAK,GAAS,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,EAAE,CAAA;AAEzC,MAAM,QAAQ,GAAG,OAAO,CAAA;AAExB,MAAM,GAAG,GAAG,CAAC,EAAU,EAAQ,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAA;AAEpD,MAAM,QAAQ,GAAG,CAA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CAAC;YAC3B,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAA;QACpB,CAAC;aAAM,IAAI,GAAG,CAAC,CAAC,KAAK,OAAO,EAAE,CAAC;YAC7B,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAA;QACpB,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;QACf,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,oEAAoE;AACpE,oEAAoE;AACpE,kEAAkE;AAClE,yDAAyD;AACzD,MAAM,SAAS,GAAG,CAAC,KAAa,EAAE,IAAU,EAAU,EAAE;IACtD,MAAM,GAAG,GAAW,EAAE,CAAA;IACtB,IAAI,GAAG,GAAG,EAAE,CAAA;IACZ,MAALine truncated
@@ -0,0 +1,3 @@
var D={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}"],"[:alpha:]":["\\p{L}\\p{Nl}"],"[:ascii:]":["\\x00-\\x7f"],"[:blank:]":["\\p{Zs}\\t"],"[:cntrl:]":["\\p{Cc}"],"[:digit:]":["\\p{Nd}"],"[:graph:]":["\\p{Z}\\p{C}",!0],"[:lower:]":["\\p{Ll}"],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}\\p{S}"],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f"],"[:upper:]":["\\p{Lu}"],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}"],"[:xdigit:]":["A-Fa-f0-9"]},y=i=>i.replace(/[[\]\\-]/g,"\\$&"),A=/$./,E=(i,t,e=!1,s)=>{let h=p=>{let m=s?p.normalize(s):p;return[...m].length===1?m:p},n=t;if(i.charAt(n)!=="[")throw new Error("not in a brace expression");let o=[],a=[],r=n+1,l=!1,c=!1,u=!1,g=n,d="";t:for(;r<i.length;){let p=String.fromCodePoint(i.codePointAt(r));if((p==="!"||p==="^")&&r===n+1){u=!0,r++;continue}if(p==="]"&&l&&!c){g=r+1;break}if(l=!0,p==="\\"&&!c){c=!0,r++;continue}if(p==="["&&!c){for(let[z,[R,B]]of Object.entries(D))if(i.startsWith(z,r)){if(d)return[A,i.length-n];r+=z.length,B?a.push(R):o.push(R);continue t}}c=!1;let m=h(p);if(d){m.codePointAt(0)>d.codePointAt(0)?o.push(y(d)+"-"+y(m)):m===d&&o.push(y(m)),d="",r+=p.length;continue}if(i.startsWith("-]",r+p.length)){o.push(y(m+"-")),r+=p.length+1;continue}if(i.startsWith("-",r+p.length)){d=m,r+=p.length+1;continue}o.push(y(m)),r+=p.length}if(g<r)return[A,0];if(!o.length&&!a.length)return[A,i.length-n];let f="["+(u?"^":"")+o.join("")+"]",w="["+(u?"":"^")+a.join("")+"]",q="^"+(o.length&&a.length?"("+f+"|"+w+")":o.length?f:w);return[new RegExp(q,e?"iu":"u"),g-n]};var C={t:"match",id:0},G="!?+*@",x=i=>({t:"lit",ch:i}),H=i=>i.replace(/[\\^$.*+?()[\]{}|/]/g,"\\$&"),W=i=>new RegExp(`^${H(i)}$`,"iu"),S=new Map,v=i=>{let t=S.get(i);return t||(t=W(i),S.size>=1e3&&S.clear(),S.set(i,t)),t},P=(i,t)=>{if(t===i.ch)return!0;if(!i.re)return!1;let e=t.charCodeAt(0);if(e>=128)return i.re.test(t);let s=i.ascii??=new Uint8Array(128);return s[e]||=i.re.test(t)?1:2,s[e]===1},J=(i,t,e,s)=>{let h=[];for(let n=0;n<i.length;){let o=String.fromCodePoint(i.codePointAt(n));if(o==="\\"){let a=i.codePointAt(n+1),r=a===void 0?o:String.fromCodePoint(a);h.push(x(r)),n+=1+r.length;continue}if(o==="["){let[a,r]=E(i,n,t,s);if(r){h.push({t:"class",re:a}),n+=r;continue}}if(!e&&G.includes(o)&&i[n+1]==="("){h.push({t:"open",type:o}),n+=2;continue}h.push(!e&&o==="|"?{t:"bar"}:!e&&o===")"?{t:"close"}:o==="*"?{t:"star"}:o==="?"?{t:"any"}:x(o)),n+=o.length}return h},K=i=>{let t=new Map,e=[];return i.forEach((s,h)=>{s.t==="open"?e.push(h):s.t==="close"&&e.length&&t.set(e.pop(),h)}),t},I=(i,t,e,s,h)=>{let n=[],o=[n];for(let a=e;a<s;a++){let r=i[a],l=t.get(a);if(r.t==="open"&&l!==void 0){let c=I(i,t,a+1,l,!1);n.push({t:"ext",type:r.type,alts:c}),a=l}else r.t==="bar"&&!h?o.push(n=[]):r.t==="open"?n.push(x(r.type),x("(")):r.t==="bar"?n.push(x("|")):r.t==="close"?n.push(x(")")):n.push(r)}return o},T=(i,t)=>{let e=[],s="",h=()=>{for(let n of s.normalize(t))e.push(x(n));s=""};for(let n of i){if(n.t==="lit"){s+=n.ch;continue}h(),e.push(n.t==="ext"?{...n,alts:n.alts.map(o=>T(o,t))}:n)}return h(),e},_=(i,t)=>{let e=1,s=a=>({t:"split",id:e++,out:a}),h=(a,r)=>a.reduceRight((l,c)=>n(c,l),r),n=(a,r)=>{switch(a.t){case"lit":let g=t?v(a.ch):void 0;return{t:"lit",id:e++,ch:a.ch,re:g,next:r};case"any":case"star":return{t:a.t,id:e++,next:r};case"class":return{t:"class",id:e++,re:a.re,next:r}}let l=g=>a.alts.map(d=>h(d,g));switch(a.type){case"@":return s(l(r));case"?":return s([r,...l(r)]);case"!":return{t:"neg",id:e++,sub:s(l(C)),next:r}}let c=s([]),u=s(l(c));return c.out.push(r,u),a.type==="*"?c:u};return[h(i,C),e]},Q=i=>{let t=[],e=new Set,s=n=>n.t==="match"?"match":String(n.id),h=(n,o)=>{if(n.t==="match"||e.has(n))return;e.add(n);let a=r=>t.push(`${o}${n.id}: ${r}`);switch(n.t){case"split":a(`split -> ${n.out.map(s).join(", ")}`);for(let r of n.out)h(r,o);return;case"neg":return a(`!(${s(n.sub)}) -> ${s(n.next)}`),h(n.sub,o+" "),h(n.next,o);case"lit":a(`${JSON.stringify(n.ch)} -> ${s(n.next)}`);break;case"class":a(`${n.re} -> ${s(n.next)}`);break;default:a(`${n.t==="any"?"?":"*"} -> ${s(n.next)}`)}h(n.next,o)};return h(i,""),[`start -> ${s(i)}`,...t].join(`
`)},b=class{gen;threads=[];match=!1;runs=[];ids=[];constructor(t){this.gen=t}get dead(){return!this.threads.length&&!this.match&&!this.runs.length}},O=(i,t)=>i.ids.length!==t.ids.length||i.runs.length!==t.runs.length||i.ids.some((e,s)=>e!==t.ids[s])?!1:i.runs.every(e=>t.runs.some(s=>s.neg===e.neg&&O(s.state,e.state))),N=i=>({has:new Float64Array(i),seen:new Float64Array(i),gen:0}),$=class{dots;dotStart;#t;constructor(t,e,s){this.dots=t,this.dotStart=e,this.#t=s}state(){return new b(++this.#t.gen)}done(t){return t.ids=t.threads.map(e=>e.id).sort((e,s)=>e-s),t.match&&t.ids.unshift(C.id),t}#s(t,e){let{seen:s}=this.#t;return s[e.id]===t.gen?!1:(s[e.id]=t.gen,!0)}#e(t,e){let{has:s}=this.#t;return s[e.id]===t.gen?!1:(s[e.id]=t.gen,t.threads.push(e),!0)}restricted(t,e){return e&&(this.dots||this.dotStart&&t===0)}add(t,e,s,h){switch(e.t){case"split":if(!this.#s(t,e))return;for(let o of e.out)this.add(t,o,s,h);return;case"neg":if(!this.#s(t,e))return;let n=this.state();return this.add(n,e.sub,s,!1),this.done(n),this.addRun(t,{t:"run",neg:e,state:n},s,h);case"star":if(this.restricted(s,h))return;this.#e(t,e)&&this.add(t,e.next,s,h);return;case"match":t.match=!0;return;default:this.#e(t,e)}}addRun(t,e,s,h){for(let n of t.runs)if(n.neg===e.neg&&O(n.state,e.state))return;t.runs.push(e),e.state.match||this.add(t,e.neg.next,s,h)}step(t,e,s,h){let n=this.state();for(let o of t.threads)switch(o.t){case"lit":P(o,e)&&this.add(n,o.next,s+1,h);break;case"any":this.restricted(s,h)||this.add(n,o.next,s+1,h);break;case"class":!this.restricted(s,h)&&o.re.test(e)&&this.add(n,o.next,s+1,h);break;case"star":this.restricted(s,h)||this.add(n,o,s+1,h)}if(!this.restricted(s,h))for(let o of t.runs){if(o.state.dead){this.addRun(n,o,s+1,h);continue}let a=this.step(o.state,e,s,!1);this.addRun(n,{t:"run",neg:o.neg,state:a},s+1,h)}return this.done(n)}},U=i=>{let t=i.ids.join();if(!i.runs.length)return t;let e=i.runs.map(s=>`${s.neg.id}(${U(s.state)})`);return`${t}|${e.sort().join("|")}`},V=1<<18,j=class{#t;#s=new Map;#e=0;#c;#n;#i;#h;constructor(t,e){this.#t=t,this.#i=new $(!1,!1,e),this.#h=new $(!1,!0,e)}#o(t){return{state:t,match:t.match,dead:t.dead,next:new Map}}#u(t){let e=U(t),s=this.#s.get(e);if(s)return s;this.#e>V&&this.#f();let h=this.#o(t);return this.#s.set(e,h),this.#e+=e.length+1,h}#f(){this.#s.clear(),this.#e=0,this.#c=void 0,this.#n=void 0}start(t){if(t){if(this.#n)return this.#n;let s=this.#h.state();return this.#h.add(s,this.#t,0,!0),this.#n=this.#o(this.#h.done(s))}if(this.#c)return this.#c;let e=this.#i.state();return this.#i.add(e,this.#t,0,!0),this.#c=this.#u(this.#i.done(e))}next(t,e){let s=e.charCodeAt(0),h=s<128?void 0:t.next.get(e);if(h)return h;let n=t===this.#n?this.#u(this.#h.step(t.state,e,0,!0)):this.#u(this.#i.step(t.state,e,1,!0));return s<128?(t.ascii||(t.ascii=new Array(128),this.#e+=128),t.ascii[s]=n):t.next.set(e,n),this.#e++,n}},X=i=>{let t=[];for(let e=i;e.t!=="match";e=e.next){if(e.t==="split"||e.t==="neg")return;t.push(e)}return t},Y=(i,t,e,s)=>{let h=0,n=e,o=-1,a=0;for(;n<s;){let r=i[h];if(r?.t==="star"){o=h++,a=n;continue}let l=t[n];if(r&&(r.t==="any"||r.t==="lit"&&P(r,l)||r.t==="class"&&r.re.test(l))){h++,n++;continue}if(o===-1)return!1;h=o+1,n=++a}for(;i[h]?.t==="star";)h++;return h===i.length},Z=i=>{let t=0,e=0;for(let s of i){let[h,n]=tt(s);t+=h,e+=n}return[t,e]},tt=i=>{if(i.t==="star")return[0,1/0];if(i.t!=="ext")return[1,1];if(i.type==="!")return[0,1/0];let t=i.alts.map(Z),e=Math.min(...t.map(n=>n[0])),s=Math.max(...t.map(n=>n[1])),h=s===0?0:1/0;return i.type==="@"?[e,s]:i.type==="?"?[0,s]:i.type==="*"?[0,h]:[e,h]},M=(i,t,e)=>{for(let s=0;s<i.length;s++)if(!P(i[s],t[e+s]))return!1;return!0},et=/[/\ud800-\udfff]/,st=/[\ud800-\udfff]/,k=i=>st.test(i)?[...i]:i,F=i=>{if(i.includes("/"))throw new Error("can only match a single path portion, got: "+i)},L=class{pattern;options;#t;#s;#e;#c;#n;#i=!1;#h;#o;#u=!1;#f=0;#m=1/0;#l=[];#a=[];#p;#g;#w=!1;#x;#r;constructor(t,e={}){if(t.includes("/"))throw new Error("can only match a single path portion, got pattern: "+t);this.pattern=t,this.options=e;let{nocase:s=!1,noext:h=!1,normalize:n}=e;this.#r=n===!0?"NFC":n||void 0;let o=/^[?*+@]\(\)$/.test(t),a=J(t,s,h||o,this.#r),[r]=I(a,K(a),0,a.length,!0);this.#r&&(r=T(r,this.#r));let[l,c]=_(r,s);if(this.#t=l,this.#s=c,r.every(u=>u.t==="lit"))this.#n=r.map(u=>u.ch).join(""),this.#i=s;else{let u=f=>f.t!=="lit"?void 0:s?{ch:f.ch,re:v(f.ch)}:{ch:f.ch};for(let f of r){let w=u(f);if(!w)break;this.#l.push(w)}for(let f=r.length-1;f>=0;f--){let w=u(r[f]);if(!w)break;this.#a.unshift(w)}this.#w=!!(this.#l.length||this.#a.length),s||(this.#p=this.#l.map(f=>f.ch).join(""),this.#g=this.#a.map(f=>f.ch).join("")),this.#o=X(this.#t)?.slice(this.#l.length,-this.#a.length||void 0),this.#u=!!this.#o?.every(f=>f.t==="star"||f.t==="any");let[g,d]=Z(r);this.#f=g,this.#m=d}}test(t){return this.#r?(F(t),this.#d(t.normalize(this.#r))):et.test(t)?(F(t),this.#d(t,[...t])):this.#d(t,t)}testUnchecked(t){return this.#d(this.#r?t.normalize(this.#r):t Line truncated
//# sourceMappingURL=index.min.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../src/parse-class.ts", "../../src/index.ts"],
"sourcesContent": ["// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { <posix class>: [<translation>, negated]\nconst posixClasses: { [k: string]: [e: string, n?: boolean] } = {\n '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}'],\n '[:alpha:]': ['\\\\p{L}\\\\p{Nl}'],\n '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f'],\n '[:blank:]': ['\\\\p{Zs}\\\\t'],\n '[:cntrl:]': ['\\\\p{Cc}'],\n '[:digit:]': ['\\\\p{Nd}'],\n '[:graph:]': ['\\\\p{Z}\\\\p{C}', true],\n '[:lower:]': ['\\\\p{Ll}'],\n '[:print:]': ['\\\\p{C}', true],\n '[:punct:]': ['\\\\p{P}\\\\p{S}'],\n '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f'],\n '[:upper:]': ['\\\\p{Lu}'],\n '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}'],\n '[:xdigit:]': ['A-Fa-f0-9'],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n\nexport type ParseClassResult = [re: RegExp, consumed: number]\n\nexport type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD'\n\nconst noMatch = /$./\n\n// Takes a glob string at a posix brace expression. Returns a RegExp\n// that tests one character, and the number of glob chars consumed.\n// If the class is not closed, consumed is 0, and the `[` must be\n// treated as a literal character.\n// Out of order ranges are removed. If nothing is left, the RegExp\n// is `/$./`, and the rest of the glob is consumed, so that the\n// whole glob cannot match.\nexport const parseClass = (\n glob: string,\n position: number,\n nocase: boolean = false,\n form?: Form,\n): ParseClassResult => {\n // normalize one class member, if it stays one code point\n const norm = (c: string) => {\n const n = form ? c.normalize(form) : c\n return [...n].length === 1 ? n : c\n }\n const pos = position\n /* c8 ignore start */\n if (glob.charAt(pos) !== '[') {\n throw new Error('not in a brace expression')\n }\n /* c8 ignore stop */\n const ranges: string[] = []\n const negs: string[] = []\n\n let i = pos + 1\n let sawStart = false\n let escaping = false\n let negate = false\n let endPos = pos\n let rangeStart = ''\n WHILE: while (i < glob.length) {\n const c = String.fromCodePoint(glob.codePointAt(i)!)\n if ((c === '!' || c === '^') && i === pos + 1) {\n negate = true\n i++\n continue\n }\n\n if (c === ']' && sawStart && !escaping) {\n endPos = i + 1\n break\n }\n\n sawStart = true\n if (c === '\\\\') {\n if (!escaping) {\n escaping = true\n i++\n continue\n }\n // escaped \\ char, fall through and treat like normal char\n }\n if (c === '[' && !escaping) {\n // either a posix class, a collation equivalent, or just a [\n for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n // invalid, [a-[] is fine, but not [a-[:alpha]]\n if (rangeStart) {\n return [noMatch, glob.length - pos]\n }\n i += cls.length\n if (neg) negs.push(unip)\n else ranges.push(unip)\n continue WHILE\n }\n }\n }\n\n // now it's just a normal character, effectively\n escaping = false\n const n = norm(c)\n if (rangeStart) {\n // throw this range away if it's not valid, but others\n // can still match.\n if (n.codePointAt(0)! > rangeStart.codePointAt(0)!) {\n ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n))\n } else if (n === rangeStart) {\n ranges.push(braceEscape(n))\n }\n rangeStart = ''\n i += c.length\n continue\n }\n\n // now might be the start of a range.\n // can be either c-d or c-] or c<more...>] or c] at this point\n if (glob.startsWith('-]', i + c.length)) {\n ranges.push(braceEscape(n + '-'))\n i += c.length + 1\n continue\n }\n if (glob.startsWith('-', i + c.length)) {\n rangeStart = n\n i += c.length + 1\n continue\n }\n\n // not the start of a range, just a single character\n ranges.push(braceEscape(n))\n i += c.length\n }\n\n if (endPos < i) {\n // didn't see the end of the class, not a valid class,\n // but might still be valid as a literal match.\n return [noMatch, 0]\n }\n\n // if we got no ranges and no negates, then we have a range that\n // cannot possibly match anything, and that poisons the whole glob\n if (!ranges.length && !negs.length) {\n return [noMatch, glob.length - pos]\n }\n\n const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']'\n const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']'\n const comb =\n '^' +\n (ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'\n : ranges.length ? sranges\n : snegs)\n\n return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos]\n}\n", "import { type Form, parseClass } from './parse-class.js'\nLine truncated
"mappings": "AAIA,IAAMA,EAA0D,CAC9D,YAAa,CAAC,sBAAsB,EACpC,YAAa,CAAC,eAAe,EAC7B,YAAa,CAAC,aAAuB,EACrC,YAAa,CAAC,YAAY,EAC1B,YAAa,CAAC,SAAS,EACvB,YAAa,CAAC,SAAS,EACvB,YAAa,CAAC,eAAgB,EAAI,EAClC,YAAa,CAAC,SAAS,EACvB,YAAa,CAAC,SAAU,EAAI,EAC5B,YAAa,CAAC,cAAc,EAC5B,YAAa,CAAC,uBAAuB,EACrC,YAAa,CAAC,SAAS,EACvB,WAAY,CAAC,6BAA6B,EAC1C,aAAc,CAAC,WAAW,GAKtBC,EAAeC,GAAcA,EAAE,QAAQ,YAAa,MAAM,EAM1DC,EAAU,KASHC,EAAa,CACxBC,EACAC,EACAC,EAAkB,GAClBC,IACoB,CAEpB,IAAMC,EAAQC,GAAa,CACzB,IAAMC,EAAIH,EAAOE,EAAE,UAAUF,CAAI,EAAIE,EACrC,MAAO,CAAC,GAAGC,CAAC,EAAE,SAAW,EAAIA,EAAID,CACnC,EACME,EAAMN,EAEZ,GAAID,EAAK,OAAOO,CAAG,IAAM,IACvB,MAAM,IAAI,MAAM,2BAA2B,EAG7C,IAAMC,EAAmB,CAAA,EACnBC,EAAiB,CAAA,EAEnBC,EAAIH,EAAM,EACVI,EAAW,GACXC,EAAW,GACXC,EAAS,GACTC,E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UM,EAAGxB,CAAI,CAAC,Line truncated
"names": ["posixClasses", "braceEscape", "s", "noMatch", "parseClass", "glob", "position", "nocase", "form", "norm", "c", "n", "pos", "ranges", "negs", "i", "sawStart", "escaping", "negate", "endPos", "rangeStart", "WHILE", "cls", "unip", "neg", "sranges", "snegs", "comb", "MATCH", "extTypes", "lit", "ch", "reEscape", "s", "newFoldRe", "foldCache", "foldRe", "re", "litMatch", "l", "c", "code", "ascii", "tokenize", "p", "nocase", "noext", "form", "toks", "i", "e", "consumed", "parseClass", "pair", "pairs", "stack", "tok", "build", "start", "end", "top", "seq", "alts", "close", "sub", "normalize", "items", "out", "run", "flush", "it", "a", "compile", "id", "split", "next", "item", "after", "entry", "show", "lines", "seen", "ref", "walk", "indent", "line", "desc", "o", "State", "gen", "sameState", "b", "r", "marks", "size", "Sim", "#marks", "dots", "dotStart", "state", "n", "#visit", "node", "#addThread", "has", "th", "stateKey", "ids", "runs", "DFA_BUDGET", "Dfa", "#start", "#states", "#size", "#plain", "#dotStart", "#sim", "#dotSim", "#make", "#intern", "key", "found", "#clear", "d", "linear", "nodes", "testLinear", "chars", "ni", "ci", "starNi", "starCi", "lengths", "min", "max", "lo", "hi", "itemLengths", "loop", "hasAffix", "lits", "j", "slashOrSurrogate", "surrogate", "codePoints", "noSlash", "Matcher", "#dotsSim", "#literal", "#literalFold", "#literalRe", "#linear", "#wild", "#min", "#max", "#prefix", "#suffix", "#prefixStr", "#suffixStr", "#affix", "#dfa", "#form", "pattern", "options", "literal", "#test", "most", "least", "prefix", "sim", "dfa", "str"]
}
@@ -0,0 +1,3 @@
{
"type": "module"
}
@@ -0,0 +1,4 @@
export type ParseClassResult = [re: RegExp, consumed: number];
export type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD';
export declare const parseClass: (glob: string, position: number, nocase?: boolean, form?: Form) => ParseClassResult;
//# sourceMappingURL=parse-class.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"parse-class.d.ts","sourceRoot":"","sources":["../../src/parse-class.ts"],"names":[],"mappings":"AAyBA,MAAM,MAAM,gBAAgB,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;AAE7D,MAAM,MAAM,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,CAAA;AAWlD,eAAO,MAAM,UAAU,GACrB,MAAM,MAAM,EACZ,UAAU,MAAM,EAChB,SAAQ,OAAe,EACvB,OAAO,IAAI,KACV,gBAkHF,CAAA"}
@@ -0,0 +1,138 @@
// translate the various posix character classes into unicode properties
// this works across all unicode locales
// { <posix class>: [<translation>, negated]
const posixClasses = {
'[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}'],
'[:alpha:]': ['\\p{L}\\p{Nl}'],
'[:ascii:]': ['\\x' + '00-\\x' + '7f'],
'[:blank:]': ['\\p{Zs}\\t'],
'[:cntrl:]': ['\\p{Cc}'],
'[:digit:]': ['\\p{Nd}'],
'[:graph:]': ['\\p{Z}\\p{C}', true],
'[:lower:]': ['\\p{Ll}'],
'[:print:]': ['\\p{C}', true],
'[:punct:]': ['\\p{P}\\p{S}'],
'[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f'],
'[:upper:]': ['\\p{Lu}'],
'[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}'],
'[:xdigit:]': ['A-Fa-f0-9'],
};
// only need to escape a few things inside of brace expressions
// escapes: [ \ ] -
const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
const noMatch = /$./;
// Takes a glob string at a posix brace expression. Returns a RegExp
// that tests one character, and the number of glob chars consumed.
// If the class is not closed, consumed is 0, and the `[` must be
// treated as a literal character.
// Out of order ranges are removed. If nothing is left, the RegExp
// is `/$./`, and the rest of the glob is consumed, so that the
// whole glob cannot match.
export const parseClass = (glob, position, nocase = false, form) => {
// normalize one class member, if it stays one code point
const norm = (c) => {
const n = form ? c.normalize(form) : c;
return [...n].length === 1 ? n : c;
};
const pos = position;
/* c8 ignore start */
if (glob.charAt(pos) !== '[') {
throw new Error('not in a brace expression');
}
/* c8 ignore stop */
const ranges = [];
const negs = [];
let i = pos + 1;
let sawStart = false;
let escaping = false;
let negate = false;
let endPos = pos;
let rangeStart = '';
WHILE: while (i < glob.length) {
const c = String.fromCodePoint(glob.codePointAt(i));
if ((c === '!' || c === '^') && i === pos + 1) {
negate = true;
i++;
continue;
}
if (c === ']' && sawStart && !escaping) {
endPos = i + 1;
break;
}
sawStart = true;
if (c === '\\') {
if (!escaping) {
escaping = true;
i++;
continue;
}
// escaped \ char, fall through and treat like normal char
}
if (c === '[' && !escaping) {
// either a posix class, a collation equivalent, or just a [
for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {
if (glob.startsWith(cls, i)) {
// invalid, [a-[] is fine, but not [a-[:alpha]]
if (rangeStart) {
return [noMatch, glob.length - pos];
}
i += cls.length;
if (neg)
negs.push(unip);
else
ranges.push(unip);
continue WHILE;
}
}
}
// now it's just a normal character, effectively
escaping = false;
const n = norm(c);
if (rangeStart) {
// throw this range away if it's not valid, but others
// can still match.
if (n.codePointAt(0) > rangeStart.codePointAt(0)) {
ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n));
}
else if (n === rangeStart) {
ranges.push(braceEscape(n));
}
rangeStart = '';
i += c.length;
continue;
}
// now might be the start of a range.
// can be either c-d or c-] or c<more...>] or c] at this point
if (glob.startsWith('-]', i + c.length)) {
ranges.push(braceEscape(n + '-'));
i += c.length + 1;
continue;
}
if (glob.startsWith('-', i + c.length)) {
rangeStart = n;
i += c.length + 1;
continue;
}
// not the start of a range, just a single character
ranges.push(braceEscape(n));
i += c.length;
}
if (endPos < i) {
// didn't see the end of the class, not a valid class,
// but might still be valid as a literal match.
return [noMatch, 0];
}
// if we got no ranges and no negates, then we have a range that
// cannot possibly match anything, and that poisons the whole glob
if (!ranges.length && !negs.length) {
return [noMatch, glob.length - pos];
}
const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']';
const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']';
const comb = '^' +
(ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
: ranges.length ? sranges
: snegs);
return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos];
};
//# sourceMappingURL=parse-class.js.map
@@ -0,0 +1 @@
{"version":3,"file":"parse-class.js","sourceRoot":"","sources":["../../src/parse-class.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,wCAAwC;AAExC,4CAA4C;AAC5C,MAAM,YAAY,GAA8C;IAC9D,WAAW,EAAE,CAAC,sBAAsB,CAAC;IACrC,WAAW,EAAE,CAAC,eAAe,CAAC;IAC9B,WAAW,EAAE,CAAC,KAAK,GAAG,QAAQ,GAAG,IAAI,CAAC;IACtC,WAAW,EAAE,CAAC,YAAY,CAAC;IAC3B,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,WAAW,EAAE,CAAC,cAAc,EAAE,IAAI,CAAC;IACnC,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,WAAW,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC;IAC7B,WAAW,EAAE,CAAC,cAAc,CAAC;IAC7B,WAAW,EAAE,CAAC,uBAAuB,CAAC;IACtC,WAAW,EAAE,CAAC,SAAS,CAAC;IACxB,UAAU,EAAE,CAAC,6BAA6B,CAAC;IAC3C,YAAY,EAAE,CAAC,WAAW,CAAC;CAC5B,CAAA;AAED,+DAA+D;AAC/D,mBAAmB;AACnB,MAAM,WAAW,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,MAAM,CAAC,CAAA;AAMjE,MAAM,OAAO,GAAG,IAAI,CAAA;AAEpB,oEAAoE;AACpE,mEAAmE;AACnE,iEAAiE;AACjE,kCAAkC;AAClC,kEAAkE;AAClE,+DAA+D;AAC/D,2BAA2B;AAC3B,MAAM,CAAC,MAAM,UAAU,GAAG,CACxB,I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AAI,CAAC,MAAM,GAAG,GAAG,CAAC,CAAA;IACrC,CAAC;IAED,MAAM,OAAO,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,GAAG,CAAA;IACjE,MAAM,KAAK,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,GAAG,CAAA;IAC7D,MAAM,IAAI,GACR,GAAG;QACH,CAAC,MAAM,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,GAAG,KAAK,GAAG,GAAG;YACjE,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO;gBACzB,CAAC,CAAC,KAAK,CAAC,CAAA;IAEV,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC,CAAA;AAC9D,CAAC,CAAA","sourcesContent":["// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { <posix class>: [<translation>, negated]\nconst posixClasses: { [k: string]: [e: string, n?: boolean] } = {\n '[Line truncated
+56
View File
@@ -0,0 +1,56 @@
{
"name": "@isaacs/nonrecursive-glob-match",
"description": "a single-path-portion glob matcher not subject to recursive backtracking ReDoS",
"version": "1.0.3",
"license": "BlueOak-1.0.0",
"files": [
"dist",
"src"
],
"devDependencies": {
"esbuild": "^0.28.2",
"prettier": "^3.9.10",
"tap": "^21.8.0",
"tshy": "^4.1.3",
"typedoc": "^0.28.20"
},
"scripts": {
"format": "prettier --write .",
"test": "tap",
"snap": "tap",
"typedoc": "typedoc",
"pretest": "npm run prepare",
"presnap": "npm run prepare",
"prepare": "tshy && bash scripts/build.sh",
"preversion": "npm test",
"postversion": "npm publish",
"prepublishOnly": "git push origin --follow-tags"
},
"type": "module",
"tshy": {
"selfLink": false,
"exports": {
"./package.json": "./package.json",
".": "./src/index.ts"
}
},
"exports": {
"./package.json": "./package.json",
".": {
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
},
"require": {
"types": "./dist/commonjs/index.d.ts",
"default": "./dist/commonjs/index.js"
}
}
},
"main": "./dist/commonjs/index.js",
"types": "./dist/commonjs/index.d.ts",
"module": "./dist/esm/index.js",
"allowScripts": {
"[email protected]": true
}
}
+900
View File
@@ -0,0 +1,900 @@
import { type Form, parseClass } from './parse-class.js'
export type { Form }
export type MatcherOptions = {
/** perform a case-insensitive match */
nocase?: boolean
/** do not treat strings starting with `.` specially */
dot?: boolean
/** do not match extglobs (treat them as normal strings) */
noext?: boolean
/**
* normalize unicode in the pattern and the tested strings, with
* this form. `true` means `'NFC'`.
*/
normalize?: boolean | Form
}
// parsed pattern items
export type Item =
| { t: 'lit'; ch: string }
| { t: 'any' | 'star' }
| { t: 'class'; re: RegExp }
| { t: 'ext'; type: string; alts: Item[][] }
// extglob syntax tokens become literals if they are not part of a
// closed extglob
export type Token =
Item | { t: 'open'; type: string } | { t: 'bar' } | { t: 'close' }
// state machine nodes
export type NegNode = { t: 'neg'; id: number; sub: Node; next: Node }
export type SplitNode = { t: 'split'; id: number; out: Node[] }
export type Node =
| ({ t: 'lit'; id: number; next: Node } & Lit)
| { t: 'any' | 'star'; id: number; next: Node }
| { t: 'class'; id: number; re: RegExp; next: Node }
| SplitNode
| NegNode
| { t: 'match'; id: number }
// the end of the pattern, or of a negated sub-pattern
const MATCH: Node = { t: 'match', id: 0 }
const extTypes = '!?+*@'
const lit = (ch: string): Item => ({ t: 'lit', ch })
const reEscape = (s: string) => s.replace(/[\\^$.*+?()[\]{}|/]/g, '\\$&')
// a RegExp that only matches `s`, with unicode case folding
const newFoldRe = (s: string) => new RegExp(`^${reEscape(s)}$`, 'iu')
// foldRe for one literal char. The same chars are in most patterns,
// so keep them. A RegExp without the `g` or `y` flag has no state to
// share.
const foldCache = new Map<string, RegExp>()
const foldRe = (ch: string) => {
let re = foldCache.get(ch)
if (!re) {
re = newFoldRe(ch)
if (foldCache.size >= 1000) foldCache.clear()
foldCache.set(ch, re)
}
return re
}
/**
* A literal char. With `nocase:true`, `re` folds case, and `ascii`
* holds its results for ASCII chars, by char code: 1 for a match,
* and 2 for not.
*/
export type Lit = { ch: string; re?: RegExp; ascii?: Uint8Array }
const litMatch = (l: Lit, c: string) => {
if (c === l.ch) return true
if (!l.re) return false
const code = c.charCodeAt(0)
if (code >= 128) return l.re.test(c)
const ascii = (l.ascii ??= new Uint8Array(128))
ascii[code] ||= l.re.test(c) ? 1 : 2
return ascii[code] === 1
}
const tokenize = (
p: string,
nocase: boolean,
noext: boolean,
form?: Form,
) => {
const toks: Token[] = []
for (let i = 0; i < p.length;) {
const c = String.fromCodePoint(p.codePointAt(i)!)
if (c === '\\') {
// a trailing \ is a literal \
const e = p.codePointAt(i + 1)
const ch = e === undefined ? c : String.fromCodePoint(e)
toks.push(lit(ch))
i += 1 + ch.length
continue
}
if (c === '[') {
const [re, consumed] = parseClass(p, i, nocase, form)
if (consumed) {
toks.push({ t: 'class', re })
i += consumed
continue
}
}
if (!noext && extTypes.includes(c) && p[i + 1] === '(') {
toks.push({ t: 'open', type: c })
i += 2
continue
}
toks.push(
!noext && c === '|' ? { t: 'bar' }
: !noext && c === ')' ? { t: 'close' }
: c === '*' ? { t: 'star' }
: c === '?' ? { t: 'any' }
: lit(c),
)
i += c.length
}
return toks
}
// map each open token index to the index of its close token
const pair = (toks: Token[]) => {
const pairs = new Map<number, number>()
const stack: number[] = []
toks.forEach((tok, i) => {
if (tok.t === 'open') stack.push(i)
else if (tok.t === 'close' && stack.length) pairs.set(stack.pop()!, i)
})
return pairs
}
// build the alternatives between start and end. An open token that
// is not closed is never inside a closed extglob, so bar and close
// tokens are only literal at the top level.
const build = (
toks: Token[],
pairs: Map<number, number>,
start: number,
end: number,
top: boolean,
): Item[][] => {
let seq: Item[] = []
const alts = [seq]
for (let i = start; i < end; i++) {
const tok = toks[i]!
const close = pairs.get(i)
if (tok.t === 'open' && close !== undefined) {
const sub = build(toks, pairs, i + 1, close, false)
seq.push({ t: 'ext', type: tok.type, alts: sub })
i = close
} else if (tok.t === 'bar' && !top) {
alts.push((seq = []))
} else if (tok.t === 'open') {
seq.push(lit(tok.type), lit('('))
} else if (tok.t === 'bar') {
seq.push(lit('|'))
} else if (tok.t === 'close') {
seq.push(lit(')'))
} else {
seq.push(tok)
}
}
return alts
}
// normalize each run of literal chars as one string, so that a char
// and the combining marks after it compose (or decompose) together.
// Syntax is already parsed, so a char that normalizes to a syntax
// char (such as full-width `*` in NFKC) stays a literal.
const normalize = (items: Item[], form: Form): Item[] => {
const out: Item[] = []
let run = ''
const flush = () => {
for (const ch of run.normalize(form)) out.push(lit(ch))
run = ''
}
for (const it of items) {
if (it.t === 'lit') {
run += it.ch
continue
}
flush()
out.push(
it.t === 'ext' ?
{ ...it, alts: it.alts.map(a => normalize(a, form)) }
: it,
)
}
flush()
return out
}
// the start node, and the number of node ids. Ids are dense, from 0
// for the match node.
const compile = (
items: Item[],
nocase: boolean,
): [start: Node, size: number] => {
let id = 1
const split = (out: Node[]): SplitNode => ({ t: 'split', id: id++, out })
const seq = (items: Item[], next: Node): Node =>
items.reduceRight((next, it) => item(it, next), next)
const item = (it: Item, next: Node): Node => {
switch (it.t) {
case 'lit':
const re = nocase ? foldRe(it.ch) : undefined
return { t: 'lit', id: id++, ch: it.ch, re, next }
case 'any':
case 'star':
return { t: it.t, id: id++, next }
case 'class':
return { t: 'class', id: id++, re: it.re, next }
}
const alts = (next: Node) => it.alts.map(a => seq(a, next))
switch (it.type) {
case '@':
return split(alts(next))
case '?':
return split([next, ...alts(next)])
case '!':
return { t: 'neg', id: id++, sub: split(alts(MATCH)), next }
}
// * and +, loop back after each match
const after = split([])
const entry = split(alts(after))
after.out.push(next, entry)
return it.type === '*' ? after : entry
}
const start = seq(items, MATCH)
return [start, id]
}
// one line per node, in the order that a walk from the start
// reaches them. Edges point to node ids. The nodes of a negated
// sub-pattern are indented under their negation.
const show = (start: Node): string => {
const lines: string[] = []
const seen = new Set<Node>()
const ref = (n: Node) => (n.t === 'match' ? 'match' : String(n.id))
const walk = (n: Node, indent: string) => {
if (n.t === 'match' || seen.has(n)) return
seen.add(n)
const line = (desc: string) => lines.push(`${indent}${n.id}: ${desc}`)
switch (n.t) {
case 'split':
line(`split -> ${n.out.map(ref).join(', ')}`)
for (const o of n.out) walk(o, indent)
return
case 'neg':
line(`!(${ref(n.sub)}) -> ${ref(n.next)}`)
walk(n.sub, indent + ' ')
return walk(n.next, indent)
case 'lit':
line(`${JSON.stringify(n.ch)} -> ${ref(n.next)}`)
break
case 'class':
line(`${n.re} -> ${ref(n.next)}`)
break
default:
line(`${n.t === 'any' ? '?' : '*'} -> ${ref(n.next)}`)
}
walk(n.next, indent)
}
walk(start, '')
return [`start -> ${ref(start)}`, ...lines].join('\n')
}
// A thread inside a !(...) negation. It holds the threads of the
// negated sub-pattern, started where the negation started. The
// negation matches the chars so far if the sub-pattern does not.
type Run = { t: 'run'; neg: NegNode; state: State }
// The threads at one position in the string. Each node thread is
// only kept once, and runs with the same state are only kept once,
// so that identical threads merge. The match node is not in
// `threads`, because it can not step. It sets `match` instead.
class State {
// set by the Sim, to mark the nodes that this state has
gen: number
threads: Node[] = []
match = false
runs: Run[] = []
// the sorted ids of the threads, with 0 for a match, once the
// state is done
ids: number[] = []
constructor(gen: number) {
this.gen = gen
}
// no threads, so nothing more can match
get dead() {
return !this.threads.length && !this.match && !this.runs.length
}
}
// true if the two states hold the same threads
const sameState = (a: State, b: State): boolean => {
if (a.ids.length !== b.ids.length) return false
if (a.runs.length !== b.runs.length) return false
if (a.ids.some((id, i) => id !== b.ids[i])) return false
return a.runs.every(r =>
b.runs.some(o => o.neg === r.neg && sameState(o.state, r.state)),
)
}
/**
* For each node id, the gen of the last state that has the node as
* a thread, and of the last state that walked through it. A state is
* built to the end before the states around it go on, and the nodes
* of a negated sub-pattern are only in its states (other than the
* match node, which is never marked). So one mark for each node is
* enough to know if the state being built has it. The Sims of a
* matcher never run at the same time, so they share one Marks.
*/
export type Marks = { has: Float64Array; seen: Float64Array; gen: number }
const marks = (size: number): Marks => ({
has: new Float64Array(size),
seen: new Float64Array(size),
gen: 0,
})
class Sim {
// `.` and `..` only match literal dots, even with `dot:true`
dots: boolean
// the string starts with `.`, and `dot:true` is not set
dotStart: boolean
#marks: Marks
constructor(dots: boolean, dotStart: boolean, marks: Marks) {
this.dots = dots
this.dotStart = dotStart
this.#marks = marks
}
state() {
return new State(++this.#marks.gen)
}
// sort the ids of a state, once it has all of its threads
done(state: State) {
state.ids = state.threads.map(n => n.id).sort((a, b) => a - b)
if (state.match) state.ids.unshift(MATCH.id)
return state
}
// true the first time that the state walks through the node, so
// that loops in the graph stop
#visit(state: State, node: Node) {
const { seen } = this.#marks
if (seen[node.id] === state.gen) return false
seen[node.id] = state.gen
return true
}
#addThread(state: State, node: Node) {
const { has } = this.#marks
if (has[node.id] === state.gen) return false
has[node.id] = state.gen
state.threads.push(node)
return true
}
// wildcards only match a leading dot if `dot:true`. In a negated
// sub-pattern, this does not apply, because the negation itself
// can not match a leading dot.
restricted(i: number, top: boolean) {
return top && (this.dots || (this.dotStart && i === 0))
}
add(state: State, node: Node, i: number, top: boolean): void {
switch (node.t) {
case 'split':
if (!this.#visit(state, node)) return
for (const o of node.out) this.add(state, o, i, top)
return
case 'neg':
if (!this.#visit(state, node)) return
const sub = this.state()
this.add(sub, node.sub, i, false)
this.done(sub)
return this.addRun(
state,
{ t: 'run', neg: node, state: sub },
i,
top,
)
case 'star':
// a * can not start a dotfile, even if it matches nothing
if (this.restricted(i, top)) return
if (this.#addThread(state, node))
this.add(state, node.next, i, top)
return
case 'match':
state.match = true
return
default:
this.#addThread(state, node)
}
}
addRun(state: State, run: Run, i: number, top: boolean) {
for (const r of state.runs) {
if (r.neg === run.neg && sameState(r.state, run.state)) return
}
state.runs.push(run)
if (!run.state.match) {
this.add(state, run.neg.next, i, top)
}
}
// the threads after char `c`, at index `i`
step(state: State, c: string, i: number, top: boolean): State {
const next = this.state()
for (const th of state.threads) {
switch (th.t) {
case 'lit':
if (litMatch(th, c)) {
this.add(next, th.next, i + 1, top)
}
break
case 'any':
if (!this.restricted(i, top)) this.add(next, th.next, i + 1, top)
break
case 'class':
if (!this.restricted(i, top) && th.re.test(c)) {
this.add(next, th.next, i + 1, top)
}
break
case 'star':
if (!this.restricted(i, top)) this.add(next, th, i + 1, top)
}
}
if (!this.restricted(i, top)) {
for (const run of state.runs) {
// a sub-pattern with no threads can not match again, so the
// run stays the same
if (run.state.dead) {
this.addRun(next, run, i + 1, top)
continue
}
const sub = this.step(run.state, c, i, false)
this.addRun(
next,
{ t: 'run', neg: run.neg, state: sub },
i + 1,
top,
)
}
}
return this.done(next)
}
}
// A canonical key for the threads in a state. States with the same
// key hold the same threads, so they match the same strings.
const stateKey = (state: State): string => {
const ids = state.ids.join()
if (!state.runs.length) return ids
const runs = state.runs.map(r => `${r.neg.id}(${stateKey(r.state)})`)
return `${ids}|${runs.sort().join('|')}`
}
// A cached state of the simulation, and the states that each char
// leads to.
type DState = {
state: State
match: boolean
// no threads, so nothing more can match
dead: boolean
// the next state for each ASCII char, by char code, and for the
// other chars
ascii?: (DState | undefined)[]
next: Map<string, DState>
}
// The cache can hold about this many chars of state keys and
// transitions. When it is full, it is cleared, so that a pattern
// can not use an unbounded amount of memory.
const DFA_BUDGET = 1 << 18
// A cache of the states that the simulation reaches, built as the
// matcher is used. Each char of a string is then one Map lookup,
// once the states that it leads to are known.
//
// The dot rules only restrict the first char of a dotfile (strings
// that are only `.` or `..` do not use the cache). So a dotfile
// starts at its own state, which takes its first step with the
// restriction, and every other state takes steps without it.
class Dfa {
#start: Node
#states = new Map<string, DState>()
#size = 0
#plain?: DState
#dotStart?: DState
#sim: Sim
#dotSim: Sim
constructor(start: Node, marks: Marks) {
this.#start = start
this.#sim = new Sim(false, false, marks)
this.#dotSim = new Sim(false, true, marks)
}
#make(state: State): DState {
return {
state,
match: state.match,
dead: state.dead,
next: new Map(),
}
}
#intern(state: State): DState {
const key = stateKey(state)
const found = this.#states.get(key)
if (found) return found
if (this.#size > DFA_BUDGET) this.#clear()
const d = this.#make(state)
this.#states.set(key, d)
this.#size += key.length + 1
return d
}
#clear() {
this.#states.clear()
this.#size = 0
this.#plain = undefined
this.#dotStart = undefined
}
start(dotStart: boolean): DState {
if (dotStart) {
if (this.#dotStart) return this.#dotStart
const state = this.#dotSim.state()
this.#dotSim.add(state, this.#start, 0, true)
return (this.#dotStart = this.#make(this.#dotSim.done(state)))
}
if (this.#plain) return this.#plain
const state = this.#sim.state()
this.#sim.add(state, this.#start, 0, true)
return (this.#plain = this.#intern(this.#sim.done(state)))
}
// the next state, after a miss in `d.ascii`
next(d: DState, c: string): DState {
const code = c.charCodeAt(0)
const found = code < 128 ? undefined : d.next.get(c)
if (found) return found
// the dotfile start is not in the cache, so it is never shared
const n =
d === this.#dotStart ?
this.#intern(this.#dotSim.step(d.state, c, 0, true))
: this.#intern(this.#sim.step(d.state, c, 1, true))
if (code < 128) {
if (!d.ascii) {
d.ascii = new Array(128)
this.#size += 128
}
d.ascii[code] = n
} else {
d.next.set(c, n)
}
this.#size++
return n
}
}
/**
* A node in a graph with no splits or negations. Such a graph is a
* chain of nodes that each match one char, or a `*`.
*/
export type LinearNode = Exclude<
Node,
SplitNode | NegNode | { t: 'match' }
>
// the nodes in order, if the graph is a single chain
const linear = (start: Node): LinearNode[] | undefined => {
const nodes: LinearNode[] = []
for (let n = start; n.t !== 'match'; n = n.next) {
if (n.t === 'split' || n.t === 'neg') return undefined
nodes.push(n)
}
return nodes
}
// Match a chain of nodes. Each node other than `*` matches exactly
// one char, so on a failure it is enough to go back to the last `*`
// and let it match one more char. This takes at most
// nodes.length * chars.length steps.
const testLinear = (
nodes: LinearNode[],
chars: ArrayLike<string>,
start: number,
end: number,
) => {
let ni = 0
let ci = start
let starNi = -1
let starCi = 0
while (ci < end) {
const n = nodes[ni]
if (n?.t === 'star') {
starNi = ni++
starCi = ci
continue
}
const c = chars[ci]!
if (
n &&
(n.t === 'any' ||
(n.t === 'lit' && litMatch(n, c)) ||
(n.t === 'class' && n.re.test(c)))
) {
ni++
ci++
continue
}
if (starNi === -1) return false
ni = starNi + 1
ci = ++starCi
}
while (nodes[ni]?.t === 'star') ni++
return ni === nodes.length
}
// The least and most chars that the items can match. These are only
// bounds: a negation can match a string of any length, so it counts
// as 0 to Infinity.
const lengths = (items: Item[]): [min: number, max: number] => {
let min = 0
let max = 0
for (const it of items) {
const [lo, hi] = itemLengths(it)
min += lo
max += hi
}
return [min, max]
}
const itemLengths = (it: Item): [min: number, max: number] => {
if (it.t === 'star') return [0, Infinity]
if (it.t !== 'ext') return [1, 1]
if (it.type === '!') return [0, Infinity]
const alts = it.alts.map(lengths)
const min = Math.min(...alts.map(a => a[0]))
const max = Math.max(...alts.map(a => a[1]))
// a loop of alternatives that only match the empty string is empty
const loop = max === 0 ? 0 : Infinity
return (
it.type === '@' ? [min, max]
: it.type === '?' ? [0, max]
: it.type === '*' ? [0, loop]
: [min, loop]
)
}
// true if the chars from `start` match the literals
const hasAffix = (
lits: Lit[],
chars: ArrayLike<string>,
start: number,
) => {
for (let j = 0; j < lits.length; j++) {
if (!litMatch(lits[j]!, chars[start + j]!)) return false
}
return true
}
// a `/`, or half of a surrogate pair
const slashOrSurrogate = /[/\ud800-\udfff]/
const surrogate = /[\ud800-\udfff]/
// a string can be indexed by code point, unless it has surrogate
// pairs
const codePoints = (s: string): ArrayLike<string> =>
surrogate.test(s) ? [...s] : s
const noSlash = (s: string) => {
if (s.includes('/')) {
throw new Error('can only match a single path portion, got: ' + s)
}
}
export class Matcher {
pattern: string
options: MatcherOptions
#start: Node
// the number of node ids
#size: number
#marks?: Marks
// the Sim for strings that are only `.` or `..`
#dotsSim?: Sim
// the string to compare, if the pattern has no magic. With
// `nocase:true`, the RegExp that folds case is made when it is
// first used.
#literal?: string
#literalFold = false
#literalRe?: RegExp
// the nodes between the prefix and suffix, if the graph is a
// single chain
#linear?: LinearNode[]
// the linear nodes are only `*` and `?`, so the length bounds and
// the prefix and suffix decide the match
#wild = false
// the least and most chars that a match can have
#min = 0
#max = Infinity
// the literals that a match must start and end with. Each one
// matches exactly one char, and they are distinct items in the
// pattern, so a string that does not have them can not match.
#prefix: Lit[] = []
#suffix: Lit[] = []
// the prefix and suffix as strings, if they do not fold case
#prefixStr?: string
#suffixStr?: string
// there is a prefix or suffix to check
#affix = false
#dfa?: Dfa
#form?: Form
constructor(pattern: string, options: MatcherOptions = {}) {
if (pattern.includes('/')) {
throw new Error(
'can only match a single path portion, got pattern: ' + pattern,
)
}
this.pattern = pattern
this.options = options
const { nocase = false, noext = false, normalize: n } = options
this.#form = n === true ? 'NFC' : n || undefined
// a pattern that is only an empty extglob is a literal string,
// except for `!()`, which matches any non-empty string
const literal = /^[?*+@]\(\)$/.test(pattern)
const toks = tokenize(pattern, nocase, noext || literal, this.#form)
let [items] = build(toks, pair(toks), 0, toks.length, true)
if (this.#form) items = normalize(items!, this.#form)
const [start, size] = compile(items!, nocase)
this.#start = start
this.#size = size
if (items!.every(it => it.t === 'lit')) {
this.#literal = items!.map(it => it.ch).join('')
this.#literalFold = nocase
} else {
const lit = (it: Item): Lit | undefined =>
it.t !== 'lit' ? undefined
: nocase ? { ch: it.ch, re: foldRe(it.ch) }
: { ch: it.ch }
for (const it of items!) {
const l = lit(it)
if (!l) break
this.#prefix.push(l)
}
for (let j = items!.length - 1; j >= 0; j--) {
const l = lit(items![j]!)
if (!l) break
this.#suffix.unshift(l)
}
this.#affix = !!(this.#prefix.length || this.#suffix.length)
if (!nocase) {
this.#prefixStr = this.#prefix.map(l => l.ch).join('')
this.#suffixStr = this.#suffix.map(l => l.ch).join('')
}
this.#linear = linear(this.#start)?.slice(
this.#prefix.length,
-this.#suffix.length || undefined,
)
this.#wild = !!this.#linear?.every(
n => n.t === 'star' || n.t === 'any',
)
const [min, max] = lengths(items!)
this.#min = min
this.#max = max
}
}
test(s: string): boolean {
// The `/` check uses the string as given, so with normalization it
// is a separate step. Otherwise, one scan finds both a `/` and the
// surrogate pairs that stop the string being indexed by code point.
if (this.#form) {
noSlash(s)
return this.#test(s.normalize(this.#form))
}
if (slashOrSurrogate.test(s)) {
noSlash(s)
return this.#test(s, [...s])
}
return this.#test(s, s)
}
/**
* The same as {@link Matcher#test}, but the string is not checked
* for `/` chars, so the result for a string that has one is not
* defined. Only use it for a string that is known to be one path
* portion, such as a part of a path that was split on `/`. It can
* be faster, because some patterns do not need to look at each char
* of the string.
*/
testUnchecked(s: string): boolean {
return this.#test(this.#form ? s.normalize(this.#form) : s)
}
// Test a string that has no `/`. `chars` indexes it by code point.
// If it is not given, it is only found if a step needs it.
#test(s: string, chars?: ArrayLike<string>): boolean {
if (this.#literal !== undefined) {
return this.#literalFold ?
(this.#literalRe ??= newFoldRe(this.#literal)).test(s)
: s === this.#literal
}
// the length check means that the prefix and suffix do not
// overlap. Without the chars, the length in code points is from
// half of the UTF-16 length (if each one is a surrogate pair) to
// all of it, which is often enough to know.
const min = this.#min
const max = this.#max
if (chars === undefined) {
const most = s.length
const least = (most + 1) >> 1
if (most < min || least > max) return false
if (least < min || most > max) chars = codePoints(s)
}
if (
chars !== undefined &&
(chars.length < min || chars.length > max)
) {
return false
}
const prefix = this.#prefix.length
if (this.#affix) {
if (this.#prefixStr !== undefined && this.#suffixStr !== undefined) {
if (
!s.startsWith(this.#prefixStr) ||
!s.endsWith(this.#suffixStr)
) {
return false
}
} else {
chars ??= codePoints(s)
const end = chars.length - this.#suffix.length
if (
!hasAffix(this.#prefix, chars, 0) ||
!hasAffix(this.#suffix, chars, end)
) {
return false
}
}
}
const dotStart = !this.options.dot && s.startsWith('.')
if (this.#linear) {
// `.` and `..` only match literal dots, even with `dot:true`
if (s === '.' || s === '..') return false
// only a literal can match the leading dot. A `*` can not
// start a dotfile, even if it matches nothing.
if (dotStart && !prefix) return false
if (this.#wild) return true
chars ??= codePoints(s)
const end = chars.length - this.#suffix.length
return testLinear(this.#linear, chars, prefix, end)
}
chars ??= codePoints(s)
if (s === '.' || s === '..') {
this.#marks ??= marks(this.#size)
const sim = (this.#dotsSim ??= new Sim(true, false, this.#marks))
const start = sim.state()
sim.add(start, this.#start, 0, true)
let state = sim.done(start)
for (let i = 0; i < chars.length; i++) {
state = sim.step(state, chars[i]!, i, true)
}
return state.match
}
this.#marks ??= marks(this.#size)
const dfa = (this.#dfa ??= new Dfa(this.#start, this.#marks))
let d = dfa.start(dotStart)
// read char codes from the string, so that a one-char string is
// only made for a cache miss
const str = chars === s
for (let i = 0; i < chars.length; i++) {
if (d.dead) return false
const code = str ? s.charCodeAt(i) : chars[i]!.charCodeAt(0)
d = d.ascii?.[code] ?? dfa.next(d, chars[i]!)
}
return d.match
}
/** a readable listing of the state machine */
toString(): string {
return show(this.#start)
}
}
@@ -0,0 +1,158 @@
// translate the various posix character classes into unicode properties
// this works across all unicode locales
// { <posix class>: [<translation>, negated]
const posixClasses: { [k: string]: [e: string, n?: boolean] } = {
'[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}'],
'[:alpha:]': ['\\p{L}\\p{Nl}'],
'[:ascii:]': ['\\x' + '00-\\x' + '7f'],
'[:blank:]': ['\\p{Zs}\\t'],
'[:cntrl:]': ['\\p{Cc}'],
'[:digit:]': ['\\p{Nd}'],
'[:graph:]': ['\\p{Z}\\p{C}', true],
'[:lower:]': ['\\p{Ll}'],
'[:print:]': ['\\p{C}', true],
'[:punct:]': ['\\p{P}\\p{S}'],
'[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f'],
'[:upper:]': ['\\p{Lu}'],
'[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}'],
'[:xdigit:]': ['A-Fa-f0-9'],
}
// only need to escape a few things inside of brace expressions
// escapes: [ \ ] -
const braceEscape = (s: string) => s.replace(/[[\]\\-]/g, '\\$&')
export type ParseClassResult = [re: RegExp, consumed: number]
export type Form = 'NFC' | 'NFD' | 'NFKC' | 'NFKD'
const noMatch = /$./
// Takes a glob string at a posix brace expression. Returns a RegExp
// that tests one character, and the number of glob chars consumed.
// If the class is not closed, consumed is 0, and the `[` must be
// treated as a literal character.
// Out of order ranges are removed. If nothing is left, the RegExp
// is `/$./`, and the rest of the glob is consumed, so that the
// whole glob cannot match.
export const parseClass = (
glob: string,
position: number,
nocase: boolean = false,
form?: Form,
): ParseClassResult => {
// normalize one class member, if it stays one code point
const norm = (c: string) => {
const n = form ? c.normalize(form) : c
return [...n].length === 1 ? n : c
}
const pos = position
/* c8 ignore start */
if (glob.charAt(pos) !== '[') {
throw new Error('not in a brace expression')
}
/* c8 ignore stop */
const ranges: string[] = []
const negs: string[] = []
let i = pos + 1
let sawStart = false
let escaping = false
let negate = false
let endPos = pos
let rangeStart = ''
WHILE: while (i < glob.length) {
const c = String.fromCodePoint(glob.codePointAt(i)!)
if ((c === '!' || c === '^') && i === pos + 1) {
negate = true
i++
continue
}
if (c === ']' && sawStart && !escaping) {
endPos = i + 1
break
}
sawStart = true
if (c === '\\') {
if (!escaping) {
escaping = true
i++
continue
}
// escaped \ char, fall through and treat like normal char
}
if (c === '[' && !escaping) {
// either a posix class, a collation equivalent, or just a [
for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {
if (glob.startsWith(cls, i)) {
// invalid, [a-[] is fine, but not [a-[:alpha]]
if (rangeStart) {
return [noMatch, glob.length - pos]
}
i += cls.length
if (neg) negs.push(unip)
else ranges.push(unip)
continue WHILE
}
}
}
// now it's just a normal character, effectively
escaping = false
const n = norm(c)
if (rangeStart) {
// throw this range away if it's not valid, but others
// can still match.
if (n.codePointAt(0)! > rangeStart.codePointAt(0)!) {
ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n))
} else if (n === rangeStart) {
ranges.push(braceEscape(n))
}
rangeStart = ''
i += c.length
continue
}
// now might be the start of a range.
// can be either c-d or c-] or c<more...>] or c] at this point
if (glob.startsWith('-]', i + c.length)) {
ranges.push(braceEscape(n + '-'))
i += c.length + 1
continue
}
if (glob.startsWith('-', i + c.length)) {
rangeStart = n
i += c.length + 1
continue
}
// not the start of a range, just a single character
ranges.push(braceEscape(n))
i += c.length
}
if (endPos < i) {
// didn't see the end of the class, not a valid class,
// but might still be valid as a literal match.
return [noMatch, 0]
}
// if we got no ranges and no negates, then we have a range that
// cannot possibly match anything, and that poisons the whole glob
if (!ranges.length && !negs.length) {
return [noMatch, glob.length - pos]
}
const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']'
const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']'
const comb =
'^' +
(ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
: ranges.length ? sranges
: snegs)
return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos]
}
+64
View File
@@ -0,0 +1,64 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres
to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.0.3] - 2023-01-19
### Changed
- Correctly log object keys [#1](https://github.com/seald/node-binary-search-tree/pull/1)
## [1.0.2] - 2021-05-19
### Changed
- Specify files to be included in published version, v1.0.1 contained cache,
which contains, a now revoked, npm authentication token.
## [1.0.1] - 2021-05-19
### Added
- Added a changelog.
### Changed
- Removed `underscore` dependency which was used only in the tests.
## [1.0.0] - 2021-05-17
This version should be a drop-in replacement for `[email protected]`
provided you use modern browsers / versions of Node.js since ES6 features are
now used (such as `class` and `const` / `let`).
### Changed
- Update `homepage` & `repository` fields in the `package.json`
- New maintainer [seald](https://github.com/seald/) and new package
name [@seald-io/binary-search-tree](https://www.npmjs.com/package/@seald-io/binary-search-tree)
;
- Added `lockfileVersion: 2` `package-lock.json`;
- Modernized some of the code with ES6 features (`class`, `const` & `let`);
- Uses [`standard`](https://standardjs.com/) to lint the code (which removes all
unnecessary semicolons);
- Updated dependencies;
### Removed
- Compatibility with old browsers and old version of Node.js that don't support
ES6 features.
### Security
- This version no longer
uses [a vulnerable version of `underscore`](https://github.com/advisories/GHSA-cf4h-3jhx-xvhq)
.
## [0.2.6] - 2016-02-28
See [original repo](https://github.com/louischatriot/node-binary-search-tree)
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2013 Louis Chatriot &lt;louis.chatriot@gmail.com&gt;
Copyright (c) 2021 Seald [[email protected]](mailto:[email protected]);
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including without
limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+130
View File
@@ -0,0 +1,130 @@
# Binary search trees for Node.js
This module is a fork
of [node-binary-search-tree](https://github.com/louischatriot/node-binary-search-tree)
written by Louis Chatriot for storing indexes
in [nedb](https://github.com/louischatriot/nedb).
Since the original maintainer doesn't support these packages anymore, we forked
them (here is [nedb](https://github.com/seald/nedb)) and maintain them for the
needs of [Seald](https://www.seald.io).
Two implementations of binary search
tree: [basic](http://en.wikipedia.org/wiki/Binary_search_tree)
and [AVL](http://en.wikipedia.org/wiki/AVL_tree) (a kind of self-balancing
binmary search tree).
## Installation and tests
Package name is `@seald-io/binary-search-tree`.
```bash
npm install @seald-io/binary-search-tree
```
If you want to run the tests, you'll have to clone the repository:
```bash
git clone https://github.com/seald/node-binary-search-tree
npm install
npm test
```
## Usage
The API mainly provides 3 functions: `insert`, `search` and `delete`. If you do
not create a unique-type binary search tree, you can store multiple pieces of
data for the same key. Doing so with a unique-type BST will result in an error
being thrown. Data is always returned as an array, and you can delete all data
relating to a given key, or just one piece of data.
Values inserted can be anything except `undefined`.
```javascript
const BinarySearchTree = require('binary-search-tree').BinarySearchTree
const AVLTree = require('binary-search-tree').AVLTree // Same API as BinarySearchTree
// Creating a binary search tree
const bst = new BinarySearchTree()
// Inserting some data
bst.insert(15, 'some data for key 15')
bst.insert(12, 'something else')
bst.insert(18, 'hello')
// You can insert multiple pieces of data for the same key
// if your tree doesn't enforce a unique constraint
bst.insert(18, 'world')
// Retrieving data (always returned as an array of all data stored for this key)
bst.search(15) // Equal to ['some data for key 15']
bst.search(18) // Equal to ['hello', 'world']
bst.search(1) // Equal to []
// Search between bounds with a MongoDB-like query
// Data is returned in key order
// Note the difference between $lt (less than) and $gte (less than OR EQUAL)
bst.betweenBounds({ $lt: 18, $gte: 12 }) // Equal to ['something else', 'some data for key 15']
// Deleting all the data relating to a key
bst.delete(15) // bst.search(15) will now give []
bst.delete(18, 'world') // bst.search(18) will now give ['hello']
```
There are three optional parameters you can pass the BST constructor, allowing
you to enforce a key-uniqueness constraint, use a custom function to compare
keys and use a custom function to check whether values are equal. These
parameters are all passed in an object.
### Uniqueness
```javascript
const bst = new BinarySearchTree({ unique: true });
bst.insert(10, 'hello');
bst.insert(10, 'world'); // Will throw an error
```
### Custom key comparison
```javascript
// Custom key comparison function
// It needs to return a negative number if a is less than b,
// a positive number if a is greater than b
// and 0 if they are equal
// If none is provided, the default one can compare numbers, dates and strings
// which are the most common usecases
const compareKeys = (a, b) => {
if (a.age < b.age) return -1
if (a.age > b.age) return 1
return 0
}
// Now we can use objects with an 'age' property as keys
const bst = new BinarySearchTree({ compareKeys })
bst.insert({ age: 23 }, 'Mark')
bst.insert({ age: 47 }, 'Franck')
```
### Custom value checking
```javascript
// Custom value equality checking function used when we try to just delete one piece of data
// Returns true if a and b are considered the same, false otherwise
// The default function is able to compare numbers and strings
const checkValueEquality = (a, b) => a.length === b.length
var bst = new BinarySearchTree({ checkValueEquality })
bst.insert(10, 'hello')
bst.insert(10, 'world')
bst.insert(10, 'howdoyoudo')
bst.delete(10, 'abcde')
bst.search(10) // Returns ['howdoyoudo']
```
## License
The package is released under the MIT License as the original package.
See LICENSE.md.
+2
View File
@@ -0,0 +1,2 @@
module.exports.BinarySearchTree = require('./lib/bst')
module.exports.AVLTree = require('./lib/avltree')
+412
View File
@@ -0,0 +1,412 @@
/**
* Self-balancing binary search tree using the AVL implementation
*/
const BinarySearchTree = require('./bst')
const customUtils = require('./customUtils')
class AVLTree {
/**
* Constructor
* We can't use a direct pointer to the root node (as in the simple binary search tree)
* as the root will change during tree rotations
* @param {Boolean} options.unique Whether to enforce a 'unique' constraint on the key or not
* @param {Function} options.compareKeys Initialize this BST's compareKeys
*/
constructor (options) {
this.tree = new _AVLTree(options)
}
checkIsAVLT () { this.tree.checkIsAVLT() }
// Insert in the internal tree, update the pointer to the root if needed
insert (key, value) {
const newTree = this.tree.insert(key, value)
// If newTree is undefined, that means its structure was not modified
if (newTree) { this.tree = newTree }
}
// Delete a value
delete (key, value) {
const newTree = this.tree.delete(key, value)
// If newTree is undefined, that means its structure was not modified
if (newTree) { this.tree = newTree }
}
}
class _AVLTree extends BinarySearchTree {
/**
* Constructor of the internal AVLTree
* @param {Object} options Optional
* @param {Boolean} options.unique Whether to enforce a 'unique' constraint on the key or not
* @param {Key} options.key Initialize this BST's key with key
* @param {Value} options.value Initialize this BST's data with [value]
* @param {Function} options.compareKeys Initialize this BST's compareKeys
*/
constructor (options) {
super()
options = options || {}
this.left = null
this.right = null
this.parent = options.parent !== undefined ? options.parent : null
if (Object.prototype.hasOwnProperty.call(options, 'key')) this.key = options.key
this.data = Object.prototype.hasOwnProperty.call(options, 'value') ? [options.value] : []
this.unique = options.unique || false
this.compareKeys = options.compareKeys || customUtils.defaultCompareKeysFunction
this.checkValueEquality = options.checkValueEquality || customUtils.defaultCheckValueEquality
}
/**
* Check the recorded height is correct for every node
* Throws if one height doesn't match
*/
checkHeightCorrect () {
if (!Object.prototype.hasOwnProperty.call(this, 'key')) { return } // Empty tree
if (this.left && this.left.height === undefined) { throw new Error('Undefined height for node ' + this.left.key) }
if (this.right && this.right.height === undefined) { throw new Error('Undefined height for node ' + this.right.key) }
if (this.height === undefined) { throw new Error('Undefined height for node ' + this.key) }
const leftH = this.left ? this.left.height : 0
const rightH = this.right ? this.right.height : 0
if (this.height !== 1 + Math.max(leftH, rightH)) { throw new Error('Height constraint failed for node ' + this.key) }
if (this.left) { this.left.checkHeightCorrect() }
if (this.right) { this.right.checkHeightCorrect() }
}
/**
* Return the balance factor
*/
balanceFactor () {
const leftH = this.left ? this.left.height : 0
const rightH = this.right ? this.right.height : 0
return leftH - rightH
}
/**
* Check that the balance factors are all between -1 and 1
*/
checkBalanceFactors () {
if (Math.abs(this.balanceFactor()) > 1) { throw new Error('Tree is unbalanced at node ' + this.key) }
if (this.left) { this.left.checkBalanceFactors() }
if (this.right) { this.right.checkBalanceFactors() }
}
/**
* When checking if the BST conditions are met, also check that the heights are correct
* and the tree is balanced
*/
checkIsAVLT () {
super.checkIsBST()
this.checkHeightCorrect()
this.checkBalanceFactors()
}
/**
* Perform a right rotation of the tree if possible
* and return the root of the resulting tree
* The resulting tree's nodes' heights are also updated
*/
rightRotation () {
const q = this
const p = this.left
if (!p) return q // No change
const b = p.right
// Alter tree structure
if (q.parent) {
p.parent = q.parent
if (q.parent.left === q) q.parent.left = p
else q.parent.right = p
} else {
p.parent = null
}
p.right = q
q.parent = p
q.left = b
if (b) { b.parent = q }
// Update heights
const ah = p.left ? p.left.height : 0
const bh = b ? b.height : 0
const ch = q.right ? q.right.height : 0
q.height = Math.max(bh, ch) + 1
p.height = Math.max(ah, q.height) + 1
return p
}
/**
* Perform a left rotation of the tree if possible
* and return the root of the resulting tree
* The resulting tree's nodes' heights are also updated
*/
leftRotation () {
const p = this
const q = this.right
if (!q) { return this } // No change
const b = q.left
// Alter tree structure
if (p.parent) {
q.parent = p.parent
if (p.parent.left === p) p.parent.left = q
else p.parent.right = q
} else {
q.parent = null
}
q.left = p
p.parent = q
p.right = b
if (b) { b.parent = p }
// Update heights
const ah = p.left ? p.left.height : 0
const bh = b ? b.height : 0
const ch = q.right ? q.right.height : 0
p.height = Math.max(ah, bh) + 1
q.height = Math.max(ch, p.height) + 1
return q
}
/**
* Modify the tree if its right subtree is too small compared to the left
* Return the new root if any
*/
rightTooSmall () {
if (this.balanceFactor() <= 1) return this // Right is not too small, don't change
if (this.left.balanceFactor() < 0) this.left.leftRotation()
return this.rightRotation()
}
/**
* Modify the tree if its left subtree is too small compared to the right
* Return the new root if any
*/
leftTooSmall () {
if (this.balanceFactor() >= -1) { return this } // Left is not too small, don't change
if (this.right.balanceFactor() > 0) this.right.rightRotation()
return this.leftRotation()
}
/**
* Rebalance the tree along the given path. The path is given reversed (as he was calculated
* in the insert and delete functions).
* Returns the new root of the tree
* Of course, the first element of the path must be the root of the tree
*/
rebalanceAlongPath (path) {
let newRoot = this
let rotated
let i
if (!Object.prototype.hasOwnProperty.call(this, 'key')) {
delete this.height
return this
} // Empty tree
// Rebalance the tree and update all heights
for (i = path.length - 1; i >= 0; i -= 1) {
path[i].height = 1 + Math.max(path[i].left ? path[i].left.height : 0, path[i].right ? path[i].right.height : 0)
if (path[i].balanceFactor() > 1) {
rotated = path[i].rightTooSmall()
if (i === 0) newRoot = rotated
}
if (path[i].balanceFactor() < -1) {
rotated = path[i].leftTooSmall()
if (i === 0) newRoot = rotated
}
}
return newRoot
}
/**
* Insert a key, value pair in the tree while maintaining the AVL tree height constraint
* Return a pointer to the root node, which may have changed
*/
insert (key, value) {
const insertPath = []
let currentNode = this
// Empty tree, insert as root
if (!Object.prototype.hasOwnProperty.call(this, 'key')) {
this.key = key
this.data.push(value)
this.height = 1
return this
}
// Insert new leaf at the right place
while (true) {
// Same key: no change in the tree structure
if (currentNode.compareKeys(currentNode.key, key) === 0) {
if (currentNode.unique) {
const err = new Error(`Can't insert key ${JSON.stringify(key)}, it violates the unique constraint`)
err.key = key
err.errorType = 'uniqueViolated'
throw err
} else currentNode.data.push(value)
return this
}
insertPath.push(currentNode)
if (currentNode.compareKeys(key, currentNode.key) < 0) {
if (!currentNode.left) {
insertPath.push(currentNode.createLeftChild({ key: key, value: value }))
break
} else currentNode = currentNode.left
} else {
if (!currentNode.right) {
insertPath.push(currentNode.createRightChild({ key: key, value: value }))
break
} else currentNode = currentNode.right
}
}
return this.rebalanceAlongPath(insertPath)
}
/**
* Delete a key or just a value and return the new root of the tree
* @param {Key} key
* @param {Value} value Optional. If not set, the whole key is deleted. If set, only this value is deleted
*/
delete (key, value) {
const newData = []
let replaceWith
let currentNode = this
const deletePath = []
if (!Object.prototype.hasOwnProperty.call(this, 'key')) return this // Empty tree
// Either no match is found and the function will return from within the loop
// Or a match is found and deletePath will contain the path from the root to the node to delete after the loop
while (true) {
if (currentNode.compareKeys(key, currentNode.key) === 0) { break }
deletePath.push(currentNode)
if (currentNode.compareKeys(key, currentNode.key) < 0) {
if (currentNode.left) {
currentNode = currentNode.left
} else return this // Key not found, no modification
} else {
// currentNode.compareKeys(key, currentNode.key) is > 0
if (currentNode.right) {
currentNode = currentNode.right
} else return this // Key not found, no modification
}
}
// Delete only a value (no tree modification)
if (currentNode.data.length > 1 && value !== undefined) {
currentNode.data.forEach(function (d) {
if (!currentNode.checkValueEquality(d, value)) newData.push(d)
})
currentNode.data = newData
return this
}
// Delete a whole node
// Leaf
if (!currentNode.left && !currentNode.right) {
if (currentNode === this) { // This leaf is also the root
delete currentNode.key
currentNode.data = []
delete currentNode.height
return this
} else {
if (currentNode.parent.left === currentNode) currentNode.parent.left = null
else currentNode.parent.right = null
return this.rebalanceAlongPath(deletePath)
}
}
// Node with only one child
if (!currentNode.left || !currentNode.right) {
replaceWith = currentNode.left ? currentNode.left : currentNode.right
if (currentNode === this) { // This node is also the root
replaceWith.parent = null
return replaceWith // height of replaceWith is necessarily 1 because the tree was balanced before deletion
} else {
if (currentNode.parent.left === currentNode) {
currentNode.parent.left = replaceWith
replaceWith.parent = currentNode.parent
} else {
currentNode.parent.right = replaceWith
replaceWith.parent = currentNode.parent
}
return this.rebalanceAlongPath(deletePath)
}
}
// Node with two children
// Use the in-order predecessor (no need to randomize since we actively rebalance)
deletePath.push(currentNode)
replaceWith = currentNode.left
// Special case: the in-order predecessor is right below the node to delete
if (!replaceWith.right) {
currentNode.key = replaceWith.key
currentNode.data = replaceWith.data
currentNode.left = replaceWith.left
if (replaceWith.left) { replaceWith.left.parent = currentNode }
return this.rebalanceAlongPath(deletePath)
}
// After this loop, replaceWith is the right-most leaf in the left subtree
// and deletePath the path from the root (inclusive) to replaceWith (exclusive)
while (true) {
if (replaceWith.right) {
deletePath.push(replaceWith)
replaceWith = replaceWith.right
} else break
}
currentNode.key = replaceWith.key
currentNode.data = replaceWith.data
replaceWith.parent.right = replaceWith.left
if (replaceWith.left) replaceWith.left.parent = replaceWith.parent
return this.rebalanceAlongPath(deletePath)
}
}
/**
* Keep a pointer to the internal tree constructor for testing purposes
*/
AVLTree._AVLTree = _AVLTree;
/**
* Other functions we want to use on an AVLTree as if it were the internal _AVLTree
*/
['getNumberOfKeys', 'search', 'betweenBounds', 'prettyPrint', 'executeOnEveryNode'].forEach(function (fn) {
AVLTree.prototype[fn] = function () {
return this.tree[fn].apply(this.tree, arguments)
}
})
// Interface
module.exports = AVLTree
+452
View File
@@ -0,0 +1,452 @@
/**
* Simple binary search tree
*/
const customUtils = require('./customUtils')
class BinarySearchTree {
/**
* Constructor
* @param {Object} options Optional
* @param {Boolean} options.unique Whether to enforce a 'unique' constraint on the key or not
* @param {Key} options.key Initialize this BST's key with key
* @param {Value} options.value Initialize this BST's data with [value]
* @param {Function} options.compareKeys Initialize this BST's compareKeys
*/
constructor (options) {
options = options || {}
this.left = null
this.right = null
this.parent = options.parent !== undefined ? options.parent : null
if (Object.prototype.hasOwnProperty.call(options, 'key')) { this.key = options.key }
this.data = Object.prototype.hasOwnProperty.call(options, 'value') ? [options.value] : []
this.unique = options.unique || false
this.compareKeys = options.compareKeys || customUtils.defaultCompareKeysFunction
this.checkValueEquality = options.checkValueEquality || customUtils.defaultCheckValueEquality
}
/**
* Get the descendant with max key
*/
getMaxKeyDescendant () {
if (this.right) return this.right.getMaxKeyDescendant()
else return this
}
/**
* Get the maximum key
*/
getMaxKey () {
return this.getMaxKeyDescendant().key
}
/**
* Get the descendant with min key
*/
getMinKeyDescendant () {
if (this.left) return this.left.getMinKeyDescendant()
else return this
}
/**
* Get the minimum key
*/
getMinKey () {
return this.getMinKeyDescendant().key
}
/**
* Check that all nodes (incl. leaves) fullfil condition given by fn
* test is a function passed every (key, data) and which throws if the condition is not met
*/
checkAllNodesFullfillCondition (test) {
if (!Object.prototype.hasOwnProperty.call(this, 'key')) return
test(this.key, this.data)
if (this.left) this.left.checkAllNodesFullfillCondition(test)
if (this.right) this.right.checkAllNodesFullfillCondition(test)
}
/**
* Check that the core BST properties on node ordering are verified
* Throw if they aren't
*/
checkNodeOrdering () {
if (!Object.prototype.hasOwnProperty.call(this, 'key')) return
if (this.left) {
this.left.checkAllNodesFullfillCondition(k => {
if (this.compareKeys(k, this.key) >= 0) throw new Error(`Tree with root ${this.key} is not a binary search tree`)
})
this.left.checkNodeOrdering()
}
if (this.right) {
this.right.checkAllNodesFullfillCondition(k => {
if (this.compareKeys(k, this.key) <= 0) throw new Error(`Tree with root ${this.key} is not a binary search tree`)
})
this.right.checkNodeOrdering()
}
}
/**
* Check that all pointers are coherent in this tree
*/
checkInternalPointers () {
if (this.left) {
if (this.left.parent !== this) throw new Error(`Parent pointer broken for key ${this.key}`)
this.left.checkInternalPointers()
}
if (this.right) {
if (this.right.parent !== this) throw new Error(`Parent pointer broken for key ${this.key}`)
this.right.checkInternalPointers()
}
}
/**
* Check that a tree is a BST as defined here (node ordering and pointer references)
*/
checkIsBST () {
this.checkNodeOrdering()
this.checkInternalPointers()
if (this.parent) throw new Error("The root shouldn't have a parent")
}
/**
* Get number of keys inserted
*/
getNumberOfKeys () {
let res
if (!Object.prototype.hasOwnProperty.call(this, 'key')) return 0
res = 1
if (this.left) res += this.left.getNumberOfKeys()
if (this.right) res += this.right.getNumberOfKeys()
return res
}
/**
* Create a BST similar (i.e. same options except for key and value) to the current one
* Use the same constructor (i.e. BinarySearchTree, AVLTree etc)
* @param {Object} options see constructor
*/
createSimilar (options) {
options = options || {}
options.unique = this.unique
options.compareKeys = this.compareKeys
options.checkValueEquality = this.checkValueEquality
return new this.constructor(options)
}
/**
* Create the left child of this BST and return it
*/
createLeftChild (options) {
const leftChild = this.createSimilar(options)
leftChild.parent = this
this.left = leftChild
return leftChild
}
/**
* Create the right child of this BST and return it
*/
createRightChild (options) {
const rightChild = this.createSimilar(options)
rightChild.parent = this
this.right = rightChild
return rightChild
}
/**
* Insert a new element
*/
insert (key, value) {
// Empty tree, insert as root
if (!Object.prototype.hasOwnProperty.call(this, 'key')) {
this.key = key
this.data.push(value)
return
}
// Same key as root
if (this.compareKeys(this.key, key) === 0) {
if (this.unique) {
const err = new Error(`Can't insert key ${JSON.stringify(key)}, it violates the unique constraint`)
err.key = key
err.errorType = 'uniqueViolated'
throw err
} else this.data.push(value)
return
}
if (this.compareKeys(key, this.key) < 0) {
// Insert in left subtree
if (this.left) this.left.insert(key, value)
else this.createLeftChild({ key: key, value: value })
} else {
// Insert in right subtree
if (this.right) this.right.insert(key, value)
else this.createRightChild({ key: key, value: value })
}
}
/**
* Search for all data corresponding to a key
*/
search (key) {
if (!Object.prototype.hasOwnProperty.call(this, 'key')) return []
if (this.compareKeys(this.key, key) === 0) return this.data
if (this.compareKeys(key, this.key) < 0) {
if (this.left) return this.left.search(key)
else return []
} else {
if (this.right) return this.right.search(key)
else return []
}
}
/**
* Return a function that tells whether a given key matches a lower bound
*/
getLowerBoundMatcher (query) {
// No lower bound
if (!Object.prototype.hasOwnProperty.call(query, '$gt') && !Object.prototype.hasOwnProperty.call(query, '$gte')) return () => true
if (Object.prototype.hasOwnProperty.call(query, '$gt') && Object.prototype.hasOwnProperty.call(query, '$gte')) {
if (this.compareKeys(query.$gte, query.$gt) === 0) return key => this.compareKeys(key, query.$gt) > 0
if (this.compareKeys(query.$gte, query.$gt) > 0) return key => this.compareKeys(key, query.$gte) >= 0
else return key => this.compareKeys(key, query.$gt) > 0
}
if (Object.prototype.hasOwnProperty.call(query, '$gt')) return key => this.compareKeys(key, query.$gt) > 0
else return key => this.compareKeys(key, query.$gte) >= 0
}
/**
* Return a function that tells whether a given key matches an upper bound
*/
getUpperBoundMatcher (query) {
// No lower bound
if (!Object.prototype.hasOwnProperty.call(query, '$lt') && !Object.prototype.hasOwnProperty.call(query, '$lte')) return () => true
if (Object.prototype.hasOwnProperty.call(query, '$lt') && Object.prototype.hasOwnProperty.call(query, '$lte')) {
if (this.compareKeys(query.$lte, query.$lt) === 0) return key => this.compareKeys(key, query.$lt) < 0
if (this.compareKeys(query.$lte, query.$lt) < 0) return key => this.compareKeys(key, query.$lte) <= 0
else return key => this.compareKeys(key, query.$lt) < 0
}
if (Object.prototype.hasOwnProperty.call(query, '$lt')) return key => this.compareKeys(key, query.$lt) < 0
else return key => this.compareKeys(key, query.$lte) <= 0
}
/**
* Get all data for a key between bounds
* Return it in key order
* @param {Object} query Mongo-style query where keys are $lt, $lte, $gt or $gte (other keys are not considered)
* @param {Functions} lbm/ubm matching functions calculated at the first recursive step
*/
betweenBounds (query, lbm, ubm) {
const res = []
if (!Object.prototype.hasOwnProperty.call(this, 'key')) return [] // Empty tree
lbm = lbm || this.getLowerBoundMatcher(query)
ubm = ubm || this.getUpperBoundMatcher(query)
if (lbm(this.key) && this.left) append(res, this.left.betweenBounds(query, lbm, ubm))
if (lbm(this.key) && ubm(this.key)) append(res, this.data)
if (ubm(this.key) && this.right) append(res, this.right.betweenBounds(query, lbm, ubm))
return res
}
/**
* Delete the current node if it is a leaf
* Return true if it was deleted
*/
deleteIfLeaf () {
if (this.left || this.right) return false
// The leaf is itself a root
if (!this.parent) {
delete this.key
this.data = []
return true
}
if (this.parent.left === this) this.parent.left = null
else this.parent.right = null
return true
}
/**
* Delete the current node if it has only one child
* Return true if it was deleted
*/
deleteIfOnlyOneChild () {
let child
if (this.left && !this.right) child = this.left
if (!this.left && this.right) child = this.right
if (!child) return false
// Root
if (!this.parent) {
this.key = child.key
this.data = child.data
this.left = null
if (child.left) {
this.left = child.left
child.left.parent = this
}
this.right = null
if (child.right) {
this.right = child.right
child.right.parent = this
}
return true
}
if (this.parent.left === this) {
this.parent.left = child
child.parent = this.parent
} else {
this.parent.right = child
child.parent = this.parent
}
return true
}
/**
* Delete a key or just a value
* @param {Key} key
* @param {Value} value Optional. If not set, the whole key is deleted. If set, only this value is deleted
*/
delete (key, value) {
const newData = []
let replaceWith
if (!Object.prototype.hasOwnProperty.call(this, 'key')) return
if (this.compareKeys(key, this.key) < 0) {
if (this.left) this.left.delete(key, value)
return
}
if (this.compareKeys(key, this.key) > 0) {
if (this.right) this.right.delete(key, value)
return
}
if (!this.compareKeys(key, this.key) === 0) return
// Delete only a value
if (this.data.length > 1 && value !== undefined) {
this.data.forEach(d => {
if (!this.checkValueEquality(d, value)) newData.push(d)
})
this.data = newData
return
}
// Delete the whole node
if (this.deleteIfLeaf()) return
if (this.deleteIfOnlyOneChild()) return
// We are in the case where the node to delete has two children
if (Math.random() >= 0.5) { // Randomize replacement to avoid unbalancing the tree too much
// Use the in-order predecessor
replaceWith = this.left.getMaxKeyDescendant()
this.key = replaceWith.key
this.data = replaceWith.data
if (this === replaceWith.parent) { // Special case
this.left = replaceWith.left
if (replaceWith.left) replaceWith.left.parent = replaceWith.parent
} else {
replaceWith.parent.right = replaceWith.left
if (replaceWith.left) replaceWith.left.parent = replaceWith.parent
}
} else {
// Use the in-order successor
replaceWith = this.right.getMinKeyDescendant()
this.key = replaceWith.key
this.data = replaceWith.data
if (this === replaceWith.parent) { // Special case
this.right = replaceWith.right
if (replaceWith.right) replaceWith.right.parent = replaceWith.parent
} else {
replaceWith.parent.left = replaceWith.right
if (replaceWith.right) replaceWith.right.parent = replaceWith.parent
}
}
}
/**
* Execute a function on every node of the tree, in key order
* @param {Function} fn Signature: node. Most useful will probably be node.key and node.data
*/
executeOnEveryNode (fn) {
if (this.left) this.left.executeOnEveryNode(fn)
fn(this)
if (this.right) this.right.executeOnEveryNode(fn)
}
/**
* Pretty print a tree
* @param {Boolean} printData To print the nodes' data along with the key
*/
prettyPrint (printData, spacing) {
spacing = spacing || ''
console.log(`${spacing}* ${this.key}`)
if (printData) console.log(`${spacing}* ${this.data}`)
if (!this.left && !this.right) return
if (this.left) this.left.prettyPrint(printData, `${spacing} `)
else console.log(`${spacing} *`)
if (this.right) this.right.prettyPrint(printData, `${spacing} `)
else console.log(`${spacing} *`)
}
}
// ================================
// Methods used to test the tree
// ================================
// ============================================
// Methods used to actually work on the tree
// ============================================
// Append all elements in toAppend to array
function append (array, toAppend) {
for (let i = 0; i < toAppend.length; i += 1) {
array.push(toAppend[i])
}
}
// Interface
module.exports = BinarySearchTree
+38
View File
@@ -0,0 +1,38 @@
/**
* Return an array with the numbers from 0 to n-1, in a random order
*/
const getRandomArray = n => {
if (n === 0) return []
if (n === 1) return [0]
const res = getRandomArray(n - 1)
const next = Math.floor(Math.random() * n)
res.splice(next, 0, n - 1) // Add n-1 at a random position in the array
return res
}
module.exports.getRandomArray = getRandomArray
/*
* Default compareKeys function will work for numbers, strings and dates
*/
const defaultCompareKeysFunction = (a, b) => {
if (a < b) return -1
if (a > b) return 1
if (a === b) return 0
const err = new Error("Couldn't compare elements")
err.a = a
err.b = b
throw err
}
module.exports.defaultCompareKeysFunction = defaultCompareKeysFunction
/**
* Check whether two values are equal (used in non-unique deletion)
*/
const defaultCheckValueEquality = (a, b) => a === b
module.exports.defaultCheckValueEquality = defaultCheckValueEquality
+51
View File
@@ -0,0 +1,51 @@
{
"name": "@seald-io/binary-search-tree",
"version": "1.0.3",
"author": {
"name": "Timothée Rebours",
"email": "[email protected]",
"url": "https://www.seald.io/"
},
"files": [
"lib/**/*.js",
"index.js"
],
"contributors": [
{
"name": "Louis Chatriot",
"email": "[email protected]"
},
{
"name": "Timothée Rebours",
"email": "[email protected]",
"url": "https://www.seald.io/"
}
],
"description": "Different binary search tree implementations, including a self-balancing one (AVL)",
"keywords": [
"AVL tree",
"binary search tree",
"self-balancing",
"AVL tree"
],
"homepage": "https://github.com/seald/node-binary-search-tree",
"repository": {
"type": "git",
"url": "[email protected]:seald/node-binary-search-tree.git"
},
"devDependencies": {
"chai": "^4.3.4",
"mocha": "^8.4.0",
"semver": "^7.3.5",
"standard": "^16.0.3"
},
"scripts": {
"test": "mocha --reporter spec --timeout 10000",
"lint": "standard"
},
"main": "index.js",
"licence": "MIT",
"publishConfig": {
"access": "public"
}
}
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2013 Louis Chatriot &lt;louis.chatriot@gmail.com&gt;
Copyright (c) 2021 Seald [[email protected]](mailto:[email protected]);
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including without
limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+905
View File
@@ -0,0 +1,905 @@
<img src="http://i.imgur.com/9O1xHFb.png" style="width: 25%; height: 25%; float: left;">
## The JavaScript Database
This module is a fork of [nedb](https://github.com/louischatriot/nedb)
written by Louis Chatriot.
Since the original maintainer doesn't support this package anymore, we forked it
and maintain it for the needs of [Seald](https://www.seald.io).
**Embedded persistent or in memory database for Node.js, Electron and browsers,
100% JavaScript, no binary dependency**. API is a subset of MongoDB's and it's
[plenty fast](#speed).
## Installation
Module name on npm is [`@seald-io/nedb`](https://www.npmjs.com/package/@seald-io/nedb).
```
npm install @seald-io/nedb
```
Then to import, you just have to:
```js
const Datastore = require('@seald-io/nedb')
```
## Documentation
The API is a subset of MongoDB's API (the most used operations).
Since version [3.0.0](./CHANGELOG.md#300---2022-03-16), NeDB provides a Promise-based equivalent for each function
which is suffixed with `Async`, for example `loadDatabaseAsync`.
The original callback-based interface is still available, fully retro-compatible
(as far as the test suites can tell) and are a shim to this Promise-based
version.
Don't hesitate to open an issue if it breaks something in your project.
The rest of the readme will only show the Promise-based API, the full
documentation is available in the [`API.md`](./API.md) file at the root of the
repository. It is generated by running `npm run generateDocs:markdown`.
* [Creating/loading a database](#creatingloading-a-database)
* [Dropping a database](#dropping-a-database)
* [Persistence](#persistence)
* [Inserting documents](#inserting-documents)
* [Finding documents](#finding-documents)
* [Basic Querying](#basic-querying)
* [Operators ($lt, $lte, $gt, $gte, $in, $nin, $ne, $exists, $regex)](#operators-lt-lte-gt-gte-in-nin-ne-stat-regex)
* [Array fields](#array-fields)
* [Logical operators $or, $and, $not, $where](#logical-operators-or-and-not-where)
* [Sorting and paginating](#sorting-and-paginating)
* [Projections](#projections)
* [Counting documents](#counting-documents)
* [Updating documents](#updating-documents)
* [Removing documents](#removing-documents)
* [Indexing](#indexing)
* [Other environments](#other-environments)
### Creating/loading a database
You can use NeDB as an in-memory only datastore or as a persistent datastore.
One datastore is the equivalent of a MongoDB collection. The constructor is used
as follows [`new Datastore(options)` where `options` is an object](./API.md#new_Datastore_new).
If the Datastore is persistent (if you give it [`options.filename`](./API.md#Datastore+filename),
you'll need to load the database using [Datastore#loadDatabaseAsync](./API.md#Datastore+loadDatabaseAsync),
or using [`options.autoload`](./API.md#Datastore+autoload).
```javascript
// Type 1: In-memory only datastore (no need to load the database)
const Datastore = require('@seald-io/nedb')
const db = new Datastore()
// Type 2: Persistent datastore with manual loading
const Datastore = require('@seald-io/nedb')
const db = new Datastore({ filename: 'path/to/datafile' })
try {
await db.loadDatabaseAsync()
} catch (error) {
// loading has failed
}
// loading has succeeded
// Type 3: Persistent datastore with automatic loading
const Datastore = require('@seald-io/nedb')
const db = new Datastore({ filename: 'path/to/datafile', autoload: true }) // You can await db.autoloadPromise to catch a potential error when autoloading.
// You can issue commands right away
// Of course you can create multiple datastores if you need several
// collections. In this case it's usually a good idea to use autoload for all collections.
db = {}
db.users = new Datastore('path/to/users.db')
db.robots = new Datastore('path/to/robots.db')
// You need to load each database
await db.users.loadDatabaseAsync()
await db.robots.loadDatabaseAsync()
```
### Dropping a database
Since v3.0.0, you can drop the database by using [`Datastore#dropDatabaseAsync`](./API.md#Datastore+dropDatabaseAsync):
```js
const Datastore = require('@seald-io/nedb')
const db = new Datastore()
await d.insertAsync({ hello: 'world' })
await d.dropDatabaseAsync()
assert.equal(d.getAllData().length, 0)
assert.equal(await exists(testDb), false)
```
It is not recommended to keep using an instance of Datastore when its database
has been dropped as it may have some unintended side effects.
### Persistence
Under the hood, NeDB's [persistence](./API.md#Persistence) uses an append-only
format, meaning that all updates and deletes actually result in lines added at
the end of the datafile, for performance reasons. The database is automatically
compacted (i.e. put back in the one-line-per-document format) every time you
load each database within your application.
**Breaking change**: [since v3.0.0](./CHANGELOG.md#300---unreleased), calling methods of `yourDatabase.persistence`
is deprecated. The same functions exists directly on the `Datastore`.
You can manually call the compaction function
with [`yourDatabase#compactDatafileAsync`](./API.md#Datastore+compactDatafileAsync).
You can also set automatic compaction at regular intervals
with [`yourDatabase#setAutocompactionInterval`](./API.md#Datastore+setAutocompactionInterval),
and stop automatic compaction with [`yourDatabase#stopAutocompaction`](./API.md#Datastore+stopAutocompaction).
### Inserting documents
The native types are `String`, `Number`, `Boolean`, `Date` and `null`. You can
also use arrays and subdocuments (objects). If a field is `undefined`, it will
not be saved (this is different from MongoDB which transforms `undefined`
in `null`, something I find counter-intuitive).
If the document does not contain an `_id` field, NeDB will automatically
generate one for you (a 16-characters alphanumerical string). The `_id` of a
document, once set, cannot be modified.
Field names cannot start with '$' or contain the characters '.' and ','.
```javascript
const doc = {
hello: 'world',
n: 5,
today: new Date(),
nedbIsAwesome: true,
notthere: null,
notToBeSaved: undefined, // Will not be saved
fruits: ['apple', 'orange', 'pear'],
infos: { name: '@seald-io/nedb' }
}
try {
const newDoc = await db.insertAsync(doc)
// newDoc is the newly inserted document, including its _id
// newDoc has no key called notToBeSaved since its value was undefined
} catch (error) {
// if an error happens
}
```
You can also bulk-insert an array of documents. This operation is atomic,
meaning that if one insert fails due to a unique constraint being violated, all
changes are rolled back.
```javascript
const newDocs = await db.insertAsync([{ a: 5 }, { a: 42 }])
// Two documents were inserted in the database
// newDocs is an array with these documents, augmented with their _id
// If there is a unique constraint on field 'a', this will fail
try {
await db.insertAsync([{ a: 5 }, { a: 42 }, { a: 5 }])
} catch (error) {
// err is a 'uniqueViolated' error
// The database was not modified
}
```
### Finding documents
Use `findAsync` to look for multiple documents matching you query, or `findOneAsync` to
look for one specific document. You can select documents based on field equality
or use comparison operators (`$lt`, `$lte`, `$gt`, `$gte`, `$in`, `$nin`, `$ne`)
. You can also use logical operators `$or`, `$and`, `$not` and `$where`. See
below for the syntax.
You can use regular expressions in two ways: in basic querying in place of a
string, or with the `$regex` operator.
You can sort and paginate results using the cursor API (see below).
You can use standard projections to restrict the fields to appear in the
results (see below).
#### Basic querying
Basic querying means are looking for documents whose fields match the ones you
specify. You can use regular expression to match strings. You can use the dot
notation to navigate inside nested documents, arrays, arrays of subdocuments and
to match a specific element of an array.
```javascript
// Let's say our datastore contains the following collection
// { _id: 'id1', planet: 'Mars', system: 'solar', inhabited: false, satellites: ['Phobos', 'Deimos'] }
// { _id: 'id2', planet: 'Earth', system: 'solar', inhabited: true, humans: { genders: 2, eyes: true } }
// { _id: 'id3', planet: 'Jupiter', system: 'solar', inhabited: false }
// { _id: 'id4', planet: 'Omicron Persei 8', system: 'futurama', inhabited: true, humans: { genders: 7 } }
// { _id: 'id5', completeData: { planets: [ { name: 'Earth', number: 3 }, { name: 'Mars', number: 2 }, { name: 'Pluton', number: 9 } ] } }
// Finding all planets in the solar system
const docs = await db.findAsync({ system: 'solar' })
// docs is an array containing documents Mars, Earth, Jupiter
// If no document is found, docs is equal to []
// Finding all planets whose name contain the substring 'ar' using a regular expression
const docs = await db.findAsync({ planet: /ar/ })
// docs contains Mars and Earth
// Finding all inhabited planets in the solar system
const docs = await db.findAsync({ system: 'solar', inhabited: true })
// docs is an array containing document Earth only
// Use the dot-notation to match fields in subdocuments
const docs = await db.findAsync({ 'humans.genders': 2 })
// docs contains Earth
// Use the dot-notation to navigate arrays of subdocuments
const docs = await db.findAsync({ 'completeData.planets.name': 'Mars' })
// docs contains document 5
const docs = await db.findAsync({ 'completeData.planets.name': 'Jupiter' })
// docs is empty
const docs = await db.findAsync({ 'completeData.planets.0.name': 'Earth' })
// docs contains document 5
// If we had tested against 'Mars' docs would be empty because we are matching against a specific array element
// You can also deep-compare objects. Don't confuse this with dot-notation!
const docs = await db.findAsync({ humans: { genders: 2 } })
// docs is empty, because { genders: 2 } is not equal to { genders: 2, eyes: true }
// Find all documents in the collection
const docs = await db.findAsync({})
// The same rules apply when you want to only find one document
const doc = await db.findOneAsync({ _id: 'id1' })
// doc is the document Mars
// If no document is found, doc is null
```
#### Operators ($lt, $lte, $gt, $gte, $in, $nin, $ne, $exists, $regex)
The syntax is `{ field: { $op: value } }` where `$op` is any comparison
operator:
* `$lt`, `$lte`: less than, less than or equal
* `$gt`, `$gte`: greater than, greater than or equal
* `$in`: member of. `value` must be an array of values
* `$ne`, `$nin`: not equal, not a member of
* `$exists`: checks whether the document posses the property `field`. `value`
should be true or false
* `$regex`: checks whether a string is matched by the regular expression.
Contrary to MongoDB, the use of `$options` with `$regex` is not supported,
because it doesn't give you more power than regex flags. Basic queries are
more readable so only use the `$regex` operator when you need to use another
operator with it (see example below)
```javascript
// $lt, $lte, $gt and $gte work on numbers and strings
const docs = await db.findAsync({ 'humans.genders': { $gt: 5 } })
// docs contains Omicron Persei 8, whose humans have more than 5 genders (7).
// When used with strings, lexicographical order is used
const docs = await db.findAsync({ planet: { $gt: 'Mercury' } })
// docs contains Omicron Persei 8
// Using $in. $nin is used in the same way
const docs = await db.findAsync({ planet: { $in: ['Earth', 'Jupiter'] } })
// docs contains Earth and Jupiter
// Using $exists
const docs = await db.findAsync({ satellites: { $exists: true } })
// docs contains only Mars
// Using $regex with another operator
const docs = await db.findAsync({
planet: {
$regex: /ar/,
$nin: ['Jupiter', 'Earth']
}
})
// docs only contains Mars because Earth was excluded from the match by $nin
```
#### Array fields
When a field in a document is an array, NeDB first tries to see if the query
value is an array to perform an exact match, then whether there is an
array-specific comparison function (for now there is only `$size`
and `$elemMatch`) being used. If not, the query is treated as a query on every
element and there is a match if at least one element matches.
* `$size`: match on the size of the array
* `$elemMatch`: matches if at least one array element matches the query entirely
```javascript
// Exact match
const docs = await db.findAsync({ satellites: ['Phobos', 'Deimos'] })
// docs contains Mars
const docs = await db.findAsync({ satellites: ['Deimos', 'Phobos'] })
// docs is empty
// Using an array-specific comparison function
// $elemMatch operator will provide match for a document, if an element from the array field satisfies all the conditions specified with the `$elemMatch` operator
const docs = await db.findAsync({
completeData: {
planets: {
$elemMatch: {
name: 'Earth',
number: 3
}
}
}
})
// docs contains documents with id 5 (completeData)
const docs = await db.findAsync({
completeData: {
planets: {
$elemMatch: {
name: 'Earth',
number: 5
}
}
}
})
// docs is empty
// You can use inside #elemMatch query any known document query operator
const docs = await db.findAsync({
completeData: {
planets: {
$elemMatch: {
name: 'Earth',
number: { $gt: 2 }
}
}
}
})
// docs contains documents with id 5 (completeData)
// Note: you can't use nested comparison functions, e.g. { $size: { $lt: 5 } } will throw an error
const docs = await db.findAsync({ satellites: { $size: 2 } })
// docs contains Mars
const docs = await db.findAsync({ satellites: { $size: 1 } })
// docs is empty
// If a document's field is an array, matching it means matching any element of the array
const docs = await db.findAsync({ satellites: 'Phobos' })
// docs contains Mars. Result would have been the same if query had been { satellites: 'Deimos' }
// This also works for queries that use comparison operators
const docs = await db.findAsync({ satellites: { $lt: 'Amos' } })
// docs is empty since Phobos and Deimos are after Amos in lexicographical order
// This also works with the $in and $nin operator
const docs = await db.findAsync({ satellites: { $in: ['Moon', 'Deimos'] } })
// docs contains Mars (the Earth document is not complete!)
```
#### Logical operators $or, $and, $not, $where
You can combine queries using logical operators:
* For `$or` and `$and`, the syntax is `{ $op: [query1, query2, ...] }`.
* For `$not`, the syntax is `{ $not: query }`
* For `$where`, the syntax
is `{ $where: function () { /* object is 'this', return a boolean */ } }`
```javascript
const docs = await db.findAsync({ $or: [{ planet: 'Earth' }, { planet: 'Mars' }] })
// docs contains Earth and Mars
const docs = await db.findAsync({ $not: { planet: 'Earth' } })
// docs contains Mars, Jupiter, Omicron Persei 8
const docs = await db.findAsync({ $where: function () { return Object.keys(this) > 6 } })
// docs with more than 6 properties
// You can mix normal queries, comparison queries and logical operators
const docs = await db.findAsync({
$or: [{ planet: 'Earth' }, { planet: 'Mars' }],
inhabited: true
})
// docs contains Earth
```
#### Sorting and paginating
[`Datastore#findAsync`](./API.md#Datastore+findAsync),
[`Datastore#findOneAsync`](./API.md#Datastore+findOneAsync) and
[`Datastore#countAsync`](./API.md#Datastore+countAsync) don't
actually return a `Promise`, but a [`Cursor`](./API.md#Cursor) which is a
[`Thenable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#thenable_objects)
which calls [`Cursor#execAsync`](./API.md#Cursor+execAsync) when awaited.
This pattern allows to chain [`Cursor#sort`](./API.md#Cursor+sort),
[`Cursor#skip`](./API.md#Cursor+skip),
[`Cursor#limit`](./API.md#Cursor+limit) and
[`Cursor#projection`](./API.md#Cursor+projection) and await the result.
```javascript
// Let's say the database contains these 4 documents
// doc1 = { _id: 'id1', planet: 'Mars', system: 'solar', inhabited: false, satellites: ['Phobos', 'Deimos'] }
// doc2 = { _id: 'id2', planet: 'Earth', system: 'solar', inhabited: true, humans: { genders: 2, eyes: true } }
// doc3 = { _id: 'id3', planet: 'Jupiter', system: 'solar', inhabited: false }
// doc4 = { _id: 'id4', planet: 'Omicron Persei 8', system: 'futurama', inhabited: true, humans: { genders: 7 } }
// No query used means all results are returned (before the Cursor modifiers)
const docs = await db.findAsync({}).sort({ planet: 1 }).skip(1).limit(2)
// docs is [doc3, doc1]
// You can sort in reverse order like this
const docs = await db.findAsync({ system: 'solar' }).sort({ planet: -1 })
// docs is [doc1, doc3, doc2]
// You can sort on one field, then another, and so on like this:
const docs = await db.findAsync({}).sort({ firstField: 1, secondField: -1 })
// ... You understand how this works!
```
#### Projections
You can give `findAsync` and `findOneAsync` an optional second argument, `projections`.
The syntax is the same as MongoDB: `{ a: 1, b: 1 }` to return only the `a`
and `b` fields, `{ a: 0, b: 0 }` to omit these two fields. You cannot use both
modes at the time, except for `_id` which is by default always returned and
which you can choose to omit. You can project on nested documents.
```javascript
// Same database as above
// Keeping only the given fields
const docs = await db.findAsync({ planet: 'Mars' }, { planet: 1, system: 1 })
// docs is [{ planet: 'Mars', system: 'solar', _id: 'id1' }]
// Keeping only the given fields but removing _id
const docs = await db.findAsync({ planet: 'Mars' }, {
planet: 1,
system: 1,
_id: 0
})
// docs is [{ planet: 'Mars', system: 'solar' }]
// Omitting only the given fields and removing _id
const docs = await db.findAsync({ planet: 'Mars' }, {
planet: 0,
system: 0,
_id: 0
})
// docs is [{ inhabited: false, satellites: ['Phobos', 'Deimos'] }]
// Failure: using both modes at the same time
const docs = await db.findAsync({ planet: 'Mars' }, { planet: 0, system: 1 })
// err is the error message, docs is undefined
// You can also use it in a Cursor way but this syntax is not compatible with MongoDB
const docs = await db.findAsync({ planet: 'Mars' }).projection({
planet: 1,
system: 1
})
// docs is [{ planet: 'Mars', system: 'solar', _id: 'id1' }]
// Project on a nested document
const doc = await db.findOneAsync({ planet: 'Earth' }).projection({
planet: 1,
'humans.genders': 1
})
// doc is { planet: 'Earth', _id: 'id2', humans: { genders: 2 } }
```
### Counting documents
You can use `countAsync` to count documents. It has the same syntax as `findAsync`.
For example:
```javascript
// Count all planets in the solar system
const count = await db.countAsync({ system: 'solar' })
// count equals to 3
// Count all documents in the datastore
const count = await db.countAsync({})
// count equals to 4
```
### Updating documents
[`db.updateAsync(query, update, options)`](./API.md#Datastore+updateAsync)
will update all documents matching `query` according to the `update` rules.
`update` specifies how the documents should be modified. It is either a new
document or a set of modifiers (you cannot use both together):
* A new document will replace the matched docs;
* Modifiers create the fields they need to modify if they don't exist,
and you can apply them to subdocs (see [the API reference]((./API.md#Datastore+updateAsync)))
`options` is an object with three possible parameters:
* `multi` which allows the modification of several documents if set to true.
* `upsert` will insert a new document corresponding if it doesn't exist (either
the `update` is a simple object with no modifiers, or the `query` modified by
the modifiers in the `update`) if set to `true`.
* `returnUpdatedDocs` will return the array of documents matched by the find
query and updated (updated documents will be returned even if the update did not
actually modify them) if set to `true`.
It resolves into an Object with the following properties:
- `numAffected`: how many documents were affected by the update;
- `upsert`: if a document was actually upserted (not always the same as `options.upsert`;
- `affectedDocuments`:
- if `upsert` is `true` the document upserted;
- if `options.returnUpdatedDocs` is `true` either the affected document or, if `options.multi` is `true` an Array of the affected documents, else `null`;
**Note**: you can't change a document's _id.
```javascript
// Let's use the same example collection as in the 'finding document' part
// { _id: 'id1', planet: 'Mars', system: 'solar', inhabited: false }
// { _id: 'id2', planet: 'Earth', system: 'solar', inhabited: true }
// { _id: 'id3', planet: 'Jupiter', system: 'solar', inhabited: false }
// { _id: 'id4', planet: 'Omicron Persia 8', system: 'futurama', inhabited: true }
// Replace a document by another
const { numAffected } = await db.updateAsync({ planet: 'Jupiter' }, { planet: 'Pluton' }, {})
// numAffected = 1
// The doc #3 has been replaced by { _id: 'id3', planet: 'Pluton' }
// Note that the _id is kept unchanged, and the document has been replaced
// (the 'system' and inhabited fields are not here anymore)
// Set an existing field's value
const { numAffected } = await db.updateAsync({ system: 'solar' }, { $set: { system: 'solar system' } }, { multi: true })
// numAffected = 3
// Field 'system' on Mars, Earth, Jupiter now has value 'solar system'
// Setting the value of a non-existing field in a subdocument by using the dot-notation
await db.updateAsync({ planet: 'Mars' }, {
$set: {
'data.satellites': 2,
'data.red': true
}
}, {})
// Mars document now is { _id: 'id1', system: 'solar', inhabited: false
// , data: { satellites: 2, red: true }
// }
// Not that to set fields in subdocuments, you HAVE to use dot-notation
// Using object-notation will just replace the top-level field
await db.updateAsync({ planet: 'Mars' }, { $set: { data: { satellites: 3 } } }, {})
// Mars document now is { _id: 'id1', system: 'solar', inhabited: false
// , data: { satellites: 3 }
// }
// You lost the 'data.red' field which is probably not the intended behavior
// Deleting a field
await db.updateAsync({ planet: 'Mars' }, { $unset: { planet: true } }, {})
// Now the document for Mars doesn't contain the planet field
// You can unset nested fields with the dot notation of course
// Upserting a document
const { numAffected, affectedDocuments, upsert } = await db.updateAsync({ planet: 'Pluton' }, {
planet: 'Pluton',
inhabited: false
}, { upsert: true })
// numAffected = 1, affectedDocuments = { _id: 'id5', planet: 'Pluton', inhabited: false }, upsert = true
// A new document { _id: 'id5', planet: 'Pluton', inhabited: false } has been added to the collection
// If you upsert with a modifier, the upserted doc is the query modified by the modifier
// This is simpler than it sounds :)
await db.updateAsync({ planet: 'Pluton' }, { $inc: { distance: 38 } }, { upsert: true })
// A new document { _id: 'id5', planet: 'Pluton', distance: 38 } has been added to the collection
// If we insert a new document { _id: 'id6', fruits: ['apple', 'orange', 'pear'] } in the collection,
// let's see how we can modify the array field atomically
// $push inserts new elements at the end of the array
await db.updateAsync({ _id: 'id6' }, { $push: { fruits: 'banana' } }, {})
// Now the fruits array is ['apple', 'orange', 'pear', 'banana']
// $pop removes an element from the end (if used with 1) or the front (if used with -1) of the array
await db.updateAsync({ _id: 'id6' }, { $pop: { fruits: 1 } }, {})
// Now the fruits array is ['apple', 'orange']
// With { $pop: { fruits: -1 } }, it would have been ['orange', 'pear']
// $addToSet adds an element to an array only if it isn't already in it
// Equality is deep-checked (i.e. $addToSet will not insert an object in an array already containing the same object)
// Note that it doesn't check whether the array contained duplicates before or not
await db.updateAsync({ _id: 'id6' }, { $addToSet: { fruits: 'apple' } }, {})
// The fruits array didn't change
// If we had used a fruit not in the array, e.g. 'banana', it would have been added to the array
// $pull removes all values matching a value or even any NeDB query from the array
await db.updateAsync({ _id: 'id6' }, { $pull: { fruits: 'apple' } }, {})
// Now the fruits array is ['orange', 'pear']
await db.updateAsync({ _id: 'id6' }, { $pull: { fruits: { $in: ['apple', 'pear'] } } }, {})
// Now the fruits array is ['orange']
// $each can be used to $push or $addToSet multiple values at once
// This example works the same way with $addToSet
await db.updateAsync({ _id: 'id6' }, { $push: { fruits: { $each: ['banana', 'orange'] } } }, {})
// Now the fruits array is ['apple', 'orange', 'pear', 'banana', 'orange']
// $slice can be used in cunjunction with $push and $each to limit the size of the resulting array.
// A value of 0 will update the array to an empty array. A positive value n will keep only the n first elements
// A negative value -n will keep only the last n elements.
// If $slice is specified but not $each, $each is set to []
await db.updateAsync({ _id: 'id6' }, {
$push: {
fruits: {
$each: ['banana'],
$slice: 2
}
}
})
// Now the fruits array is ['apple', 'orange']
// $min/$max to update only if provided value is less/greater than current value
// Let's say the database contains this document
// doc = { _id: 'id', name: 'Name', value: 5 }
await db.updateAsync({ _id: 'id1' }, { $min: { value: 2 } }, {})
// The document will be updated to { _id: 'id', name: 'Name', value: 2 }
await db.updateAsync({ _id: 'id1' }, { $min: { value: 8 } }, {})
// The document will not be modified
```
### Removing documents
[`db.removeAsync(query, options)`](./API.md#Datastore#removeAsync)
will remove documents matching `query`. Can remove multiple documents if
`options.multi` is set. Returns the `Promise<numRemoved>`.
```javascript
// Let's use the same example collection as in the "finding document" part
// { _id: 'id1', planet: 'Mars', system: 'solar', inhabited: false }
// { _id: 'id2', planet: 'Earth', system: 'solar', inhabited: true }
// { _id: 'id3', planet: 'Jupiter', system: 'solar', inhabited: false }
// { _id: 'id4', planet: 'Omicron Persia 8', system: 'futurama', inhabited: true }
// Remove one document from the collection
// options set to {} since the default for multi is false
const { numRemoved } = await db.removeAsync({ _id: 'id2' }, {})
// numRemoved = 1
// Remove multiple documents
const { numRemoved } = await db.removeAsync({ system: 'solar' }, { multi: true })
// numRemoved = 3
// All planets from the solar system were removed
// Removing all documents with the 'match-all' query
const { numRemoved } = await db.removeAsync({}, { multi: true })
```
### Indexing
NeDB supports indexing. It gives a very nice speed boost and can be used to
enforce a unique constraint on a field. You can index any field, including
fields in nested documents using the dot notation. For now, indexes are only
used to speed up basic queries and queries using `$in`, `$lt`, `$lte`, `$gt`
and `$gte`. The indexed values cannot be of type array of object.
**Breaking change**: [since v4.0.0](./CHANGELOG.md#400---2023-01-20), commas (`,`) can no longer be used in indexed field names.
The following is illegal:
```javascript
db.ensureIndexAsync({ fieldName: 'some,field' })
db.ensureIndexAsync({ fieldName: ['some,field', 'other,field'] })
```
This is a side effect of the compound index implementation.
To create an index, use [`datastore#ensureIndexAsync(options)`](./API.md#Datastore+ensureIndexAsync).
It resolves when the index is persisted on disk (if the database is persistent)
and may throw an Error (usually a unique constraint that was violated). It can
be called when you want, even after some data was inserted, though it's best to
call it at application startup. The options are:
* **fieldName** (required): name of the field to index. Use the dot notation to
index a field in a nested document. For a compound index, use an array of field names.
* **unique** (optional, defaults to `false`): enforce field uniqueness.
* **sparse** (optional, defaults to `false`): don't index documents for which
the field is not defined.
* **expireAfterSeconds** (number of seconds, optional): if set, the created
index is a TTL (time to live) index, that will automatically remove documents
when the indexed field value is older than `expireAfterSeconds`.
Note: the `_id` is automatically indexed with a unique constraint.
You can remove a previously created index with
[`datastore#removeIndexAsync(fieldName)`](./API.md#Datastore+removeIndexAsync).
```javascript
try {
await db.ensureIndexAsync({ fieldName: 'somefield' })
} catch (error) {
// If there was an error, error is not null
}
// Using a unique constraint with the index
await db.ensureIndexAsync({ fieldName: 'somefield', unique: true })
// Using a sparse unique index
await db.ensureIndexAsync({
fieldName: 'somefield',
unique: true,
sparse: true
})
// Using a compound index
await db.ensureIndexAsync({ fieldName: ["field1", "field2"] });
try {
// Format of the error message when the unique constraint is not met
await db.insertAsync({ somefield: '@seald-io/nedb' })
// works
await db.insertAsync({ somefield: '@seald-io/nedb' })
//rejects
} catch (error) {
// error is { errorType: 'uniqueViolated',
// key: 'name',
// message: 'Unique constraint violated for key name' }
}
// Remove index on field somefield
await db.removeIndexAsync('somefield')
// Example of using expireAfterSeconds to remove documents 1 hour
// after their creation (db's timestampData option is true here)
await db.ensureIndex({
fieldName: 'createdAt',
expireAfterSeconds: 3600
})
// You can also use the option to set an expiration date like so
await db.ensureIndex({
fieldName: 'expirationDate',
expireAfterSeconds: 0
})
// Now all documents will expire when system time reaches the date in their
// expirationDate field
```
## Other environments
NeDB runs on Node.js (it is tested on Node 12, 14 and 16), the browser (it is
tested on the latest version of Chrome) and React-Native using
[@react-native-async-storage/async-storage](https://github.com/react-native-async-storage/async-storage).
### Browser bundle
The npm package contains a bundle and its minified counterpart for the browser.
They are located in the `browser-version/out` directory. You only need to require `nedb.js`
or `nedb.min.js` in your HTML file and the global object `Nedb` can be used
right away, with the same API as the server version:
```
<script src="nedb.min.js"></script>
<script>
var db = new Nedb(); // Create an in-memory only datastore
db.insert({ planet: 'Earth' }, function (err) {
db.find({}, function (err, docs) {
// docs contains the two planets Earth and Mars
});
});
</script>
```
If you specify a `filename`, the database will be persistent, and automatically
select the best storage method available using [localforage](https://github.com/localForage/localForage)
(IndexedDB, WebSQL or localStorage) depending on the browser. In most cases that
means a lot of data can be stored, typically in hundreds of MB.
**WARNING**: the storage system changed between
v1.3 and v1.4 and is NOT back-compatible! Your application needs to resync
client-side when you upgrade NeDB.
NeDB uses modern Javascript features such as `async`, `Promise`, `class`, `const`
, `let`, `Set`, `Map`, ... The bundle does not polyfill these features. If you
need to target another environment, you will need to make your own bundle.
### Using the `browser` and `react-native` fields
NeDB uses the `browser` and `react-native` fields to replace some modules by an
environment specific shim.
The way this works is by counting on the bundler that will package NeDB to use
this fields. This is [done by default by Webpack](https://webpack.js.org/configuration/resolve/#resolvealiasfields)
for the `browser` field. And this is [done by default by Metro](https://github.com/facebook/metro/blob/c21daba415ea26511e157f794689caab9abe8236/packages/metro/src/ModuleGraph/node-haste/Package.js#L108)
for the `react-native` field.
This is done for:
- the [storage module](./lib/storage.js) which uses Node.js `fs`. It is
[replaced in the browser](./browser-version/lib/storage.browser.js) by one that uses
[localforage](https://github.com/localForage/localForage), and
[in `react-native`](./browser-version/lib/storage.react-native.js) by one that uses
[@react-native-async-storage/async-storage](https://github.com/react-native-async-storage/async-storage)
- the [customUtils module](./browser-version/lib/customUtils.js) which uses Node.js
`crypto` module. It is replaced by a good enough shim to generate ids that uses `Math.random()`.
- the [byline module](./browser-version/lib/byline.js) which uses Node.js `stream`
(a fork of [`node-byline`](https://github.com/jahewson/node-byline) included in
the repo because it is unmaintained). It isn't used in the browser nor
react-native versions, therefore it is shimmed with an empty object.
However, the `browser` and `react-native` versions rely on node native modules and therefore must be polyfilled:
- `util` with https://github.com/browserify/node-util.
- `events` with https://github.com/browserify/events.
## Performance
### Speed
NeDB is not intended to be a replacement of large-scale databases such as
MongoDB, and as such was not designed for speed. That said, it is still pretty
fast on the expected datasets, especially if you use indexing. On a typical,
not-so-fast dev machine, for a collection containing 10,000 documents, with
indexing:
* Insert: **10,680 ops/s**
* Find: **43,290 ops/s**
* Update: **8,000 ops/s**
* Remove: **11,750 ops/s**
You can run these simple benchmarks by executing the scripts in the `benchmarks`
folder. Run them with the `--help` flag to see how they work.
### Memory footprint
A copy of the whole database is kept in memory. This is not much on the expected
kind of datasets (20MB for 10,000 2KB documents).
## Use in other services
* An ODM for NeDB: [follicle](https://github.com/seald/follicle)
* A layer to add a promise-only interface: [nedb-promises](https://www.npmjs.com/package/nedb-promises)
## Modernization
This fork of NeDB will be incrementally updated to:
* [ ] cleanup the benchmark and update the performance statistics;
* [ ] remove deprecated features;
* [ ] add a way to change the `Storage` module by dependency injection, which will
pave the way to cleaner browser react-native versions (cf https://github.com/seald/nedb/pull/19).
* [x] use `async` functions and `Promises` instead of callbacks with `[email protected]`;
* [x] expose a `Promise`-based interface;
* [x] remove the `underscore` dependency;
## Pull requests guidelines
If you submit a pull request, thanks! There are a couple rules to follow though
to make it manageable:
* The pull request should be atomic, i.e. contain only one feature. If it
contains more, please submit multiple pull requests. Reviewing massive, 1000
loc+ pull requests is extremely hard.
* Likewise, if for one unique feature the pull request grows too large (more
than 200 loc tests not included), please get in touch first.
* Please stick to the current coding style. It's important that the code uses a
coherent style for readability (this package uses [`standard`](https://standardjs.com/)).
* Do not include stylistic improvements ('housekeeping'). If you think one part
deserves lots of housekeeping, use a separate pull request so as not to
pollute the code.
* Don't forget tests for your new feature. Also don't forget to run the whole
test suite before submitting to make sure you didn't introduce regressions.
* Update the JSDoc and regenerate [the markdown docs](./API.md).
* Update the readme accordingly.
## License
See [License](LICENSE.md)
+1
View File
@@ -0,0 +1 @@
module.exports = {}
@@ -0,0 +1,76 @@
/**
* Utility functions that need to be reimplemented for each environment.
* This is the version for the browser & React-Native
* @module customUtilsBrowser
* @private
*/
/**
* Taken from the crypto-browserify module
* https://github.com/dominictarr/crypto-browserify
* NOTE: Math.random() does not guarantee "cryptographic quality" but we actually don't need it
* @param {number} size in bytes
* @return {Array<number>}
*/
const randomBytes = size => {
const bytes = new Array(size)
for (let i = 0, r; i < size; i++) {
if ((i & 0x03) === 0) r = Math.random() * 0x100000000
bytes[i] = r >>> ((i & 0x03) << 3) & 0xff
}
return bytes
}
/**
* Taken from the base64-js module
* https://github.com/beatgammit/base64-js/
* @param {Array} uint8
* @return {string}
*/
const byteArrayToBase64 = uint8 => {
const lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
const extraBytes = uint8.length % 3 // if we have 1 byte left, pad 2 bytes
let output = ''
let temp
const tripletToBase64 = num => lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
// go through the array every three bytes, we'll deal with trailing stuff later
for (let i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output += tripletToBase64(temp)
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
temp = uint8[uint8.length - 1]
output += lookup[temp >> 2]
output += lookup[(temp << 4) & 0x3F]
output += '=='
} else if (extraBytes === 2) {
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
output += lookup[temp >> 10]
output += lookup[(temp >> 4) & 0x3F]
output += lookup[(temp << 2) & 0x3F]
output += '='
}
return output
}
/**
* Return a random alphanumerical string of length len
* There is a very small probability (less than 1/1,000,000) for the length to be less than len
* (il the base64 conversion yields too many pluses and slashes) but
* that's not an issue here
* The probability of a collision is extremely small (need 3*10^12 documents to have one chance in a million of a collision)
* See http://en.wikipedia.org/wiki/Birthday_problem
* @param {number} len
* @return {string}
* @alias module:customUtilsNode.uid
*/
const uid = len => byteArrayToBase64(randomBytes(Math.ceil(Math.max(8, len * 2)))).replace(/[+/]/g, '').slice(0, len)
module.exports.uid = uid
@@ -0,0 +1,197 @@
/**
* Way data is stored for this database
*
* This version is the browser version and uses [localforage]{@link https://github.com/localForage/localForage} which chooses the best option depending on user browser (IndexedDB then WebSQL then localStorage).
* @module storageBrowser
* @see module:storage
* @see module:storageReactNative
* @private
*/
const localforage = require('localforage')
// Configure localforage to display NeDB name for now. Would be a good idea to let user use his own app name
const store = localforage.createInstance({
name: 'NeDB',
storeName: 'nedbdata'
})
/**
* Returns Promise<true> if file exists.
*
* @param {string} file
* @return {Promise<boolean>}
* @async
* @alias module:storageBrowser.existsAsync
*/
const existsAsync = async file => {
try {
const value = await store.getItem(file)
if (value !== null) return true // Even if value is undefined, localforage returns null
return false
} catch (error) {
console.warn('NeDB - storage.browser - existsAsync:', error)
return false
}
}
/**
* Moves the item from one path to another.
* @param {string} oldPath
* @param {string} newPath
* @return {Promise<void>}
* @alias module:storageBrowser.renameAsync
* @async
*/
const renameAsync = async (oldPath, newPath) => {
try {
const value = await store.getItem(oldPath)
if (value === null) await store.removeItem(newPath)
else {
await store.setItem(newPath, value)
await store.removeItem(oldPath)
}
} catch (err) {
console.warn('NeDB - storage.browser - renameAsync:', err)
console.warn('An error happened while renaming, skip')
}
}
/**
* Saves the item at given path.
* @param {string} file
* @param {string} data
* @param {object} [options]
* @return {Promise<void>}
* @alias module:storageBrowser.writeFileAsync
* @async
*/
const writeFileAsync = async (file, data, options) => {
// Options do not matter in browser setup
try {
await store.setItem(file, data)
} catch (error) {
console.warn('NeDB - storage.browser - writeFileAsync:', error)
console.warn('An error happened while writing, skip')
}
}
/**
* Append to the item at given path.
* @function
* @param {string} filename
* @param {string} toAppend
* @param {object} [options]
* @return {Promise<void>}
* @alias module:storageBrowser.appendFileAsync
* @async
*/
const appendFileAsync = async (filename, toAppend, options) => {
// Options do not matter in browser setup
try {
const contents = (await store.getItem(filename)) || ''
await store.setItem(filename, contents + toAppend)
} catch (error) {
console.warn('NeDB - storage.browser - appendFileAsync:', error)
console.warn('An error happened appending to file writing, skip')
}
}
/**
* Read data at given path.
* @function
* @param {string} filename
* @param {object} [options]
* @return {Promise<Buffer>}
* @alias module:storageBrowser.readFileAsync
* @async
*/
const readFileAsync = async (filename, options) => {
try {
return (await store.getItem(filename)) || ''
} catch (error) {
console.warn('NeDB - storage.browser - readFileAsync:', error)
console.warn('An error happened while reading, skip')
return ''
}
}
/**
* Async version of {@link module:storageBrowser.unlink}.
* @function
* @param {string} filename
* @return {Promise<void>}
* @async
* @alias module:storageBrowser.unlink
*/
const unlinkAsync = async filename => {
try {
await store.removeItem(filename)
} catch (error) {
console.warn('NeDB - storage.browser - unlinkAsync:', error)
console.warn('An error happened while unlinking, skip')
}
}
/**
* Shim for {@link module:storage.mkdirAsync}, nothing to do, no directories will be used on the browser.
* @function
* @param {string} path
* @param {object} [options]
* @return {Promise<void|string>}
* @alias module:storageBrowser.mkdirAsync
* @async
*/
const mkdirAsync = (path, options) => Promise.resolve()
/**
* Shim for {@link module:storage.ensureParentDirectoryExistsAsync}, nothing to do, no directories will be used on the browser.
* @function
* @param {string} file
* @param {number} [mode]
* @return {Promise<void|string>}
* @alias module:storageBrowser.ensureParentDirectoryExistsAsync
* @async
*/
const ensureParentDirectoryExistsAsync = async (file, mode) => Promise.resolve()
/**
* Shim for {@link module:storage.ensureDatafileIntegrityAsync}, nothing to do, no data corruption possible in the browser.
* @param {string} filename
* @return {Promise<void>}
* @alias module:storageBrowser.ensureDatafileIntegrityAsync
*/
const ensureDatafileIntegrityAsync = (filename) => Promise.resolve()
/**
* Fully write or rewrite the datafile, immune to crashes during the write operation (data will not be lost)
* * @param {string} filename
* @param {string[]} lines
* @return {Promise<void>}
* @alias module:storageBrowser.crashSafeWriteFileLinesAsync
*/
const crashSafeWriteFileLinesAsync = async (filename, lines) => {
lines.push('') // Add final new line
await writeFileAsync(filename, lines.join('\n'))
}
// Interface
module.exports.existsAsync = existsAsync
module.exports.renameAsync = renameAsync
module.exports.writeFileAsync = writeFileAsync
module.exports.crashSafeWriteFileLinesAsync = crashSafeWriteFileLinesAsync
module.exports.appendFileAsync = appendFileAsync
module.exports.readFileAsync = readFileAsync
module.exports.unlinkAsync = unlinkAsync
module.exports.mkdirAsync = mkdirAsync
module.exports.ensureDatafileIntegrityAsync = ensureDatafileIntegrityAsync
module.exports.ensureParentDirectoryExistsAsync = ensureParentDirectoryExistsAsync
@@ -0,0 +1,301 @@
/**
* Way data is stored for this database
*
* This version is the React-Native version and uses [@react-native-async-storage/async-storage]{@link https://github.com/react-native-async-storage/async-storage}.
* @module storageReactNative
* @see module:storageBrowser
* @see module:storage
* @private
*/
const AsyncStorage = require('@react-native-async-storage/async-storage').default
const { callbackify } = require('util')
/**
* Async version of {@link module:storageReactNative.exists}.
* @param {string} file
* @return {Promise<boolean>}
* @async
* @alias module:storageReactNative.existsAsync
* @see module:storageReactNative.exists
*/
const existsAsync = async file => {
try {
const value = await AsyncStorage.getItem(file)
if (value !== null) return true // Even if value is undefined, AsyncStorage returns null
return false
} catch (error) {
console.warn('NeDB - storage.react-native - existsAsync:', error)
return false
}
}
/**
* @callback module:storageReactNative~existsCallback
* @param {boolean} exists
*/
/**
* Callback returns true if file exists
* @function
* @param {string} file
* @param {module:storageReactNative~existsCallback} cb
* @alias module:storageReactNative.exists
*/
const exists = callbackify(existsAsync)
/**
* Async version of {@link module:storageReactNative.rename}.
* @param {string} oldPath
* @param {string} newPath
* @return {Promise<void>}
* @alias module:storageReactNative.renameAsync
* @async
* @see module:storageReactNative.rename
*/
const renameAsync = async (oldPath, newPath) => {
try {
const value = await AsyncStorage.getItem(oldPath)
if (value === null) await AsyncStorage.removeItem(newPath)
else {
await AsyncStorage.setItem(newPath, value)
await AsyncStorage.removeItem(oldPath)
}
} catch (err) {
console.warn('NeDB - storage.react-native - renameAsync:', err)
console.warn('An error happened while renaming, skip')
}
}
/**
* Moves the item from one path to another
* @function
* @param {string} oldPath
* @param {string} newPath
* @param {NoParamCallback} c
* @return {void}
* @alias module:storageReactNative.rename
*/
const rename = callbackify(renameAsync)
/**
* Async version of {@link module:storageReactNative.writeFile}.
* @param {string} file
* @param {string} data
* @param {object} [options]
* @return {Promise<void>}
* @alias module:storageReactNative.writeFileAsync
* @async
* @see module:storageReactNative.writeFile
*/
const writeFileAsync = async (file, data, options) => {
// Options do not matter in react-native setup
try {
await AsyncStorage.setItem(file, data)
} catch (error) {
console.warn('NeDB - storage.react-native - writeFileAsync:', error)
console.warn('An error happened while writing, skip')
}
}
/**
* Saves the item at given path
* @function
* @param {string} path
* @param {string} data
* @param {object} options
* @param {function} callback
* @alias module:storageReactNative.writeFile
*/
const writeFile = callbackify(writeFileAsync)
/**
* Async version of {@link module:storageReactNative.appendFile}.
* @function
* @param {string} filename
* @param {string} toAppend
* @param {object} [options]
* @return {Promise<void>}
* @alias module:storageReactNative.appendFileAsync
* @async
* @see module:storageReactNative.appendFile
*/
const appendFileAsync = async (filename, toAppend, options) => {
// Options do not matter in react-native setup
try {
const contents = (await AsyncStorage.getItem(filename)) || ''
await AsyncStorage.setItem(filename, contents + toAppend)
} catch (error) {
console.warn('NeDB - storage.react-native - appendFileAsync:', error)
console.warn('An error happened appending to file writing, skip')
}
}
/**
* Append to the item at given path
* @function
* @param {string} filename
* @param {string} toAppend
* @param {object} [options]
* @param {function} callback
* @alias module:storageReactNative.appendFile
*/
const appendFile = callbackify(appendFileAsync)
/**
* Async version of {@link module:storageReactNative.readFile}.
* @function
* @param {string} filename
* @param {object} [options]
* @return {Promise<string>}
* @alias module:storageReactNative.readFileAsync
* @async
* @see module:storageReactNative.readFile
*/
const readFileAsync = async (filename, options) => {
try {
return (await AsyncStorage.getItem(filename)) || ''
} catch (error) {
console.warn('NeDB - storage.react-native - readFileAsync:', error)
console.warn('An error happened while reading, skip')
return ''
}
}
/**
* Read data at given path
* @function
* @param {string} filename
* @param {object} options
* @param {function} callback
* @alias module:storageReactNative.readFile
*/
const readFile = callbackify(readFileAsync)
/**
* Async version of {@link module:storageReactNative.unlink}.
* @function
* @param {string} filename
* @return {Promise<void>}
* @async
* @alias module:storageReactNative.unlinkAsync
* @see module:storageReactNative.unlink
*/
const unlinkAsync = async filename => {
try {
await AsyncStorage.removeItem(filename)
} catch (error) {
console.warn('NeDB - storage.react-native - unlinkAsync:', error)
console.warn('An error happened while unlinking, skip')
}
}
/**
* Remove the data at given path
* @function
* @param {string} path
* @param {function} callback
* @alias module:storageReactNative.unlink
*/
const unlink = callbackify(unlinkAsync)
/**
* Shim for {@link module:storage.mkdirAsync}, nothing to do, no directories will be used on the react-native.
* @function
* @param {string} dir
* @param {object} [options]
* @return {Promise<void|string>}
* @alias module:storageReactNative.mkdirAsync
* @async
*/
const mkdirAsync = (dir, options) => Promise.resolve()
/**
* Shim for {@link module:storage.mkdir}, nothing to do, no directories will be used on the react-native.
* @function
* @param {string} path
* @param {object} options
* @param {function} callback
* @alias module:storageReactNative.mkdir
*/
const mkdir = callbackify(mkdirAsync)
/**
* Shim for {@link module:storage.ensureDatafileIntegrityAsync}, nothing to do, no data corruption possible in the react-native.
* @param {string} filename
* @return {Promise<void>}
* @alias module:storageReactNative.ensureDatafileIntegrityAsync
*/
const ensureDatafileIntegrityAsync = (filename) => Promise.resolve()
/**
* Shim for {@link module:storage.ensureDatafileIntegrity}, nothing to do, no data corruption possible in the react-native.
* @function
* @param {string} filename
* @param {NoParamCallback} callback signature: err
* @alias module:storageReactNative.ensureDatafileIntegrity
*/
const ensureDatafileIntegrity = callbackify(ensureDatafileIntegrityAsync)
/**
* Async version of {@link module:storageReactNative.crashSafeWriteFileLines}.
* @param {string} filename
* @param {string[]} lines
* @return {Promise<void>}
* @alias module:storageReactNative.crashSafeWriteFileLinesAsync
* @see module:storageReactNative.crashSafeWriteFileLines
*/
const crashSafeWriteFileLinesAsync = async (filename, lines) => {
lines.push('') // Add final new line
await writeFileAsync(filename, lines.join('\n'))
}
/**
* Fully write or rewrite the datafile, immune to crashes during the write operation (data will not be lost)
* @function
* @param {string} filename
* @param {string[]} lines
* @param {NoParamCallback} [callback] Optional callback, signature: err
* @alias module:storageReactNative.crashSafeWriteFileLines
*/
const crashSafeWriteFileLines = callbackify(crashSafeWriteFileLinesAsync)
/**
* Shim for {@link module:storage.ensureParentDirectoryExistsAsync}, nothing to do, no directories will be used on the browser.
* @function
* @param {string} file
* @param {number} [mode]
* @return {Promise<void|string>}
* @alias module:storageBrowser.ensureParentDirectoryExistsAsync
* @async
*/
const ensureParentDirectoryExistsAsync = async (file, mode) => Promise.resolve()
// Interface
module.exports.exists = exists
module.exports.existsAsync = existsAsync
module.exports.rename = rename
module.exports.renameAsync = renameAsync
module.exports.writeFile = writeFile
module.exports.writeFileAsync = writeFileAsync
module.exports.crashSafeWriteFileLines = crashSafeWriteFileLines
module.exports.crashSafeWriteFileLinesAsync = crashSafeWriteFileLinesAsync
module.exports.appendFile = appendFile
module.exports.appendFileAsync = appendFileAsync
module.exports.readFile = readFile
module.exports.readFileAsync = readFileAsync
module.exports.unlink = unlink
module.exports.unlinkAsync = unlinkAsync
module.exports.mkdir = mkdir
module.exports.mkdirAsync = mkdirAsync
module.exports.ensureDatafileIntegrity = ensureDatafileIntegrity
module.exports.ensureDatafileIntegrityAsync = ensureDatafileIntegrityAsync
module.exports.ensureParentDirectoryExistsAsync = ensureParentDirectoryExistsAsync
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,2 @@
/*! For license information please see nedb.min.js.LICENSE.txt */
(()=>{var e={100:e=>{e.exports={}},159:e=>{e.exports.uid=e=>(e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=e.length%3;let n,o="";for(let a=0,s=e.length-r;a<s;a+=3)n=(e[a]<<16)+(e[a+1]<<8)+e[a+2],o+=t[(i=n)>>18&63]+t[i>>12&63]+t[i>>6&63]+t[63&i];var i;return 1===r?(n=e[e.length-1],o+=t[n>>2],o+=t[n<<4&63],o+="=="):2===r&&(n=(e[e.length-2]<<8)+e[e.length-1],o+=t[n>>10],o+=t[n>>4&63],o+=t[n<<2&63],o+="="),o})((e=>{const t=new Array(e);for(let r,n=0;n<e;n++)0==(3&n)&&(r=4294967296*Math.random()),t[n]=r>>>((3&n)<<3)&255;return t})(Math.ceil(Math.max(8,2*e)))).replace(/[+/]/g,"").slice(0,e)},909:(e,t,r)=>{const n=r(483).createInstance({name:"NeDB",storeName:"nedbdata"}),o=async(e,t,r)=>{try{await n.setItem(e,t)}catch(e){console.warn("NeDB - storage.browser - writeFileAsync:",e),console.warn("An error happened while writing, skip")}};e.exports.existsAsync=async e=>{try{return null!==await n.getItem(e)}catch(e){return console.warn("NeDB - storage.browser - existsAsync:",e),!1}},e.exports.renameAsync=async(e,t)=>{try{const r=await n.getItem(e);null===r?await n.removeItem(t):(await n.setItem(t,r),await n.removeItem(e))}catch(e){console.warn("NeDB - storage.browser - renameAsync:",e),console.warn("An error happened while renaming, skip")}},e.exports.writeFileAsync=o,e.exports.crashSafeWriteFileLinesAsync=async(e,t)=>{t.push(""),await o(e,t.join("\n"))},e.exports.appendFileAsync=async(e,t,r)=>{try{const r=await n.getItem(e)||"";await n.setItem(e,r+t)}catch(e){console.warn("NeDB - storage.browser - appendFileAsync:",e),console.warn("An error happened appending to file writing, skip")}},e.exports.readFileAsync=async(e,t)=>{try{return await n.getItem(e)||""}catch(e){return console.warn("NeDB - storage.browser - readFileAsync:",e),console.warn("An error happened while reading, skip"),""}},e.exports.unlinkAsync=async e=>{try{await n.removeItem(e)}catch(e){console.warn("NeDB - storage.browser - unlinkAsync:",e),console.warn("An error happened while unlinking, skip")}},e.exports.mkdirAsync=(e,t)=>Promise.resolve(),e.exports.ensureDatafileIntegrityAsync=e=>Promise.resolve(),e.exports.ensureParentDirectoryExistsAsync=async(e,t)=>Promise.resolve()},578:(e,t,r)=>{const n=r(118),{callbackify:o}=r(539);e.exports=class{constructor(e,t,r){this.db=e,this.query=t||{},r&&(this.mapFn=r),this._limit=void 0,this._skip=void 0,this._sort=void 0,this._projection=void 0}limit(e){return this._limit=e,this}skip(e){return this._skip=e,this}sort(e){return this._sort=e,this}projection(e){return this._projection=e,this}_project(e){const t=[];let r;if(void 0===this._projection||0===Object.keys(this._projection).length)return e;const o=0!==this._projection._id,{_id:i,...a}=this._projection;this._projection=a;const s=Object.keys(this._projection);return s.forEach((e=>{if(void 0!==r&&this._projection[e]!==r)throw new Error("Can't both keep and omit fields except for _id");r=this._projection[e]})),e.forEach((e=>{let i;1===r?(i={$set:{}},s.forEach((t=>{i.$set[t]=n.getDotValue(e,t),void 0===i.$set[t]&&delete i.$set[t]})),i=n.modify({},i)):(i={$unset:{}},s.forEach((e=>{i.$unset[e]=!0})),i=n.modify(e,i)),o?i._id=e._id:delete i._id,t.push(i)})),t}async _execAsync(){let e=[],t=0,r=0;const o=await this.db._getCandidatesAsync(this.query);for(const i of o)if(n.match(i,this.query))if(this._sort)e.push(i);else if(this._skip&&this._skip>r)r+=1;else if(e.push(i),t+=1,this._limit&&this._limit<=t)break;if(this._sort){const t=Object.entries(this._sort).map((([e,t])=>({key:e,direction:t})));e.sort(((e,r)=>{for(const o of t){const t=o.direction*n.compareThings(n.getDotValue(e,o.key),n.getDotValue(r,o.key),this.db.compareStrings);if(0!==t)return t}return 0}));const r=this._limit||e.length,o=this._skip||0;e=e.slice(o,o+r)}return e=this._project(e),this.mapFn?this.mapFn(e):e}exec(e){o((()=>this.execAsync()))(e)}execAsync(){return this.db.executor.pushAsync((()=>this._execAsync()))}then(e,t){return this.execAsync().then(e,t)}catch(e){return this.execAsync().catch(e)}finally(e){return this.execAsync().finally(e)}}},797:(e,t,r)=>{const{EventEmitter:n}=r(187),{callbackify:o,deprecate:i}=r(539),a=r(578),s=r(159),c=r(196),u=r(98),f=r(118),l=r(328),{isDate:h,pick:p,filterIndexNames:y}=r(988);e.exports=class extends n{constructor(e){let t;super(),"string"==typeof e?i((()=>{t=e,this.inMemoryOnly=!1}),"@seald-io/nedb: Giving a string to the Datastore constructor is deprecated and will be removed in the next major version. Please use an options object with an argument 'filename'.")():(t=(e=e||{}).filename,this.inMemoryOnly=e.inMemoryOnly||!1,this.autoload=e.autoload||!1,this.timestampData=e.timestampData||!1),t&&"string"==typeof t&&0!==t.length?this.filename=t:(this.filename=null,this.inMemoryOnly=!0),this.compareStrings=e.compareStrings,this.persistence=new l({db:this,afterSerialization:e.afterSerialization,beforeDeserialization:e.beforeDeserialization,corruptAlertThreshold:e.corruptAlertThreshold,modes:e.modes,testSerializationHooks:e.testSerializaLine truncated
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
(()=>{var t={924:(t,r,e)=>{"use strict";var n=e(210),o=e(559),i=o(n("String.prototype.indexOf"));t.exports=function(t,r){var e=n(t,!!r);return"function"==typeof e&&i(t,".prototype.")>-1?o(e):e}},559:(t,r,e)=>{"use strict";var n=e(612),o=e(210),i=o("%Function.prototype.apply%"),a=o("%Function.prototype.call%"),u=o("%Reflect.apply%",!0)||n.call(a,i),c=o("%Object.getOwnPropertyDescriptor%",!0),p=o("%Object.defineProperty%",!0),f=o("%Math.max%");if(p)try{p({},"a",{value:1})}catch(t){p=null}t.exports=function(t){var r=u(n,a,arguments);return c&&p&&c(r,"length").configurable&&p(r,"length",{value:1+f(0,t.length-(arguments.length-1))}),r};var y=function(){return u(n,i,arguments)};p?p(t.exports,"apply",{value:y}):t.exports.apply=y},29:(t,r,e)=>{"use strict";var n=e(320),o=Object.prototype.toString,i=Object.prototype.hasOwnProperty,a=function(t,r,e){for(var n=0,o=t.length;n<o;n++)i.call(t,n)&&(null==e?r(t[n],n,t):r.call(e,t[n],n,t))},u=function(t,r,e){for(var n=0,o=t.length;n<o;n++)null==e?r(t.charAt(n),n,t):r.call(e,t.charAt(n),n,t)},c=function(t,r,e){for(var n in t)i.call(t,n)&&(null==e?r(t[n],n,t):r.call(e,t[n],n,t))};t.exports=function(t,r,e){if(!n(r))throw new TypeError("iterator must be a function");var i;arguments.length>=3&&(i=e),"[object Array]"===o.call(t)?a(t,r,i):"string"==typeof t?u(t,r,i):c(t,r,i)}},648:t=>{"use strict";var r="Function.prototype.bind called on incompatible ",e=Array.prototype.slice,n=Object.prototype.toString,o="[object Function]";t.exports=function(t){var i=this;if("function"!=typeof i||n.call(i)!==o)throw new TypeError(r+i);for(var a,u=e.call(arguments,1),c=Math.max(0,i.length-u.length),p=[],f=0;f<c;f++)p.push("$"+f);if(a=Function("binder","return function ("+p.join(",")+"){ return binder.apply(this,arguments); }")((function(){if(this instanceof a){var r=i.apply(this,u.concat(e.call(arguments)));return Object(r)===r?r:this}return i.apply(t,u.concat(e.call(arguments)))})),i.prototype){var y=function(){};y.prototype=i.prototype,a.prototype=new y,y.prototype=null}return a}},612:(t,r,e)=>{"use strict";var n=e(648);t.exports=Function.prototype.bind||n},210:(t,r,e)=>{"use strict";var n,o=SyntaxError,i=Function,a=TypeError,u=function(t){try{return i('"use strict"; return ('+t+").constructor;")()}catch(t){}},c=Object.getOwnPropertyDescriptor;if(c)try{c({},"")}catch(t){c=null}var p=function(){throw new a},f=c?function(){try{return p}catch(t){try{return c(arguments,"callee").get}catch(t){return p}}}():p,y=e(405)(),l=Object.getPrototypeOf||function(t){return t.__proto__},s={},g="undefined"==typeof Uint8Array?n:l(Uint8Array),d={"%AggregateError%":"undefined"==typeof AggregateError?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?n:ArrayBuffer,"%ArrayIteratorPrototype%":y?l([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":s,"%AsyncGenerator%":s,"%AsyncGeneratorFunction%":s,"%AsyncIteratorPrototype%":s,"%Atomics%":"undefined"==typeof Atomics?n:Atomics,"%BigInt%":"undefined"==typeof BigInt?n:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?n:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?n:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?n:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?n:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?n:FinalizationRegistry,"%Function%":i,"%GeneratorFunction%":s,"%Int8Array%":"undefined"==typeof Int8Array?n:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?n:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":y?l(l([][Symbol.iterator]())):n,"%JSON%":"object"==typeof JSON?JSON:n,"%Map%":"undefined"==typeof Map?n:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&y?l((new Map)[Symbol.iterator]()):n,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?n:Promise,"%Proxy%":"undefined"==typeof Proxy?n:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?n:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?n:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&y?l((new Set)[Symbol.iterator]()):n,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":y?l(""[Symbol.iterator]()):n,"%Symbol%":y?Symbol:n,"%SyntaxError%":o,"%ThrowTypeError%":f,"%TypedArray%":g,"%TypeError%":a,"%Uint8Array%":"undefined"==typeof Uint8Array?n:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?n:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16ArraLine truncated
+205
View File
@@ -0,0 +1,205 @@
// Type definitions for @seald-io/nedb 2.1.0
// Project: https://github.com/seald/nedb forked from https://github.com/louischatriot/nedb
// Definitions by: Timothée Rebours <https://gihub.com/tex0l>
// Mehdi Kouhen <https://github.com/arantes555>
// Stefan Steinhart <https://github.com/reppners>
// Anthony Nichols <https://github.com/anthonynichols>
// Alejandro Fernandez Haro <https://github.com/afharo>
// Pierre de la Martinière <https://github.com/martpie>
// TypeScript Version: 4.9
/// <reference types="node" />
import { EventEmitter } from "events";
export default Nedb;
export type Document<Schema> = Schema & {
_id: string;
};
declare class Nedb<Schema = Record<string, any>> extends EventEmitter {
constructor(pathOrOptions?: string | Nedb.DataStoreOptions);
persistence: Nedb.Persistence;
autoloadPromise: Promise<void> | null;
loadDatabase(callback?: (err: Error | null) => void): void;
loadDatabaseAsync(): Promise<void>;
dropDatabase(callback?: (err: Error | null) => void): void;
dropDatabaseAsync(): Promise<void>;
compactDatafile(callback?: (err: Error | null) => void): void;
compactDatafileAsync(): Promise<void>;
setAutocompactionInterval(interval: number): void;
stopAutocompaction(): void;
getAllData<T extends Schema>(): Document<T>[];
ensureIndex(
options: Nedb.EnsureIndexOptions,
callback?: (err: Error | null) => void
): void;
ensureIndexAsync(options: Nedb.EnsureIndexOptions): Promise<void>;
removeIndex(fieldName: string | string[], callback?: (err: Error | null) => void): void;
removeIndexAsync(fieldName: string | string[]): Promise<void>;
insert<T extends Schema>(
newDoc: T,
callback?: (err: Error | null, document: Document<T>) => void
): void;
insert<T extends Schema>(
newDocs: T[],
callback?: (err: Error | null, documents: Document<T>[]) => void
): void;
insertAsync<T extends Schema>(newDoc: T): Promise<Document<T>>;
insertAsync<T extends Schema>(newDocs: T[]): Promise<Document<T>[]>;
count(query: any, callback: (err: Error | null, n: number) => void): void;
count(query: any): Nedb.CursorCount;
countAsync(query: any): Nedb.Cursor<number>;
find<T extends Schema>(
query: any,
projection: any,
callback?: (err: Error | null, documents: Document<T>[]) => void
): void;
find<T extends Schema>(
query: any,
projection?: any
): Nedb.Cursor<T>;
find<T extends Schema>(
query: any,
callback: (err: Error | null, documents: Document<T>[]) => void
): void;
findAsync<T extends Schema>(
query: any,
projection?: any
): Nedb.Cursor<T[]>;
findOne<T extends Schema>(
query: any,
projection: any,
callback: (err: Error | null, document: Document<T>) => void
): void;
findOne<T extends Schema>(
query: any,
callback: (err: Error | null, document: Document<T>) => void
): void;
findOneAsync<T extends Schema>(
query: any,
projection?: any
): Nedb.Cursor<T>;
update<T extends Schema, O extends Nedb.UpdateOptions>(
query: any,
updateQuery: any,
options?: O,
callback?: (
err: Error | null,
numberOfUpdated: number,
affectedDocuments: O['returnUpdatedDocs'] extends true ? O['multi'] extends true ? Document<T>[] | null : Document<T> | null : null,
upsert: boolean | null
) => void
): void;
updateAsync<T extends Schema, O extends Nedb.UpdateOptions>(
query: any,
updateQuery: any,
options?: O
): Promise<{
numAffected: number;
affectedDocuments: O['returnUpdatedDocs'] extends true ? O['multi'] extends true ? Document<T>[] | null : Document<T> | null : null;
upsert: boolean;
}>;
remove(
query: any,
options: Nedb.RemoveOptions,
callback?: (err: Error | null, n: number) => void
): void;
remove(query: any, callback?: (err: Error | null, n: number) => void): void;
removeAsync(query: any, options: Nedb.RemoveOptions): Promise<number>;
addListener(event: "compaction.done", listener: () => void): this;
on(event: "compaction.done", listener: () => void): this;
once(event: "compaction.done", listener: () => void): this;
prependListener(event: "compaction.done", listener: () => void): this;
prependOnceListener(event: "compaction.done", listener: () => void): this;
removeListener(event: "compaction.done", listener: () => void): this;
off(event: "compaction.done", listener: () => void): this;
listeners(event: "compaction.done"): Array<() => void>;
rawListeners(event: "compaction.done"): Array<() => void>;
listenerCount(type: "compaction.done"): number;
}
declare namespace Nedb {
interface Cursor<T> extends Promise<Document<T>> {
sort(query: any): Cursor<T>;
skip(n: number): Cursor<T>;
limit(n: number): Cursor<T>;
projection(query: any): Cursor<T>;
exec(callback: (err: Error | null, documents: Document<T>[]) => void): void;
execAsync(): Promise<Document<T>>;
}
interface CursorCount {
exec(callback: (err: Error | null, count: number) => void): void;
}
interface DataStoreOptions {
filename?: string;
timestampData?: boolean;
inMemoryOnly?: boolean;
autoload?: boolean;
onload?(error: Error | null): any;
beforeDeserialization?(line: string): string|Promise<string>;
afterSerialization?(line: string): string|Promise<string>;
corruptAlertThreshold?: number;
compareStrings?(a: string, b: string): number;
modes?: { fileMode: number; dirMode: number };
}
interface UpdateOptions {
multi?: boolean;
upsert?: boolean;
returnUpdatedDocs?: boolean;
}
interface RemoveOptions {
multi?: boolean;
}
interface EnsureIndexOptions {
fieldName: string | string[];
unique?: boolean;
sparse?: boolean;
expireAfterSeconds?: number;
}
interface Persistence {
/** @deprecated */
compactDatafile(): void;
/** @deprecated */
compactDatafileAsync(): Promise<void>;
/** @deprecated */
setAutocompactionInterval(interval: number): void;
/** @deprecated */
stopAutocompaction(): void;
}
}
+3
View File
@@ -0,0 +1,3 @@
const Datastore = require('./lib/datastore')
module.exports = Datastore
+118
View File
@@ -0,0 +1,118 @@
// Forked from https://github.com/jahewson/node-byline
// Copyright (C) 2011-2015 John Hewson
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
/**
* @module byline
* @private
*/
const stream = require('stream')
const timers = require('timers')
const { Buffer } = require('buffer')
const createLineStream = (readStream, options) => {
if (!readStream) throw new Error('expected readStream')
if (!readStream.readable) throw new Error('readStream must be readable')
const ls = new LineStream(options)
readStream.pipe(ls)
return ls
}
/**
* Fork from {@link https://github.com/jahewson/node-byline}.
* @see https://github.com/jahewson/node-byline
* @alias module:byline.LineStream
* @private
*/
class LineStream extends stream.Transform {
constructor (options) {
super(options)
options = options || {}
// use objectMode to stop the output from being buffered
// which re-concatanates the lines, just without newlines.
this._readableState.objectMode = true
this._lineBuffer = []
this._keepEmptyLines = options.keepEmptyLines || false
this._lastChunkEndedWithCR = false
// take the source's encoding if we don't have one
this.once('pipe', src => {
if (!this.encoding && src instanceof stream.Readable) this.encoding = src._readableState.encoding // but we can't do this for old-style streams
})
}
_transform (chunk, encoding, done) {
// decode binary chunks as UTF-8
encoding = encoding || 'utf8'
if (Buffer.isBuffer(chunk)) {
if (encoding === 'buffer') {
chunk = chunk.toString() // utf8
encoding = 'utf8'
} else chunk = chunk.toString(encoding)
}
this._chunkEncoding = encoding
// see: http://www.unicode.org/reports/tr18/#Line_Boundaries
const lines = chunk.split(/\r\n|[\n\v\f\r\x85\u2028\u2029]/g)
// don't split CRLF which spans chunks
if (this._lastChunkEndedWithCR && chunk[0] === '\n') lines.shift()
if (this._lineBuffer.length > 0) {
this._lineBuffer[this._lineBuffer.length - 1] += lines[0]
lines.shift()
}
this._lastChunkEndedWithCR = chunk[chunk.length - 1] === '\r'
this._lineBuffer = this._lineBuffer.concat(lines)
this._pushBuffer(encoding, 1, done)
}
_pushBuffer (encoding, keep, done) {
// always buffer the last (possibly partial) line
while (this._lineBuffer.length > keep) {
const line = this._lineBuffer.shift()
// skip empty lines
if (this._keepEmptyLines || line.length > 0) {
if (!this.push(this._reencode(line, encoding))) {
// when the high-water mark is reached, defer pushes until the next tick
timers.setImmediate(() => { this._pushBuffer(encoding, keep, done) })
return
}
}
}
done()
}
_flush (done) {
this._pushBuffer(this._chunkEncoding, 0, done)
}
// see Readable::push
_reencode (line, chunkEncoding) {
if (this.encoding && this.encoding !== chunkEncoding) return Buffer.from(line, chunkEncoding).toString(this.encoding)
else if (this.encoding) return line // this should be the most common case, i.e. we're using an encoded source stream
else return Buffer.from(line, chunkEncoding)
}
}
module.exports = createLineStream
+250
View File
@@ -0,0 +1,250 @@
const model = require('./model.js')
const { callbackify } = require('util')
/**
* Has a callback
* @callback Cursor~mapFn
* @param {document[]} res
* @return {*|Promise<*>}
*/
/**
* Manage access to data, be it to find, update or remove it.
*
* It extends `Promise` so that its methods (which return `this`) are chainable & awaitable.
* @extends Promise
*/
class Cursor {
/**
* Create a new cursor for this collection.
* @param {Datastore} db - The datastore this cursor is bound to
* @param {query} query - The query this cursor will operate on
* @param {Cursor~mapFn} [mapFn] - Handler to be executed after cursor has found the results and before the callback passed to find/findOne/update/remove
*/
constructor (db, query, mapFn) {
/**
* @protected
* @type {Datastore}
*/
this.db = db
/**
* @protected
* @type {query}
*/
this.query = query || {}
/**
* The handler to be executed after cursor has found the results.
* @type {Cursor~mapFn}
* @protected
*/
if (mapFn) this.mapFn = mapFn
/**
* @see Cursor#limit
* @type {undefined|number}
* @private
*/
this._limit = undefined
/**
* @see Cursor#skip
* @type {undefined|number}
* @private
*/
this._skip = undefined
/**
* @see Cursor#sort
* @type {undefined|Object.<string, number>}
* @private
*/
this._sort = undefined
/**
* @see Cursor#projection
* @type {undefined|Object.<string, number>}
* @private
*/
this._projection = undefined
}
/**
* Set a limit to the number of results for the given Cursor.
* @param {Number} limit
* @return {Cursor} the same instance of Cursor, (useful for chaining).
*/
limit (limit) {
this._limit = limit
return this
}
/**
* Skip a number of results for the given Cursor.
* @param {Number} skip
* @return {Cursor} the same instance of Cursor, (useful for chaining).
*/
skip (skip) {
this._skip = skip
return this
}
/**
* Sort results of the query for the given Cursor.
* @param {Object.<string, number>} sortQuery - sortQuery is { field: order }, field can use the dot-notation, order is 1 for ascending and -1 for descending
* @return {Cursor} the same instance of Cursor, (useful for chaining).
*/
sort (sortQuery) {
this._sort = sortQuery
return this
}
/**
* Add the use of a projection to the given Cursor.
* @param {Object.<string, number>} projection - MongoDB-style projection. {} means take all fields. Then it's { key1: 1, key2: 1 } to take only key1 and key2
* { key1: 0, key2: 0 } to omit only key1 and key2. Except _id, you can't mix takes and omits.
* @return {Cursor} the same instance of Cursor, (useful for chaining).
*/
projection (projection) {
this._projection = projection
return this
}
/**
* Apply the projection.
*
* This is an internal function. You should use {@link Cursor#execAsync} or {@link Cursor#exec}.
* @param {document[]} candidates
* @return {document[]}
* @private
*/
_project (candidates) {
const res = []
let action
if (this._projection === undefined || Object.keys(this._projection).length === 0) {
return candidates
}
const keepId = this._projection._id !== 0
const { _id, ...rest } = this._projection
this._projection = rest
// Check for consistency
const keys = Object.keys(this._projection)
keys.forEach(k => {
if (action !== undefined && this._projection[k] !== action) throw new Error('Can\'t both keep and omit fields except for _id')
action = this._projection[k]
})
// Do the actual projection
candidates.forEach(candidate => {
let toPush
if (action === 1) { // pick-type projection
toPush = { $set: {} }
keys.forEach(k => {
toPush.$set[k] = model.getDotValue(candidate, k)
if (toPush.$set[k] === undefined) delete toPush.$set[k]
})
toPush = model.modify({}, toPush)
} else { // omit-type projection
toPush = { $unset: {} }
keys.forEach(k => { toPush.$unset[k] = true })
toPush = model.modify(candidate, toPush)
}
if (keepId) toPush._id = candidate._id
else delete toPush._id
res.push(toPush)
})
return res
}
/**
* Get all matching elements
* Will return pointers to matched elements (shallow copies), returning full copies is the role of find or findOne
* This is an internal function, use execAsync which uses the executor
* @return {document[]|Promise<*>}
* @private
*/
async _execAsync () {
let res = []
let added = 0
let skipped = 0
const candidates = await this.db._getCandidatesAsync(this.query)
for (const candidate of candidates) {
if (model.match(candidate, this.query)) {
// If a sort is defined, wait for the results to be sorted before applying limit and skip
if (!this._sort) {
if (this._skip && this._skip > skipped) skipped += 1
else {
res.push(candidate)
added += 1
if (this._limit && this._limit <= added) break
}
} else res.push(candidate)
}
}
// Apply all sorts
if (this._sort) {
// Sorting
const criteria = Object.entries(this._sort).map(([key, direction]) => ({ key, direction }))
res.sort((a, b) => {
for (const criterion of criteria) {
const compare = criterion.direction * model.compareThings(model.getDotValue(a, criterion.key), model.getDotValue(b, criterion.key), this.db.compareStrings)
if (compare !== 0) return compare
}
return 0
})
// Applying limit and skip
const limit = this._limit || res.length
const skip = this._skip || 0
res = res.slice(skip, skip + limit)
}
// Apply projection
res = this._project(res)
if (this.mapFn) return this.mapFn(res)
return res
}
/**
* @callback Cursor~execCallback
* @param {Error} err
* @param {document[]|*} res If a mapFn was given to the Cursor, then the type of this parameter is the one returned by the mapFn.
*/
/**
* Callback version of {@link Cursor#exec}.
* @param {Cursor~execCallback} _callback
* @see Cursor#execAsync
*/
exec (_callback) {
callbackify(() => this.execAsync())(_callback)
}
/**
* Get all matching elements.
* Will return pointers to matched elements (shallow copies), returning full copies is the role of {@link Datastore#findAsync} or {@link Datastore#findOneAsync}.
* @return {Promise<document[]|*>}
* @async
*/
execAsync () {
return this.db.executor.pushAsync(() => this._execAsync())
}
then (onFulfilled, onRejected) {
return this.execAsync().then(onFulfilled, onRejected)
}
catch (onRejected) {
return this.execAsync().catch(onRejected)
}
finally (onFinally) {
return this.execAsync().finally(onFinally)
}
}
// Interface
module.exports = Cursor
+26
View File
@@ -0,0 +1,26 @@
/**
* Utility functions that need to be reimplemented for each environment.
* This is the version for Node.js
* @module customUtilsNode
* @private
*/
const crypto = require('crypto')
/**
* Return a random alphanumerical string of length len
* There is a very small probability (less than 1/1,000,000) for the length to be less than len
* (il the base64 conversion yields too many pluses and slashes) but
* that's not an issue here
* The probability of a collision is extremely small (need 3*10^12 documents to have one chance in a million of a collision)
* See http://en.wikipedia.org/wiki/Birthday_problem
* @param {number} len
* @return {string}
* @alias module:customUtilsNode.uid
*/
const uid = len => crypto.randomBytes(Math.ceil(Math.max(8, len * 2)))
.toString('base64')
.replace(/[+/]/g, '')
.slice(0, len)
// Interface
module.exports.uid = uid
File diff suppressed because it is too large. Load diff
+79
View File
@@ -0,0 +1,79 @@
const Waterfall = require('./waterfall')
/**
* Executes operations sequentially.
* Has an option for a buffer that can be triggered afterwards.
* @private
*/
class Executor {
/**
* Instantiates a new Executor.
*/
constructor () {
/**
* If this.ready is `false`, then every task pushed will be buffered until this.processBuffer is called.
* @type {boolean}
* @private
*/
this.ready = false
/**
* The main queue
* @type {Waterfall}
* @private
*/
this.queue = new Waterfall()
/**
* The buffer queue
* @type {Waterfall}
* @private
*/
this.buffer = null
/**
* Method to trigger the buffer processing.
*
* Do not be use directly, use `this.processBuffer` instead.
* @function
* @private
*/
this._triggerBuffer = null
this.resetBuffer()
}
/**
* If executor is ready, queue task (and process it immediately if executor was idle)
* If not, buffer task for later processing
* @param {AsyncFunction} task Function to execute
* @param {boolean} [forceQueuing = false] Optional (defaults to false) force executor to queue task even if it is not ready
* @return {Promise<*>}
* @async
* @see Executor#push
*/
pushAsync (task, forceQueuing = false) {
if (this.ready || forceQueuing) return this.queue.waterfall(task)()
else return this.buffer.waterfall(task)()
}
/**
* Queue all tasks in buffer (in the same order they came in)
* Automatically sets executor as ready
*/
processBuffer () {
this.ready = true
this._triggerBuffer()
this.queue.waterfall(() => this.buffer.guardian)
}
/**
* Removes all tasks queued up in the buffer
*/
resetBuffer () {
this.buffer = new Waterfall()
this.buffer.chain(new Promise(resolve => {
this._triggerBuffer = resolve
}))
if (this.ready) this._triggerBuffer()
}
}
// Interface
module.exports = Executor
+333
View File
@@ -0,0 +1,333 @@
const BinarySearchTree = require('@seald-io/binary-search-tree').AVLTree
const model = require('./model.js')
const { uniq, isDate } = require('./utils.js')
/**
* Two indexed pointers are equal if they point to the same place
* @param {*} a
* @param {*} b
* @return {boolean}
* @private
*/
const checkValueEquality = (a, b) => a === b
/**
* Type-aware projection
* @param {*} elt
* @return {string|*}
* @private
*/
const projectForUnique = elt => {
if (elt === null) return '$null'
if (typeof elt === 'string') return '$string' + elt
if (typeof elt === 'boolean') return '$boolean' + elt
if (typeof elt === 'number') return '$number' + elt
if (isDate(elt)) return '$date' + elt.getTime()
return elt // Arrays and objects, will check for pointer equality
}
/**
* Indexes on field names, with atomic operations and which can optionally enforce a unique constraint or allow indexed
* fields to be undefined
* @private
*/
class Index {
/**
* Create a new index
* All methods on an index guarantee that either the whole operation was successful and the index changed
* or the operation was unsuccessful and an error is thrown while the index is unchanged
* @param {object} options
* @param {string} options.fieldName On which field should the index apply, can use dot notation to index on sub fields, can use comma-separated notation to use compound indexes
* @param {boolean} [options.unique = false] Enforces a unique constraint
* @param {boolean} [options.sparse = false] Allows a sparse index (we can have documents for which fieldName is `undefined`)
*/
constructor (options) {
/**
* On which field the index applies to, can use dot notation to index on sub fields, can use comma-separated notation to use compound indexes.
* @type {string}
*/
this.fieldName = options.fieldName
if (typeof this.fieldName !== 'string') throw new Error('fieldName must be a string')
/**
* Internal property which is an Array representing the fieldName split with `,`, useful only for compound indexes.
* @type {string[]}
* @private
*/
this._fields = this.fieldName.split(',')
/**
* Defines if the index enforces a unique constraint for this index.
* @type {boolean}
*/
this.unique = options.unique || false
/**
* Defines if we can have documents for which fieldName is `undefined`
* @type {boolean}
*/
this.sparse = options.sparse || false
/**
* Options object given to the underlying BinarySearchTree.
* @type {{unique: boolean, checkValueEquality: (function(*, *): boolean), compareKeys: ((function(*, *, compareStrings): (number|number))|*)}}
*/
this.treeOptions = { unique: this.unique, compareKeys: model.compareThings, checkValueEquality }
/**
* Underlying BinarySearchTree for this index. Uses an AVLTree for optimization.
* @type {AVLTree}
*/
this.tree = new BinarySearchTree(this.treeOptions)
}
/**
* Reset an index
* @param {?document|?document[]} [newData] Data to initialize the index with. If an error is thrown during
* insertion, the index is not modified.
*/
reset (newData) {
this.tree = new BinarySearchTree(this.treeOptions)
if (newData) this.insert(newData)
}
/**
* Insert a new document in the index
* If an array is passed, we insert all its elements (if one insertion fails the index is not modified)
* O(log(n))
* @param {document|document[]} doc The document, or array of documents, to insert.
*/
insert (doc) {
let keys
let failingIndex
let error
if (Array.isArray(doc)) {
this.insertMultipleDocs(doc)
return
}
const key = model.getDotValues(doc, this._fields)
// We don't index documents that don't contain the field if the index is sparse
if ((key === undefined || (typeof key === 'object' && key !== null && Object.values(key).every(el => el === undefined))) && this.sparse) return
if (!Array.isArray(key)) this.tree.insert(key, doc)
else {
// If an insert fails due to a unique constraint, roll back all inserts before it
keys = uniq(key, projectForUnique)
for (let i = 0; i < keys.length; i += 1) {
try {
this.tree.insert(keys[i], doc)
} catch (e) {
error = e
failingIndex = i
break
}
}
if (error) {
for (let i = 0; i < failingIndex; i += 1) {
this.tree.delete(keys[i], doc)
}
throw error
}
}
}
/**
* Insert an array of documents in the index
* If a constraint is violated, the changes should be rolled back and an error thrown
* @param {document[]} docs Array of documents to insert.
* @private
*/
insertMultipleDocs (docs) {
let error
let failingIndex
for (let i = 0; i < docs.length; i += 1) {
try {
this.insert(docs[i])
} catch (e) {
error = e
failingIndex = i
break
}
}
if (error) {
for (let i = 0; i < failingIndex; i += 1) {
this.remove(docs[i])
}
throw error
}
}
/**
* Removes a document from the index.
* If an array is passed, we remove all its elements
* The remove operation is safe with regards to the 'unique' constraint
* O(log(n))
* @param {document[]|document} doc The document, or Array of documents, to remove.
*/
remove (doc) {
if (Array.isArray(doc)) {
doc.forEach(d => { this.remove(d) })
return
}
const key = model.getDotValues(doc, this._fields)
if (key === undefined && this.sparse) return
if (!Array.isArray(key)) {
this.tree.delete(key, doc)
} else {
uniq(key, projectForUnique).forEach(_key => {
this.tree.delete(_key, doc)
})
}
}
/**
* Update a document in the index
* If a constraint is violated, changes are rolled back and an error thrown
* Naive implementation, still in O(log(n))
* @param {document|Array.<{oldDoc: document, newDoc: document}>} oldDoc Document to update, or an `Array` of
* `{oldDoc, newDoc}` pairs.
* @param {document} [newDoc] Document to replace the oldDoc with. If the first argument is an `Array` of
* `{oldDoc, newDoc}` pairs, this second argument is ignored.
*/
update (oldDoc, newDoc) {
if (Array.isArray(oldDoc)) {
this.updateMultipleDocs(oldDoc)
return
}
this.remove(oldDoc)
try {
this.insert(newDoc)
} catch (e) {
this.insert(oldDoc)
throw e
}
}
/**
* Update multiple documents in the index
* If a constraint is violated, the changes need to be rolled back
* and an error thrown
* @param {Array.<{oldDoc: document, newDoc: document}>} pairs
*
* @private
*/
updateMultipleDocs (pairs) {
let failingIndex
let error
for (let i = 0; i < pairs.length; i += 1) {
this.remove(pairs[i].oldDoc)
}
for (let i = 0; i < pairs.length; i += 1) {
try {
this.insert(pairs[i].newDoc)
} catch (e) {
error = e
failingIndex = i
break
}
}
// If an error was raised, roll back changes in the inverse order
if (error) {
for (let i = 0; i < failingIndex; i += 1) {
this.remove(pairs[i].newDoc)
}
for (let i = 0; i < pairs.length; i += 1) {
this.insert(pairs[i].oldDoc)
}
throw error
}
}
/**
* Revert an update
* @param {document|Array.<{oldDoc: document, newDoc: document}>} oldDoc Document to revert to, or an `Array` of `{oldDoc, newDoc}` pairs.
* @param {document} [newDoc] Document to revert from. If the first argument is an Array of {oldDoc, newDoc}, this second argument is ignored.
*/
revertUpdate (oldDoc, newDoc) {
const revert = []
if (!Array.isArray(oldDoc)) this.update(newDoc, oldDoc)
else {
oldDoc.forEach(pair => {
revert.push({ oldDoc: pair.newDoc, newDoc: pair.oldDoc })
})
this.update(revert)
}
}
/**
* Get all documents in index whose key match value (if it is a Thing) or one of the elements of value (if it is an array of Things)
* @param {Array.<*>|*} value Value to match the key against
* @return {document[]}
*/
getMatching (value) {
if (!Array.isArray(value)) return this.tree.search(value)
else {
const _res = {}
const res = []
value.forEach(v => {
this.getMatching(v).forEach(doc => {
_res[doc._id] = doc
})
})
Object.keys(_res).forEach(_id => {
res.push(_res[_id])
})
return res
}
}
/**
* Get all documents in index whose key is between bounds are they are defined by query
* Documents are sorted by key
* @param {object} query An object with at least one matcher among $gt, $gte, $lt, $lte.
* @param {*} [query.$gt] Greater than matcher.
* @param {*} [query.$gte] Greater than or equal matcher.
* @param {*} [query.$lt] Lower than matcher.
* @param {*} [query.$lte] Lower than or equal matcher.
* @return {document[]}
*/
getBetweenBounds (query) {
return this.tree.betweenBounds(query)
}
/**
* Get all elements in the index
* @return {document[]}
*/
getAll () {
const res = []
this.tree.executeOnEveryNode(node => {
res.push(...node.data)
})
return res
}
}
// Interface
module.exports = Index
+827
View File
@@ -0,0 +1,827 @@
/**
* Handle models (i.e. docs)
* Serialization/deserialization
* Copying
* Querying, update
* @module model
* @private
*/
const { uniq, isDate, isRegExp } = require('./utils.js')
/**
* Check a key, throw an error if the key is non valid
* @param {string} k key
* @param {document} v value, needed to treat the Date edge case
* Non-treatable edge cases here: if part of the object if of the form { $$date: number } or { $$deleted: true }
* Its serialized-then-deserialized version it will transformed into a Date object
* But you really need to want it to trigger such behaviour, even when warned not to use '$' at the beginning of the field names...
* @private
*/
const checkKey = (k, v) => {
if (typeof k === 'number') k = k.toString()
if (
k[0] === '$' &&
!(k === '$$date' && typeof v === 'number') &&
!(k === '$$deleted' && v === true) &&
!(k === '$$indexCreated') &&
!(k === '$$indexRemoved')
) throw new Error('Field names cannot begin with the $ character')
if (k.indexOf('.') !== -1) throw new Error('Field names cannot contain a .')
}
/**
* Check a DB object and throw an error if it's not valid
* Works by applying the above checkKey function to all fields recursively
* @param {document|document[]} obj
* @alias module:model.checkObject
*/
const checkObject = obj => {
if (Array.isArray(obj)) {
obj.forEach(o => {
checkObject(o)
})
}
if (typeof obj === 'object' && obj !== null) {
for (const k in obj) {
if (Object.prototype.hasOwnProperty.call(obj, k)) {
checkKey(k, obj[k])
checkObject(obj[k])
}
}
}
}
/**
* Serialize an object to be persisted to a one-line string
* For serialization/deserialization, we use the native JSON parser and not eval or Function
* That gives us less freedom but data entered in the database may come from users
* so eval and the like are not safe
* Accepted primitive types: Number, String, Boolean, Date, null
* Accepted secondary types: Objects, Arrays
* @param {document} obj
* @return {string}
* @alias module:model.serialize
*/
const serialize = obj => {
return JSON.stringify(obj, function (k, v) {
checkKey(k, v)
if (v === undefined) return undefined
if (v === null) return null
// Hackish way of checking if object is Date (this way it works between execution contexts in node-webkit).
// We can't use value directly because for dates it is already string in this function (date.toJSON was already called), so we use this
if (typeof this[k].getTime === 'function') return { $$date: this[k].getTime() }
return v
})
}
/**
* From a one-line representation of an object generate by the serialize function
* Return the object itself
* @param {string} rawData
* @return {document}
* @alias module:model.deserialize
*/
const deserialize = rawData => JSON.parse(rawData, function (k, v) {
if (k === '$$date') return new Date(v)
if (
typeof v === 'string' ||
typeof v === 'number' ||
typeof v === 'boolean' ||
v === null
) return v
if (v && v.$$date) return v.$$date
return v
})
/**
* Deep copy a DB object
* The optional strictKeys flag (defaulting to false) indicates whether to copy everything or only fields
* where the keys are valid, i.e. don't begin with $ and don't contain a .
* @param {?document} obj
* @param {boolean} [strictKeys=false]
* @return {?document}
* @alias module:modelel:(.*)
*/
function deepCopy (obj, strictKeys) {
if (
typeof obj === 'boolean' ||
typeof obj === 'number' ||
typeof obj === 'string' ||
obj === null ||
(isDate(obj))
) return obj
if (Array.isArray(obj)) return obj.map(o => deepCopy(o, strictKeys))
if (typeof obj === 'object') {
const res = {}
for (const k in obj) {
if (
Object.prototype.hasOwnProperty.call(obj, k) &&
(!strictKeys || (k[0] !== '$' && k.indexOf('.') === -1))
) {
res[k] = deepCopy(obj[k], strictKeys)
}
}
return res
}
return undefined // For now everything else is undefined. We should probably throw an error instead
}
/**
* Tells if an object is a primitive type or a "real" object
* Arrays are considered primitive
* @param {*} obj
* @return {boolean}
* @alias module:modelel:(.*)
*/
const isPrimitiveType = obj => (
typeof obj === 'boolean' ||
typeof obj === 'number' ||
typeof obj === 'string' ||
obj === null ||
isDate(obj) ||
Array.isArray(obj)
)
/**
* Utility functions for comparing things
* Assumes type checking was already done (a and b already have the same type)
* compareNSB works for numbers, strings and booleans
* @param {number|string|boolean} a
* @param {number|string|boolean} b
* @return {number} 0 if a == b, 1 i a > b, -1 if a < b
* @private
*/
const compareNSB = (a, b) => {
if (a < b) return -1
if (a > b) return 1
return 0
}
/**
* Utility function for comparing array
* Assumes type checking was already done (a and b already have the same type)
* compareNSB works for numbers, strings and booleans
* @param {Array} a
* @param {Array} b
* @return {number} 0 if arrays have the same length and all elements equal one another. Else either 1 or -1.
* @private
*/
const compareArrays = (a, b) => {
const minLength = Math.min(a.length, b.length)
for (let i = 0; i < minLength; i += 1) {
const comp = compareThings(a[i], b[i])
if (comp !== 0) return comp
}
// Common section was identical, longest one wins
return compareNSB(a.length, b.length)
}
/**
* Compare { things U undefined }
* Things are defined as any native types (string, number, boolean, null, date) and objects
* We need to compare with undefined as it will be used in indexes
* In the case of objects and arrays, we deep-compare
* If two objects dont have the same type, the (arbitrary) type hierarchy is: undefined, null, number, strings, boolean, dates, arrays, objects
* Return -1 if a < b, 1 if a > b and 0 if a = b (note that equality here is NOT the same as defined in areThingsEqual!)
* @param {*} a
* @param {*} b
* @param {compareStrings} [_compareStrings] String comparing function, returning -1, 0 or 1, overriding default string comparison (useful for languages with accented letters)
* @return {number}
* @alias module:model.compareThings
*/
const compareThings = (a, b, _compareStrings) => {
const compareStrings = _compareStrings || compareNSB
// undefined
if (a === undefined) return b === undefined ? 0 : -1
if (b === undefined) return 1 // no need to test if a === undefined
// null
if (a === null) return b === null ? 0 : -1
if (b === null) return 1 // no need to test if a === null
// Numbers
if (typeof a === 'number') return typeof b === 'number' ? compareNSB(a, b) : -1
if (typeof b === 'number') return typeof a === 'number' ? compareNSB(a, b) : 1
// Strings
if (typeof a === 'string') return typeof b === 'string' ? compareStrings(a, b) : -1
if (typeof b === 'string') return typeof a === 'string' ? compareStrings(a, b) : 1
// Booleans
if (typeof a === 'boolean') return typeof b === 'boolean' ? compareNSB(a, b) : -1
if (typeof b === 'boolean') return typeof a === 'boolean' ? compareNSB(a, b) : 1
// Dates
if (isDate(a)) return isDate(b) ? compareNSB(a.getTime(), b.getTime()) : -1
if (isDate(b)) return isDate(a) ? compareNSB(a.getTime(), b.getTime()) : 1
// Arrays (first element is most significant and so on)
if (Array.isArray(a)) return Array.isArray(b) ? compareArrays(a, b) : -1
if (Array.isArray(b)) return Array.isArray(a) ? compareArrays(a, b) : 1
// Objects
const aKeys = Object.keys(a).sort()
const bKeys = Object.keys(b).sort()
for (let i = 0; i < Math.min(aKeys.length, bKeys.length); i += 1) {
const comp = compareThings(a[aKeys[i]], b[bKeys[i]])
if (comp !== 0) return comp
}
return compareNSB(aKeys.length, bKeys.length)
}
// ==============================================================
// Updating documents
// ==============================================================
/**
* @callback modifierFunction
* The signature of modifier functions is as follows
* Their structure is always the same: recursively follow the dot notation while creating
* the nested documents if needed, then apply the "last step modifier"
* @param {Object} obj The model to modify
* @param {String} field Can contain dots, in that case that means we will set a subfield recursively
* @param {document} value
*/
/**
* Create the complete modifier function
* @param {modifierFunction} lastStepModifierFunction a lastStepModifierFunction
* @param {boolean} [unset = false] Bad looking specific fix, needs to be generalized modifiers that behave like $unset are implemented
* @return {modifierFunction}
* @private
*/
const createModifierFunction = (lastStepModifierFunction, unset = false) => {
const func = (obj, field, value) => {
const fieldParts = typeof field === 'string' ? field.split('.') : field
if (fieldParts.length === 1) lastStepModifierFunction(obj, field, value)
else {
if (obj[fieldParts[0]] === undefined) {
if (unset) return
obj[fieldParts[0]] = {}
}
func(obj[fieldParts[0]], fieldParts.slice(1), value)
}
}
return func
}
const $addToSetPartial = (obj, field, value) => {
// Create the array if it doesn't exist
if (!Object.prototype.hasOwnProperty.call(obj, field)) { obj[field] = [] }
if (!Array.isArray(obj[field])) throw new Error('Can\'t $addToSet an element on non-array values')
if (value !== null && typeof value === 'object' && value.$each) {
if (Object.keys(value).length > 1) throw new Error('Can\'t use another field in conjunction with $each')
if (!Array.isArray(value.$each)) throw new Error('$each requires an array value')
value.$each.forEach(v => {
$addToSetPartial(obj, field, v)
})
} else {
let addToSet = true
obj[field].forEach(v => {
if (compareThings(v, value) === 0) addToSet = false
})
if (addToSet) obj[field].push(value)
}
}
/**
* @enum {modifierFunction}
*/
const modifierFunctions = {
/**
* Set a field to a new value
*/
$set: createModifierFunction((obj, field, value) => {
obj[field] = value
}),
/**
* Unset a field
*/
$unset: createModifierFunction((obj, field, value) => {
delete obj[field]
}, true),
/**
* Updates the value of the field, only if specified field is smaller than the current value of the field
*/
$min: createModifierFunction((obj, field, value) => {
if (typeof obj[field] === 'undefined') obj[field] = value
else if (value < obj[field]) obj[field] = value
}),
/**
* Updates the value of the field, only if specified field is greater than the current value of the field
*/
$max: createModifierFunction((obj, field, value) => {
if (typeof obj[field] === 'undefined') obj[field] = value
else if (value > obj[field]) obj[field] = value
}),
/**
* Increment a numeric field's value
*/
$inc: createModifierFunction((obj, field, value) => {
if (typeof value !== 'number') throw new Error(`${value} must be a number`)
if (typeof obj[field] !== 'number') {
if (!Object.prototype.hasOwnProperty.call(obj, field)) obj[field] = value
else throw new Error('Don\'t use the $inc modifier on non-number fields')
} else obj[field] += value
}),
/**
* Removes all instances of a value from an existing array
*/
$pull: createModifierFunction((obj, field, value) => {
if (!Array.isArray(obj[field])) throw new Error('Can\'t $pull an element from non-array values')
const arr = obj[field]
for (let i = arr.length - 1; i >= 0; i -= 1) {
if (match(arr[i], value)) arr.splice(i, 1)
}
}),
/**
* Remove the first or last element of an array
*/
$pop: createModifierFunction((obj, field, value) => {
if (!Array.isArray(obj[field])) throw new Error('Can\'t $pop an element from non-array values')
if (typeof value !== 'number') throw new Error(`${value} isn't an integer, can't use it with $pop`)
if (value === 0) return
if (value > 0) obj[field] = obj[field].slice(0, obj[field].length - 1)
else obj[field] = obj[field].slice(1)
}),
/**
* Add an element to an array field only if it is not already in it
* No modification if the element is already in the array
* Note that it doesn't check whether the original array contains duplicates
*/
$addToSet: createModifierFunction($addToSetPartial),
/**
* Push an element to the end of an array field
* Optional modifier $each instead of value to push several values
* Optional modifier $slice to slice the resulting array, see https://docs.mongodb.org/manual/reference/operator/update/slice/
* Difference with MongoDB: if $slice is specified and not $each, we act as if value is an empty array
*/
$push: createModifierFunction((obj, field, value) => {
// Create the array if it doesn't exist
if (!Object.prototype.hasOwnProperty.call(obj, field)) obj[field] = []
if (!Array.isArray(obj[field])) throw new Error('Can\'t $push an element on non-array values')
if (
value !== null &&
typeof value === 'object' &&
value.$slice &&
value.$each === undefined
) value.$each = []
if (value !== null && typeof value === 'object' && value.$each) {
if (
Object.keys(value).length >= 3 ||
(Object.keys(value).length === 2 && value.$slice === undefined)
) throw new Error('Can only use $slice in cunjunction with $each when $push to array')
if (!Array.isArray(value.$each)) throw new Error('$each requires an array value')
value.$each.forEach(v => {
obj[field].push(v)
})
if (value.$slice === undefined || typeof value.$slice !== 'number') return
if (value.$slice === 0) obj[field] = []
else {
let start
let end
const n = obj[field].length
if (value.$slice < 0) {
start = Math.max(0, n + value.$slice)
end = n
} else if (value.$slice > 0) {
start = 0
end = Math.min(n, value.$slice)
}
obj[field] = obj[field].slice(start, end)
}
} else {
obj[field].push(value)
}
})
}
/**
* Modify a DB object according to an update query
* @param {document} obj
* @param {query} updateQuery
* @return {document}
* @alias module:model.modify
*/
const modify = (obj, updateQuery) => {
const keys = Object.keys(updateQuery)
const firstChars = keys.map(item => item[0])
const dollarFirstChars = firstChars.filter(c => c === '$')
let newDoc
let modifiers
if (keys.indexOf('_id') !== -1 && updateQuery._id !== obj._id) throw new Error('You cannot change a document\'s _id')
if (dollarFirstChars.length !== 0 && dollarFirstChars.length !== firstChars.length) throw new Error('You cannot mix modifiers and normal fields')
if (dollarFirstChars.length === 0) {
// Simply replace the object with the update query contents
newDoc = deepCopy(updateQuery)
newDoc._id = obj._id
} else {
// Apply modifiers
modifiers = uniq(keys)
newDoc = deepCopy(obj)
modifiers.forEach(m => {
if (!modifierFunctions[m]) throw new Error(`Unknown modifier ${m}`)
// Can't rely on Object.keys throwing on non objects since ES6
// Not 100% satisfying as non objects can be interpreted as objects but no false negatives so we can live with it
if (typeof updateQuery[m] !== 'object') throw new Error(`Modifier ${m}'s argument must be an object`)
const keys = Object.keys(updateQuery[m])
keys.forEach(k => {
modifierFunctions[m](newDoc, k, updateQuery[m][k])
})
})
}
// Check result is valid and return it
checkObject(newDoc)
if (obj._id !== newDoc._id) throw new Error('You can\'t change a document\'s _id')
return newDoc
}
// ==============================================================
// Finding documents
// ==============================================================
/**
* Get a value from object with dot notation
* @param {object} obj
* @param {string} field
* @return {*}
* @alias module:model.getDotValue
*/
const getDotValue = (obj, field) => {
const fieldParts = typeof field === 'string' ? field.split('.') : field
if (!obj) return undefined // field cannot be empty so that means we should return undefined so that nothing can match
if (fieldParts.length === 0) return obj
if (fieldParts.length === 1) return obj[fieldParts[0]]
if (Array.isArray(obj[fieldParts[0]])) {
// If the next field is an integer, return only this item of the array
const i = parseInt(fieldParts[1], 10)
if (typeof i === 'number' && !isNaN(i)) return getDotValue(obj[fieldParts[0]][i], fieldParts.slice(2))
// Return the array of values
return obj[fieldParts[0]].map(el => getDotValue(el, fieldParts.slice(1)))
} else return getDotValue(obj[fieldParts[0]], fieldParts.slice(1))
}
/**
* Get dot values for either a bunch of fields or just one.
*/
const getDotValues = (obj, fields) => {
if (!Array.isArray(fields)) throw new Error('fields must be an Array')
if (fields.length > 1) {
const key = {}
for (const field of fields) {
key[field] = getDotValue(obj, field)
}
return key
} else return getDotValue(obj, fields[0])
}
/**
* Check whether 'things' are equal
* Things are defined as any native types (string, number, boolean, null, date) and objects
* In the case of object, we check deep equality
* Returns true if they are, false otherwise
* @param {*} a
* @param {*} a
* @return {boolean}
* @alias module:model.areThingsEqual
*/
const areThingsEqual = (a, b) => {
// Strings, booleans, numbers, null
if (
a === null ||
typeof a === 'string' ||
typeof a === 'boolean' ||
typeof a === 'number' ||
b === null ||
typeof b === 'string' ||
typeof b === 'boolean' ||
typeof b === 'number'
) return a === b
// Dates
if (isDate(a) || isDate(b)) return isDate(a) && isDate(b) && a.getTime() === b.getTime()
// Arrays (no match since arrays are used as a $in)
// undefined (no match since they mean field doesn't exist and can't be serialized)
if (
(!(Array.isArray(a) && Array.isArray(b)) && (Array.isArray(a) || Array.isArray(b))) ||
a === undefined || b === undefined
) return false
// General objects (check for deep equality)
// a and b should be objects at this point
let aKeys
let bKeys
try {
aKeys = Object.keys(a)
bKeys = Object.keys(b)
} catch (e) {
return false
}
if (aKeys.length !== bKeys.length) return false
for (const el of aKeys) {
if (bKeys.indexOf(el) === -1) return false
if (!areThingsEqual(a[el], b[el])) return false
}
return true
}
/**
* Check that two values are comparable
* @param {*} a
* @param {*} a
* @return {boolean}
* @private
*/
const areComparable = (a, b) => {
if (
typeof a !== 'string' &&
typeof a !== 'number' &&
!isDate(a) &&
typeof b !== 'string' &&
typeof b !== 'number' &&
!isDate(b)
) return false
if (typeof a !== typeof b) return false
return true
}
/**
* @callback comparisonOperator
* Arithmetic and comparison operators
* @param {*} a Value in the object
* @param {*} b Value in the query
* @return {boolean}
*/
/**
* @enum {comparisonOperator}
*/
const comparisonFunctions = {
/** Lower than */
$lt: (a, b) => areComparable(a, b) && a < b,
/** Lower than or equals */
$lte: (a, b) => areComparable(a, b) && a <= b,
/** Greater than */
$gt: (a, b) => areComparable(a, b) && a > b,
/** Greater than or equals */
$gte: (a, b) => areComparable(a, b) && a >= b,
/** Does not equal */
$ne: (a, b) => a === undefined || !areThingsEqual(a, b),
/** Is in Array */
$in: (a, b) => {
if (!Array.isArray(b)) throw new Error('$in operator called with a non-array')
for (const el of b) {
if (areThingsEqual(a, el)) return true
}
return false
},
/** Is not in Array */
$nin: (a, b) => {
if (!Array.isArray(b)) throw new Error('$nin operator called with a non-array')
return !comparisonFunctions.$in(a, b)
},
/** Matches Regexp */
$regex: (a, b) => {
if (!isRegExp(b)) throw new Error('$regex operator called with non regular expression')
if (typeof a !== 'string') return false
else return b.test(a)
},
/** Returns true if field exists */
$exists: (a, b) => {
// This will be true for all values of stat except false, null, undefined and 0
// That's strange behaviour (we should only use true/false) but that's the way Mongo does it...
if (b || b === '') b = true
else b = false
if (a === undefined) return !b
else return b
},
/** Specific to Arrays, returns true if a length equals b */
$size: (a, b) => {
if (!Array.isArray(a)) return false
if (b % 1 !== 0) throw new Error('$size operator called without an integer')
return a.length === b
},
/** Specific to Arrays, returns true if some elements of a match the query b */
$elemMatch: (a, b) => {
if (!Array.isArray(a)) return false
return a.some(el => match(el, b))
}
}
const arrayComparisonFunctions = { $size: true, $elemMatch: true }
/**
* @enum
*/
const logicalOperators = {
/**
* Match any of the subqueries
* @param {document} obj
* @param {query[]} query
* @return {boolean}
*/
$or: (obj, query) => {
if (!Array.isArray(query)) throw new Error('$or operator used without an array')
for (let i = 0; i < query.length; i += 1) {
if (match(obj, query[i])) return true
}
return false
},
/**
* Match all of the subqueries
* @param {document} obj
* @param {query[]} query
* @return {boolean}
*/
$and: (obj, query) => {
if (!Array.isArray(query)) throw new Error('$and operator used without an array')
for (let i = 0; i < query.length; i += 1) {
if (!match(obj, query[i])) return false
}
return true
},
/**
* Inverted match of the query
* @param {document} obj
* @param {query} query
* @return {boolean}
*/
$not: (obj, query) => !match(obj, query),
/**
* @callback whereCallback
* @param {document} obj
* @return {boolean}
*/
/**
* Use a function to match
* @param {document} obj
* @param {whereCallback} fn
* @return {boolean}
*/
$where: (obj, fn) => {
if (typeof fn !== 'function') throw new Error('$where operator used without a function')
const result = fn.call(obj)
if (typeof result !== 'boolean') throw new Error('$where function must return boolean')
return result
}
}
/**
* Tell if a given document matches a query
* @param {document} obj Document to check
* @param {query} query
* @return {boolean}
* @alias module:model.match
*/
const match = (obj, query) => {
// Primitive query against a primitive type
// This is a bit of a hack since we construct an object with an arbitrary key only to dereference it later
// But I don't have time for a cleaner implementation now
if (isPrimitiveType(obj) || isPrimitiveType(query)) return matchQueryPart({ needAKey: obj }, 'needAKey', query)
// Normal query
for (const queryKey in query) {
if (Object.prototype.hasOwnProperty.call(query, queryKey)) {
const queryValue = query[queryKey]
if (queryKey[0] === '$') {
if (!logicalOperators[queryKey]) throw new Error(`Unknown logical operator ${queryKey}`)
if (!logicalOperators[queryKey](obj, queryValue)) return false
} else if (!matchQueryPart(obj, queryKey, queryValue)) return false
}
}
return true
}
/**
* Match an object against a specific { key: value } part of a query
* if the treatObjAsValue flag is set, don't try to match every part separately, but the array as a whole
* @param {object} obj
* @param {string} queryKey
* @param {*} queryValue
* @param {boolean} [treatObjAsValue=false]
* @return {boolean}
* @private
*/
function matchQueryPart (obj, queryKey, queryValue, treatObjAsValue) {
const objValue = getDotValue(obj, queryKey)
// Check if the value is an array if we don't force a treatment as value
if (Array.isArray(objValue) && !treatObjAsValue) {
// If the queryValue is an array, try to perform an exact match
if (Array.isArray(queryValue)) return matchQueryPart(obj, queryKey, queryValue, true)
// Check if we are using an array-specific comparison function
if (queryValue !== null && typeof queryValue === 'object' && !isRegExp(queryValue)) {
for (const key in queryValue) {
if (Object.prototype.hasOwnProperty.call(queryValue, key) && arrayComparisonFunctions[key]) { return matchQueryPart(obj, queryKey, queryValue, true) }
}
}
// If not, treat it as an array of { obj, query } where there needs to be at least one match
for (const el of objValue) {
if (matchQueryPart({ k: el }, 'k', queryValue)) return true // k here could be any string
}
return false
}
// queryValue is an actual object. Determine whether it contains comparison operators
// or only normal fields. Mixed objects are not allowed
if (queryValue !== null && typeof queryValue === 'object' && !isRegExp(queryValue) && !Array.isArray(queryValue)) {
const keys = Object.keys(queryValue)
const firstChars = keys.map(item => item[0])
const dollarFirstChars = firstChars.filter(c => c === '$')
if (dollarFirstChars.length !== 0 && dollarFirstChars.length !== firstChars.length) throw new Error('You cannot mix operators and normal fields')
// queryValue is an object of this form: { $comparisonOperator1: value1, ... }
if (dollarFirstChars.length > 0) {
for (const key of keys) {
if (!comparisonFunctions[key]) throw new Error(`Unknown comparison function ${key}`)
if (!comparisonFunctions[key](objValue, queryValue[key])) return false
}
return true
}
}
// Using regular expressions with basic querying
if (isRegExp(queryValue)) return comparisonFunctions.$regex(objValue, queryValue)
// queryValue is either a native value or a normal object
// Basic matching is possible
return areThingsEqual(objValue, queryValue)
}
// Interface
module.exports.serialize = serialize
module.exports.deserialize = deserialize
module.exports.deepCopy = deepCopy
module.exports.checkObject = checkObject
module.exports.isPrimitiveType = isPrimitiveType
module.exports.modify = modify
module.exports.getDotValue = getDotValue
module.exports.getDotValues = getDotValues
module.exports.match = match
module.exports.areThingsEqual = areThingsEqual
module.exports.compareThings = compareThings
+383
View File
@@ -0,0 +1,383 @@
const { deprecate } = require('util')
const byline = require('./byline')
const Index = require('./indexes.js')
const model = require('./model.js')
const storage = require('./storage.js')
const Waterfall = require('./waterfall.js')
const DEFAULT_DIR_MODE = 0o755
const DEFAULT_FILE_MODE = 0o644
/**
* Under the hood, NeDB's persistence uses an append-only format, meaning that all
* updates and deletes actually result in lines added at the end of the datafile,
* for performance reasons. The database is automatically compacted (i.e. put back
* in the one-line-per-document format) every time you load each database within
* your application.
*
* Persistence handles the compaction exposed in the Datastore {@link Datastore#compactDatafileAsync},
* {@link Datastore#setAutocompactionInterval}.
*
* Since version 3.0.0, using {@link Datastore.persistence} methods manually is deprecated.
*
* Compaction takes a bit of time (not too much: 130ms for 50k
* records on a typical development machine) and no other operation can happen when
* it does, so most projects actually don't need to use it.
*
* Compaction will also immediately remove any documents whose data line has become
* corrupted, assuming that the total percentage of all corrupted documents in that
* database still falls below the specified `corruptAlertThreshold` option's value.
*
* Durability works similarly to major databases: compaction forces the OS to
* physically flush data to disk, while appends to the data file do not (the OS is
* responsible for flushing the data). That guarantees that a server crash can
* never cause complete data loss, while preserving performance. The worst that can
* happen is a crash between two syncs, causing a loss of all data between the two
* syncs. Usually syncs are 30 seconds appart so that's at most 30 seconds of
* data. [This post by Antirez on Redis persistence](http://oldblog.antirez.com/post/redis-persistence-demystified.html)
* explains this in more details, NeDB being very close to Redis AOF persistence
* with `appendfsync` option set to `no`.
*/
class Persistence {
/**
* Create a new Persistence object for database options.db
* @param {Datastore} options.db
* @param {Number} [options.corruptAlertThreshold] Optional, threshold after which an alert is thrown if too much data is corrupt
* @param {serializationHook} [options.beforeDeserialization] Hook you can use to transform data after it was serialized and before it is written to disk.
* @param {serializationHook} [options.afterSerialization] Inverse of `afterSerialization`.
* @param {object} [options.modes] Modes to use for FS permissions. Will not work on Windows.
* @param {number} [options.modes.fileMode=0o644] Mode to use for files.
* @param {number} [options.modes.dirMode=0o755] Mode to use for directories.
*/
constructor (options) {
this.db = options.db
this.inMemoryOnly = this.db.inMemoryOnly
this.filename = this.db.filename
this.corruptAlertThreshold = options.corruptAlertThreshold !== undefined ? options.corruptAlertThreshold : 0.1
this.modes = options.modes !== undefined
? options.modes
: {
fileMode: DEFAULT_FILE_MODE,
dirMode: DEFAULT_DIR_MODE
}
if (this.modes.fileMode === undefined) this.modes.fileMode = DEFAULT_FILE_MODE
if (this.modes.dirMode === undefined) this.modes.dirMode = DEFAULT_DIR_MODE
if (
!this.inMemoryOnly &&
this.filename &&
this.filename.charAt(this.filename.length - 1) === '~'
) throw new Error('The datafile name can\'t end with a ~, which is reserved for crash safe backup files')
// After serialization and before deserialization hooks with some basic sanity checks
if (
options.afterSerialization &&
!options.beforeDeserialization
) throw new Error('Serialization hook defined but deserialization hook undefined, cautiously refusing to start NeDB to prevent dataloss')
if (
!options.afterSerialization &&
options.beforeDeserialization
) throw new Error('Serialization hook undefined but deserialization hook defined, cautiously refusing to start NeDB to prevent dataloss')
// They are wrapped with an async function to ensure that if the hooks are synchronous they won't trigger an
// uncaught exception at runtime
this.afterSerialization = async (s) => (options.afterSerialization || (x => x))(s)
this.beforeDeserialization = async (s) => (options.beforeDeserialization || (x => x))(s)
}
/**
* Internal version without using the {@link Datastore#executor} of {@link Datastore#compactDatafileAsync}, use it instead.
* @return {Promise<void>}
* @private
*/
async persistCachedDatabaseAsync () {
const lines = []
if (this.inMemoryOnly) return
for (const doc of this.db.getAllData()) {
lines.push(await this.afterSerialization(model.serialize(doc)))
}
for (const fieldName of Object.keys(this.db.indexes)) {
if (fieldName !== '_id') { // The special _id index is managed by datastore.js, the others need to be persisted
lines.push(await this.afterSerialization(model.serialize({
$$indexCreated: {
fieldName: this.db.indexes[fieldName].fieldName,
unique: this.db.indexes[fieldName].unique,
sparse: this.db.indexes[fieldName].sparse
}
})))
}
}
await storage.crashSafeWriteFileLinesAsync(this.filename, lines, this.modes)
this.db.emit('compaction.done')
}
/**
* @see Datastore#compactDatafile
* @deprecated
* @param {NoParamCallback} [callback = () => {}]
* @see Persistence#compactDatafileAsync
*/
compactDatafile (callback) {
deprecate(_callback => this.db.compactDatafile(_callback), '@seald-io/nedb: calling Datastore#persistence#compactDatafile is deprecated, please use Datastore#compactDatafile, it will be removed in the next major version.')(callback)
}
/**
* @see Datastore#setAutocompactionInterval
* @deprecated
*/
setAutocompactionInterval (interval) {
deprecate(_interval => this.db.setAutocompactionInterval(_interval), '@seald-io/nedb: calling Datastore#persistence#setAutocompactionInterval is deprecated, please use Datastore#setAutocompactionInterval, it will be removed in the next major version.')(interval)
}
/**
* @see Datastore#stopAutocompaction
* @deprecated
*/
stopAutocompaction () {
deprecate(() => this.db.stopAutocompaction(), '@seald-io/nedb: calling Datastore#persistence#stopAutocompaction is deprecated, please use Datastore#stopAutocompaction, it will be removed in the next major version.')()
}
/**
* Persist new state for the given newDocs (can be insertion, update or removal)
* Use an append-only format
*
* Do not use directly, it should only used by a {@link Datastore} instance.
* @param {document[]} newDocs Can be empty if no doc was updated/removed
* @return {Promise}
* @private
*/
async persistNewStateAsync (newDocs) {
let toPersist = ''
// In-memory only datastore
if (this.inMemoryOnly) return
for (const doc of newDocs) {
toPersist += await this.afterSerialization(model.serialize(doc)) + '\n'
}
if (toPersist.length === 0) return
await storage.appendFileAsync(this.filename, toPersist, { encoding: 'utf8', mode: this.modes.fileMode })
}
/**
* @typedef rawIndex
* @property {string} fieldName
* @property {boolean} [unique]
* @property {boolean} [sparse]
*/
/**
* From a database's raw data, return the corresponding machine understandable collection.
*
* Do not use directly, it should only used by a {@link Datastore} instance.
* @param {string} rawData database file
* @return {{data: document[], indexes: Object.<string, rawIndex>}}
* @private
*/
async treatRawData (rawData) {
const data = rawData
.split('\n')
.filter(datum => datum !== '')
.map(async datum => model.deserialize(await this.beforeDeserialization(datum)))
const dataById = {}
const indexes = {}
const dataLength = data.length
// Last line of every data file is usually blank so not really corrupt
let corruptItems = 0
for (const docToAwait of data) {
try {
const doc = await docToAwait
if (doc._id) {
if (doc.$$deleted === true) delete dataById[doc._id]
else dataById[doc._id] = doc
} else if (doc.$$indexCreated && doc.$$indexCreated.fieldName != null) indexes[doc.$$indexCreated.fieldName] = doc.$$indexCreated
else if (typeof doc.$$indexRemoved === 'string') delete indexes[doc.$$indexRemoved]
} catch (e) {
corruptItems += 1
}
}
// A bit lenient on corruption
if (dataLength > 0) {
const corruptionRate = corruptItems / dataLength
if (corruptionRate > this.corruptAlertThreshold) {
const error = new Error(`${Math.floor(100 * corruptionRate)}% of the data file is corrupt, more than given corruptAlertThreshold (${Math.floor(100 * this.corruptAlertThreshold)}%). Cautiously refusing to start NeDB to prevent dataloss.`)
error.corruptionRate = corruptionRate
error.corruptItems = corruptItems
error.dataLength = dataLength
throw error
}
}
const tdata = Object.values(dataById)
return { data: tdata, indexes }
}
/**
* From a database's raw data stream, return the corresponding machine understandable collection
* Is only used by a {@link Datastore} instance.
*
* Is only used in the Node.js version, since [React-Native]{@link module:storageReactNative} &
* [browser]{@link module:storageBrowser} storage modules don't provide an equivalent of
* {@link module:storage.readFileStream}.
*
* Do not use directly, it should only used by a {@link Datastore} instance.
* @param {Readable} rawStream
* @return {Promise<{data: document[], indexes: Object.<string, rawIndex>}>}
* @async
* @private
*/
treatRawStreamAsync (rawStream) {
return new Promise((resolve, reject) => {
const dataById = {}
const indexes = {}
let corruptItems = 0
const lineStream = byline(rawStream)
let dataLength = 0
const waterfall = new Waterfall()
lineStream.on('data', (line) => {
const deserializedPromise = this.beforeDeserialization(line) // allows to run the deserialization hook in advance to optimize
return waterfall.waterfall(async () => { // waterfall is used to preserve the order of lines
if (line === '') return
try {
const doc = model.deserialize(await deserializedPromise)
if (doc._id) {
if (doc.$$deleted === true) delete dataById[doc._id]
else dataById[doc._id] = doc
} else if (doc.$$indexCreated && doc.$$indexCreated.fieldName != null) indexes[doc.$$indexCreated.fieldName] = doc.$$indexCreated
else if (typeof doc.$$indexRemoved === 'string') delete indexes[doc.$$indexRemoved]
} catch (e) {
corruptItems += 1
}
dataLength++
})()
})
lineStream.on('end', async () => {
await waterfall.guardian // await the promises from the on('data') callbacks
// A bit lenient on corruption
if (dataLength > 0) {
const corruptionRate = corruptItems / dataLength
if (corruptionRate > this.corruptAlertThreshold) {
const error = new Error(`${Math.floor(100 * corruptionRate)}% of the data file is corrupt, more than given corruptAlertThreshold (${Math.floor(100 * this.corruptAlertThreshold)}%). Cautiously refusing to start NeDB to prevent dataloss.`)
error.corruptionRate = corruptionRate
error.corruptItems = corruptItems
error.dataLength = dataLength
reject(error, null)
return
}
}
const data = Object.values(dataById)
resolve({ data, indexes })
})
lineStream.on('error', function (err) {
reject(err, null)
})
})
}
/**
* Load the database
* 1) Create all indexes
* 2) Insert all data
* 3) Compact the database
*
* This means pulling data out of the data file or creating it if it doesn't exist
* Also, all data is persisted right away, which has the effect of compacting the database file
* This operation is very quick at startup for a big collection (60ms for ~10k docs)
*
* Do not use directly as it does not use the [Executor]{@link Datastore.executor}, use {@link Datastore#loadDatabaseAsync} instead.
* @return {Promise<void>}
* @private
*/
async loadDatabaseAsync () {
this.db._resetIndexes()
// In-memory only datastore
if (this.inMemoryOnly) return
await Persistence.ensureParentDirectoryExistsAsync(this.filename, this.modes.dirMode)
await storage.ensureDatafileIntegrityAsync(this.filename, this.modes.fileMode)
let treatedData
if (storage.readFileStream) {
// Server side
const fileStream = storage.readFileStream(this.filename, { encoding: 'utf8', mode: this.modes.fileMode })
treatedData = await this.treatRawStreamAsync(fileStream)
} else {
// Browser
const rawData = await storage.readFileAsync(this.filename, { encoding: 'utf8', mode: this.modes.fileMode })
treatedData = await this.treatRawData(rawData)
}
// Recreate all indexes in the datafile
Object.keys(treatedData.indexes).forEach(key => {
this.db.indexes[key] = new Index(treatedData.indexes[key])
})
// Fill cached database (i.e. all indexes) with data
try {
this.db._resetIndexes(treatedData.data)
} catch (e) {
this.db._resetIndexes() // Rollback any index which didn't fail
throw e
}
await this.db.persistence.persistCachedDatabaseAsync()
this.db.executor.processBuffer()
}
/**
* See {@link Datastore#dropDatabaseAsync}. This function uses {@link Datastore#executor} internally. Decorating this
* function with an {@link Executor#pushAsync} will result in a deadlock.
* @return {Promise<void>}
* @private
* @see Datastore#dropDatabaseAsync
*/
async dropDatabaseAsync () {
this.db.stopAutocompaction() // stop autocompaction
this.db.executor.ready = false // prevent queuing new tasks
this.db.executor.resetBuffer() // remove pending buffered tasks
await this.db.executor.queue.guardian // wait for the ongoing tasks to end
// remove indexes (which means remove data from memory)
this.db.indexes = {}
// add back _id index, otherwise it will fail
this.db.indexes._id = new Index({ fieldName: '_id', unique: true })
// reset TTL on indexes
this.db.ttlIndexes = {}
// remove datastore file
if (!this.db.inMemoryOnly) {
await this.db.executor.pushAsync(async () => {
if (await storage.existsAsync(this.filename)) await storage.unlinkAsync(this.filename)
}, true)
}
}
/**
* Check if a directory stat and create it on the fly if it is not the case.
* @param {string} dir
* @param {number} [mode=0o777]
* @return {Promise<void>}
* @private
*/
static async ensureParentDirectoryExistsAsync (dir, mode = DEFAULT_DIR_MODE) {
return storage.ensureParentDirectoryExistsAsync(dir, mode)
}
}
// Interface
module.exports = Persistence
+317
View File
@@ -0,0 +1,317 @@
/**
* Way data is stored for this database.
* This version is the Node.js version.
* It's essentially fs, mkdirp and crash safe write and read functions.
*
* @see module:storageBrowser
* @see module:storageReactNative
* @module storage
* @private
*/
const fs = require('fs')
const fsPromises = fs.promises
const path = require('path')
const { Readable } = require('stream')
const DEFAULT_DIR_MODE = 0o755
const DEFAULT_FILE_MODE = 0o644
/**
* Returns true if file exists.
* @param {string} file
* @return {Promise<boolean>}
* @async
* @alias module:storage.existsAsync
* @see module:storage.exists
*/
const existsAsync = file => fsPromises.access(file, fs.constants.F_OK).then(() => true, () => false)
/**
* Node.js' [fsPromises.rename]{@link https://nodejs.org/api/fs.html#fspromisesrenameoldpath-newpath}
* @function
* @param {string} oldPath
* @param {string} newPath
* @return {Promise<void>}
* @alias module:storage.renameAsync
* @async
*/
const renameAsync = fsPromises.rename
/**
* Node.js' [fsPromises.writeFile]{@link https://nodejs.org/api/fs.html#fspromiseswritefilefile-data-options}.
* @function
* @param {string} path
* @param {string} data
* @param {object} [options]
* @return {Promise<void>}
* @alias module:storage.writeFileAsync
* @async
*/
const writeFileAsync = fsPromises.writeFile
/**
* Node.js' [fs.createWriteStream]{@link https://nodejs.org/api/fs.html#fscreatewritestreampath-options}.
* @function
* @param {string} path
* @param {Object} [options]
* @return {fs.WriteStream}
* @alias module:storage.writeFileStream
*/
const writeFileStream = fs.createWriteStream
/**
* Node.js' [fsPromises.unlink]{@link https://nodejs.org/api/fs.html#fspromisesunlinkpath}.
* @function
* @param {string} path
* @return {Promise<void>}
* @async
* @alias module:storage.unlinkAsync
*/
const unlinkAsync = fsPromises.unlink
/**
* Node.js' [fsPromises.appendFile]{@link https://nodejs.org/api/fs.html#fspromisesappendfilepath-data-options}.
* @function
* @param {string} path
* @param {string} data
* @param {object} [options]
* @return {Promise<void>}
* @alias module:storage.appendFileAsync
* @async
*/
const appendFileAsync = fsPromises.appendFile
/**
* Node.js' [fsPromises.readFile]{@link https://nodejs.org/api/fs.html#fspromisesreadfilepath-options}.
* @function
* @param {string} path
* @param {object} [options]
* @return {Promise<Buffer>}
* @alias module:storage.readFileAsync
* @async
*/
const readFileAsync = fsPromises.readFile
/**
* Node.js' [fs.createReadStream]{@link https://nodejs.org/api/fs.html#fscreatereadstreampath-options}.
* @function
* @param {string} path
* @param {Object} [options]
* @return {fs.ReadStream}
* @alias module:storage.readFileStream
*/
const readFileStream = fs.createReadStream
/**
* Node.js' [fsPromises.mkdir]{@link https://nodejs.org/api/fs.html#fspromisesmkdirpath-options}.
* @function
* @param {string} path
* @param {object} options
* @return {Promise<void|string>}
* @alias module:storage.mkdirAsync
* @async
*/
const mkdirAsync = fsPromises.mkdir
/**
* Removes file if it exists.
* @param {string} file
* @return {Promise<void>}
* @alias module:storage.ensureFileDoesntExistAsync
* @async
*/
const ensureFileDoesntExistAsync = async file => {
if (await existsAsync(file)) await unlinkAsync(file)
}
/**
* Flush data in OS buffer to storage if corresponding option is set.
* @param {object|string} options If options is a string, it is assumed that the flush of the file (not dir) called options was requested
* @param {string} [options.filename]
* @param {boolean} [options.isDir = false] Optional, defaults to false
* @param {number} [options.mode = 0o644] Optional, defaults to 0o644
* @return {Promise<void>}
* @alias module:storage.flushToStorageAsync
* @async
*/
const flushToStorageAsync = async (options) => {
let filename
let flags
let mode
if (typeof options === 'string') {
filename = options
flags = 'r+'
mode = DEFAULT_FILE_MODE
} else {
filename = options.filename
flags = options.isDir ? 'r' : 'r+'
mode = options.mode !== undefined ? options.mode : DEFAULT_FILE_MODE
}
/**
* Some OSes and/or storage backends (augmented node fs) do not support fsync (FlushFileBuffers) directories,
* or calling open() on directories at all. Flushing fails silently in this case, supported by following heuristics:
* + isDir === true
* |-- open(<dir>) -> (err.code === 'EISDIR'): can't call open() on directories (eg. BrowserFS)
* `-- fsync(<dir>) -> (errFS.code === 'EPERM' || errFS.code === 'EISDIR'): can't fsync directory: permissions are checked
* on open(); EPERM error should only occur on fsync incapability and not for general lack of permissions (e.g. Windows)
*
* We can live with this as it cannot cause 100% dataloss except in the very rare event of the first time
* database is loaded and a crash happens.
*/
let filehandle, errorOnFsync, errorOnClose
try {
filehandle = await fsPromises.open(filename, flags, mode)
try {
await filehandle.sync()
} catch (errFS) {
errorOnFsync = errFS
}
} catch (error) {
if (error.code !== 'EISDIR' || !options.isDir) throw error
} finally {
try {
await filehandle.close()
} catch (errC) {
errorOnClose = errC
}
}
if ((errorOnFsync || errorOnClose) && !((errorOnFsync.code === 'EPERM' || errorOnClose.code === 'EISDIR') && options.isDir)) {
const e = new Error('Failed to flush to storage')
e.errorOnFsync = errorOnFsync
e.errorOnClose = errorOnClose
throw e
}
}
/**
* Fully write or rewrite the datafile.
* @param {string} filename
* @param {string[]} lines
* @param {number} [mode=0o644]
* @return {Promise<void>}
* @alias module:storage.writeFileLinesAsync
* @async
*/
const writeFileLinesAsync = (filename, lines, mode = DEFAULT_FILE_MODE) => new Promise((resolve, reject) => {
try {
const stream = writeFileStream(filename, { mode })
const readable = Readable.from(lines)
readable.on('data', (line) => {
try {
stream.write(line + '\n')
} catch (err) {
reject(err)
}
})
readable.on('end', () => {
stream.close(err => {
if (err) reject(err)
else resolve()
})
})
readable.on('error', err => {
reject(err)
})
stream.on('error', err => {
reject(err)
})
} catch (err) {
reject(err)
}
})
/**
* Fully write or rewrite the datafile, immune to crashes during the write operation (data will not be lost).
* @param {string} filename
* @param {string[]} lines
* @param {object} [modes={ fileMode: 0o644, dirMode: 0o755 }]
* @param {number} modes.dirMode
* @param {number} modes.fileMode
* @return {Promise<void>}
* @alias module:storage.crashSafeWriteFileLinesAsync
*/
const crashSafeWriteFileLinesAsync = async (filename, lines, modes = { fileMode: DEFAULT_FILE_MODE, dirMode: DEFAULT_DIR_MODE }) => {
const tempFilename = filename + '~'
await flushToStorageAsync({ filename: path.dirname(filename), isDir: true, mode: modes.dirMode })
const exists = await existsAsync(filename)
if (exists) await flushToStorageAsync({ filename, mode: modes.fileMode })
await writeFileLinesAsync(tempFilename, lines, modes.fileMode)
await flushToStorageAsync({ filename: tempFilename, mode: modes.fileMode })
await renameAsync(tempFilename, filename)
await flushToStorageAsync({ filename: path.dirname(filename), isDir: true, mode: modes.dirMode })
}
/**
* Ensure the datafile contains all the data, even if there was a crash during a full file write.
* @param {string} filename
* @param {number} [mode=0o644]
* @return {Promise<void>}
* @alias module:storage.ensureDatafileIntegrityAsync
*/
const ensureDatafileIntegrityAsync = async (filename, mode = DEFAULT_FILE_MODE) => {
const tempFilename = filename + '~'
const filenameExists = await existsAsync(filename)
// Write was successful
if (filenameExists) return
const oldFilenameExists = await existsAsync(tempFilename)
// New database
if (!oldFilenameExists) await writeFileAsync(filename, '', { encoding: 'utf8', mode })
// Write failed, use old version
else await renameAsync(tempFilename, filename)
}
/**
* Check if a file's parent directory exists and create it on the fly if it is not the case.
* @param {string} filename
* @param {number} mode
* @return {Promise<void>}
* @private
*/
const ensureParentDirectoryExistsAsync = async (filename, mode) => {
const dir = path.dirname(filename)
const parsedDir = path.parse(path.resolve(dir))
// this is because on Windows mkdir throws a permission error when called on the root directory of a volume
if (process.platform !== 'win32' || parsedDir.dir !== parsedDir.root || parsedDir.base !== '') {
await mkdirAsync(dir, { recursive: true, mode })
}
}
// Interface
module.exports.existsAsync = existsAsync
module.exports.renameAsync = renameAsync
module.exports.writeFileAsync = writeFileAsync
module.exports.writeFileLinesAsync = writeFileLinesAsync
module.exports.crashSafeWriteFileLinesAsync = crashSafeWriteFileLinesAsync
module.exports.appendFileAsync = appendFileAsync
module.exports.readFileAsync = readFileAsync
module.exports.unlinkAsync = unlinkAsync
module.exports.mkdirAsync = mkdirAsync
module.exports.readFileStream = readFileStream
module.exports.flushToStorageAsync = flushToStorageAsync
module.exports.ensureDatafileIntegrityAsync = ensureDatafileIntegrityAsync
module.exports.ensureFileDoesntExistAsync = ensureFileDoesntExistAsync
module.exports.ensureParentDirectoryExistsAsync = ensureParentDirectoryExistsAsync
+84
View File
@@ -0,0 +1,84 @@
/**
* Utility functions for all environments.
* This replaces the underscore dependency.
*
* @module utils
* @private
*/
/**
* @callback IterateeFunction
* @param {*} arg
* @return {*}
*/
/**
* Produces a duplicate-free version of the array, using === to test object equality. In particular only the first
* occurrence of each value is kept. If you want to compute unique items based on a transformation, pass an iteratee
* function.
*
* Heavily inspired by {@link https://underscorejs.org/#uniq}.
* @param {Array} array
* @param {IterateeFunction} [iteratee] transformation applied to every element before checking for duplicates. This will not
* transform the items in the result.
* @return {Array}
* @alias module:utils.uniq
*/
const uniq = (array, iteratee) => {
if (iteratee) return [...(new Map(array.map(x => [iteratee(x), x]))).values()]
else return [...new Set(array)]
}
/**
* Returns true if arg is an Object. Note that JavaScript arrays and functions are objects, while (normal) strings
* and numbers are not.
*
* Heavily inspired by {@link https://underscorejs.org/#isObject}.
* @param {*} arg
* @return {boolean}
*/
const isObject = arg => typeof arg === 'object' && arg !== null
/**
* Returns true if d is a Date.
*
* Heavily inspired by {@link https://underscorejs.org/#isDate}.
* @param {*} d
* @return {boolean}
* @alias module:utils.isDate
*/
const isDate = d => isObject(d) && Object.prototype.toString.call(d) === '[object Date]'
/**
* Returns true if re is a RegExp.
*
* Heavily inspired by {@link https://underscorejs.org/#isRegExp}.
* @param {*} re
* @return {boolean}
* @alias module:utils.isRegExp
*/
const isRegExp = re => isObject(re) && Object.prototype.toString.call(re) === '[object RegExp]'
/**
* Return a copy of the object filtered using the given keys.
*
* @param {object} object
* @param {string[]} keys
* @return {object}
*/
const pick = (object, keys) => {
return keys.reduce((obj, key) => {
if (object && Object.prototype.hasOwnProperty.call(object, key)) {
obj[key] = object[key]
}
return obj
}, {})
}
const filterIndexNames = (indexNames) => ([k, v]) => !!(typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || isDate(v) || v === null) &&
indexNames.includes(k)
module.exports.uniq = uniq
module.exports.isDate = isDate
module.exports.isRegExp = isRegExp
module.exports.pick = pick
module.exports.filterIndexNames = filterIndexNames
+48
View File
@@ -0,0 +1,48 @@
/**
* Responsible for sequentially executing actions on the database
* @private
*/
class Waterfall {
/**
* Instantiate a new Waterfall.
*/
constructor () {
/**
* This is the internal Promise object which resolves when all the tasks of the `Waterfall` are done.
*
* It will change any time `this.waterfall` is called.
*
* @type {Promise}
*/
this.guardian = Promise.resolve()
}
/**
*
* @param {AsyncFunction} func
* @return {AsyncFunction}
*/
waterfall (func) {
return (...args) => {
this.guardian = this.guardian.then(() => {
return func(...args)
.then(result => ({ error: false, result }), result => ({ error: true, result }))
})
return this.guardian.then(({ error, result }) => {
if (error) return Promise.reject(result)
else return Promise.resolve(result)
})
}
}
/**
* Shorthand for chaining a promise to the Waterfall
* @param {Promise} promise
* @return {Promise}
*/
chain (promise) {
return this.waterfall(() => promise)()
}
}
module.exports = Waterfall
+121
View File
@@ -0,0 +1,121 @@
{
"name": "@seald-io/nedb",
"version": "4.1.2",
"files": [
"lib/**/*.js",
"browser-version/**/*.js",
"index.js",
"index.d.ts"
],
"types": "index.d.ts",
"author": {
"name": "Timothée Rebours",
"email": "[email protected]",
"url": "https://www.seald.io/"
},
"contributors": [
{
"name": "Louis Chatriot",
"email": "[email protected]"
},
{
"name": "Timothée Rebours",
"email": "[email protected]",
"url": "https://www.seald.io/"
},
{
"name": "Eliot Akira",
"email": "[email protected]",
"url": "https://eliotakira.com/"
},
{
"name": " Loïc Hermann",
"email": "[email protected]"
}
],
"description": "File-based embedded data store for node.js",
"keywords": [
"database",
"datastore",
"embedded"
],
"homepage": "https://github.com/seald/nedb",
"repository": {
"type": "git",
"url": "[email protected]:seald/nedb.git"
},
"dependencies": {
"@seald-io/binary-search-tree": "^1.0.3",
"localforage": "^1.10.0",
"util": "^0.12.5"
},
"devDependencies": {
"@react-native-async-storage/async-storage": "^1.17.11",
"@types/jest": "^27.5.2",
"browser-resolve": "^2.0.0",
"chai": "^4.3.7",
"commander": "^7.2.0",
"events": "^3.3.0",
"jest": "^27.5.1",
"jsdoc-to-markdown": "^8.0.0",
"karma": "^6.4.1",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^3.1.1",
"karma-junit-reporter": "^2.0.1",
"karma-mocha": "^2.0.1",
"karma-source-map-support": "^1.4.0",
"mocha": "^10.2.0",
"mocha-junit-reporter": "^2.2.0",
"path-browserify": "^1.0.1",
"process": "^0.11.10",
"react": "^18.2.0",
"react-native": "^0.71.2",
"semver": "^7.3.8",
"source-map-loader": "^4.0.1",
"standard": "^17.0.0",
"terser-webpack-plugin": "^5.3.6",
"timers-browserify": "^2.0.12",
"ts-jest": "^27.1.5",
"typescript": "^4.9.5",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1",
"xvfb-maybe": "^0.2.1"
},
"scripts": {
"lint": "standard",
"test": "mocha --reporter spec --timeout 10000",
"build:browser": "webpack && webpack --optimization-minimize",
"pretest:browser": "npm run build:browser",
"test:browser": "xvfb-maybe karma start karma.conf.local.js",
"test:react-native": "jest test/react-native",
"test:typings": "tsc ./typings-tests.ts",
"prepublishOnly": "npm run build:browser",
"generateDocs:markdown": "jsdoc2md --no-cache -c jsdoc.conf.js --param-list-format list --files ./lib/*.js > API.md"
},
"main": "index.js",
"browser": {
"./lib/customUtils.js": "./browser-version/lib/customUtils.js",
"./lib/storage.js": "./browser-version/lib/storage.browser.js",
"./lib/byline.js": "./browser-version/lib/byline.js"
},
"react-native": {
"./lib/customUtils.js": "./browser-version/lib/customUtils.js",
"./lib/storage.js": "./browser-version/lib/storage.react-native.js",
"./lib/byline.js": "./browser-version/lib/byline.js"
},
"license": "MIT",
"publishConfig": {
"access": "public"
},
"standard": {
"ignore": [
"browser-version/out",
"**/*.ts"
]
},
"jest": {
"preset": "ts-jest",
"testEnvironment": "node",
"resolver": "<rootDir>/test/react-native/resolver.js"
}
}
+250
View File
@@ -0,0 +1,250 @@
2.0.0 / 2024-08-31
==================
* Drop node <18 support
* deps: mime-types@^3.0.0
* deps: negotiator@^1.0.0
1.3.8 / 2022-02-02
==================
* deps: mime-types@~2.1.34
- deps: mime-db@~1.51.0
* deps: negotiator@0.6.3
1.3.7 / 2019-04-29
==================
* deps: negotiator@0.6.2
- Fix sorting charset, encoding, and language with extra parameters
1.3.6 / 2019-04-28
==================
* deps: mime-types@~2.1.24
- deps: mime-db@~1.40.0
1.3.5 / 2018-02-28
==================
* deps: mime-types@~2.1.18
- deps: mime-db@~1.33.0
1.3.4 / 2017-08-22
==================
* deps: mime-types@~2.1.16
- deps: mime-db@~1.29.0
1.3.3 / 2016-05-02
==================
* deps: mime-types@~2.1.11
- deps: mime-db@~1.23.0
* deps: negotiator@0.6.1
- perf: improve `Accept` parsing speed
- perf: improve `Accept-Charset` parsing speed
- perf: improve `Accept-Encoding` parsing speed
- perf: improve `Accept-Language` parsing speed
1.3.2 / 2016-03-08
==================
* deps: mime-types@~2.1.10
- Fix extension of `application/dash+xml`
- Update primary extension for `audio/mp4`
- deps: mime-db@~1.22.0
1.3.1 / 2016-01-19
==================
* deps: mime-types@~2.1.9
- deps: mime-db@~1.21.0
1.3.0 / 2015-09-29
==================
* deps: mime-types@~2.1.7
- deps: mime-db@~1.19.0
* deps: negotiator@0.6.0
- Fix including type extensions in parameters in `Accept` parsing
- Fix parsing `Accept` parameters with quoted equals
- Fix parsing `Accept` parameters with quoted semicolons
- Lazy-load modules from main entry point
- perf: delay type concatenation until needed
- perf: enable strict mode
- perf: hoist regular expressions
- perf: remove closures getting spec properties
- perf: remove a closure from media type parsing
- perf: remove property delete from media type parsing
1.2.13 / 2015-09-06
===================
* deps: mime-types@~2.1.6
- deps: mime-db@~1.18.0
1.2.12 / 2015-07-30
===================
* deps: mime-types@~2.1.4
- deps: mime-db@~1.16.0
1.2.11 / 2015-07-16
===================
* deps: mime-types@~2.1.3
- deps: mime-db@~1.15.0
1.2.10 / 2015-07-01
===================
* deps: mime-types@~2.1.2
- deps: mime-db@~1.14.0
1.2.9 / 2015-06-08
==================
* deps: mime-types@~2.1.1
- perf: fix deopt during mapping
1.2.8 / 2015-06-07
==================
* deps: mime-types@~2.1.0
- deps: mime-db@~1.13.0
* perf: avoid argument reassignment & argument slice
* perf: avoid negotiator recursive construction
* perf: enable strict mode
* perf: remove unnecessary bitwise operator
1.2.7 / 2015-05-10
==================
* deps: negotiator@0.5.3
- Fix media type parameter matching to be case-insensitive
1.2.6 / 2015-05-07
==================
* deps: mime-types@~2.0.11
- deps: mime-db@~1.9.1
* deps: negotiator@0.5.2
- Fix comparing media types with quoted values
- Fix splitting media types with quoted commas
1.2.5 / 2015-03-13
==================
* deps: mime-types@~2.0.10
- deps: mime-db@~1.8.0
1.2.4 / 2015-02-14
==================
* Support Node.js 0.6
* deps: mime-types@~2.0.9
- deps: mime-db@~1.7.0
* deps: negotiator@0.5.1
- Fix preference sorting to be stable for long acceptable lists
1.2.3 / 2015-01-31
==================
* deps: mime-types@~2.0.8
- deps: mime-db@~1.6.0
1.2.2 / 2014-12-30
==================
* deps: mime-types@~2.0.7
- deps: mime-db@~1.5.0
1.2.1 / 2014-12-30
==================
* deps: mime-types@~2.0.5
- deps: mime-db@~1.3.1
1.2.0 / 2014-12-19
==================
* deps: negotiator@0.5.0
- Fix list return order when large accepted list
- Fix missing identity encoding when q=0 exists
- Remove dynamic building of Negotiator class
1.1.4 / 2014-12-10
==================
* deps: mime-types@~2.0.4
- deps: mime-db@~1.3.0
1.1.3 / 2014-11-09
==================
* deps: mime-types@~2.0.3
- deps: mime-db@~1.2.0
1.1.2 / 2014-10-14
==================
* deps: negotiator@0.4.9
- Fix error when media type has invalid parameter
1.1.1 / 2014-09-28
==================
* deps: mime-types@~2.0.2
- deps: mime-db@~1.1.0
* deps: negotiator@0.4.8
- Fix all negotiations to be case-insensitive
- Stable sort preferences of same quality according to client order
1.1.0 / 2014-09-02
==================
* update `mime-types`
1.0.7 / 2014-07-04
==================
* Fix wrong type returned from `type` when match after unknown extension
1.0.6 / 2014-06-24
==================
* deps: negotiator@0.4.7
1.0.5 / 2014-06-20
==================
* fix crash when unknown extension given
1.0.4 / 2014-06-19
==================
* use `mime-types`
1.0.3 / 2014-06-11
==================
* deps: negotiator@0.4.6
- Order by specificity when quality is the same
1.0.2 / 2014-05-29
==================
* Fix interpretation when header not in request
* deps: pin negotiator@0.4.5
1.0.1 / 2014-01-18
==================
* Identity encoding isn't always acceptable
* deps: negotiator@~0.4.0
1.0.0 / 2013-12-27
==================
* Genesis
+23
View File
@@ -0,0 +1,23 @@
(The MIT License)
Copyright (c) 2014 Jonathan Ong <[email protected]>
Copyright (c) 2015 Douglas Christopher Wilson <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+140
View File
@@ -0,0 +1,140 @@
# accepts
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][github-actions-ci-image]][github-actions-ci-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator).
Extracted from [koa](https://www.npmjs.com/package/koa) for general use.
In addition to negotiator, it allows:
- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])`
as well as `('text/html', 'application/json')`.
- Allows type shorthands such as `json`.
- Returns `false` when no types match
- Treats non-existent headers as `*`
## Installation
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
```sh
$ npm install accepts
```
## API
```js
var accepts = require('accepts')
```
### accepts(req)
Create a new `Accepts` object for the given `req`.
#### .charset(charsets)
Return the first accepted charset. If nothing in `charsets` is accepted,
then `false` is returned.
#### .charsets()
Return the charsets that the request accepts, in the order of the client's
preference (most preferred first).
#### .encoding(encodings)
Return the first accepted encoding. If nothing in `encodings` is accepted,
then `false` is returned.
#### .encodings()
Return the encodings that the request accepts, in the order of the client's
preference (most preferred first).
#### .language(languages)
Return the first accepted language. If nothing in `languages` is accepted,
then `false` is returned.
#### .languages()
Return the languages that the request accepts, in the order of the client's
preference (most preferred first).
#### .type(types)
Return the first accepted type (and it is returned as the same text as what
appears in the `types` array). If nothing in `types` is accepted, then `false`
is returned.
The `types` array can contain full MIME types or file extensions. Any value
that is not a full MIME type is passed to `require('mime-types').lookup`.
#### .types()
Return the types that the request accepts, in the order of the client's
preference (most preferred first).
## Examples
### Simple type negotiation
This simple example shows how to use `accepts` to return a different typed
respond body based on what the client wants to accept. The server lists it's
preferences in order and will get back the best match between the client and
server.
```js
var accepts = require('accepts')
var http = require('http')
function app (req, res) {
var accept = accepts(req)
// the order of this list is significant; should be server preferred order
switch (accept.type(['json', 'html'])) {
case 'json':
res.setHeader('Content-Type', 'application/json')
res.write('{"hello":"world!"}')
break
case 'html':
res.setHeader('Content-Type', 'text/html')
res.write('<b>hello, world!</b>')
break
default:
// the fallback is text/plain, so no need to specify it above
res.setHeader('Content-Type', 'text/plain')
res.write('hello, world!')
break
}
res.end()
}
http.createServer(app).listen(3000)
```
You can test this out with the cURL program:
```sh
curl -I -H'Accept: text/html' http://localhost:3000/
```
## License
[MIT](LICENSE)
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master
[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master
[github-actions-ci-image]: https://badgen.net/github/checks/jshttp/accepts/master?label=ci
[github-actions-ci-url]: https://github.com/jshttp/accepts/actions/workflows/ci.yml
[node-version-image]: https://badgen.net/npm/node/accepts
[node-version-url]: https://nodejs.org/en/download
[npm-downloads-image]: https://badgen.net/npm/dm/accepts
[npm-url]: https://npmjs.org/package/accepts
[npm-version-image]: https://badgen.net/npm/v/accepts
+238
View File
@@ -0,0 +1,238 @@
/*!
* accepts
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var Negotiator = require('negotiator')
var mime = require('mime-types')
/**
* Module exports.
* @public
*/
module.exports = Accepts
/**
* Create a new Accepts object for the given req.
*
* @param {object} req
* @public
*/
function Accepts (req) {
if (!(this instanceof Accepts)) {
return new Accepts(req)
}
this.headers = req.headers
this.negotiator = new Negotiator(req)
}
/**
* Check if the given `type(s)` is acceptable, returning
* the best match when true, otherwise `undefined`, in which
* case you should respond with 406 "Not Acceptable".
*
* The `type` value may be a single mime type string
* such as "application/json", the extension name
* such as "json" or an array `["json", "html", "text/plain"]`. When a list
* or array is given the _best_ match, if any is returned.
*
* Examples:
*
* // Accept: text/html
* this.types('html');
* // => "html"
*
* // Accept: text/*, application/json
* this.types('html');
* // => "html"
* this.types('text/html');
* // => "text/html"
* this.types('json', 'text');
* // => "json"
* this.types('application/json');
* // => "application/json"
*
* // Accept: text/*, application/json
* this.types('image/png');
* this.types('png');
* // => undefined
*
* // Accept: text/*;q=.5, application/json
* this.types(['html', 'json']);
* this.types('html', 'json');
* // => "json"
*
* @param {String|Array} types...
* @return {String|Array|Boolean}
* @public
*/
Accepts.prototype.type =
Accepts.prototype.types = function (types_) {
var types = types_
// support flattened arguments
if (types && !Array.isArray(types)) {
types = new Array(arguments.length)
for (var i = 0; i < types.length; i++) {
types[i] = arguments[i]
}
}
// no types, return all requested types
if (!types || types.length === 0) {
return this.negotiator.mediaTypes()
}
// no accept header, return first given type
if (!this.headers.accept) {
return types[0]
}
var mimes = types.map(extToMime)
var accepts = this.negotiator.mediaTypes(mimes.filter(validMime))
var first = accepts[0]
return first
? types[mimes.indexOf(first)]
: false
}
/**
* Return accepted encodings or best fit based on `encodings`.
*
* Given `Accept-Encoding: gzip, deflate`
* an array sorted by quality is returned:
*
* ['gzip', 'deflate']
*
* @param {String|Array} encodings...
* @return {String|Array}
* @public
*/
Accepts.prototype.encoding =
Accepts.prototype.encodings = function (encodings_) {
var encodings = encodings_
// support flattened arguments
if (encodings && !Array.isArray(encodings)) {
encodings = new Array(arguments.length)
for (var i = 0; i < encodings.length; i++) {
encodings[i] = arguments[i]
}
}
// no encodings, return all requested encodings
if (!encodings || encodings.length === 0) {
return this.negotiator.encodings()
}
return this.negotiator.encodings(encodings)[0] || false
}
/**
* Return accepted charsets or best fit based on `charsets`.
*
* Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
* an array sorted by quality is returned:
*
* ['utf-8', 'utf-7', 'iso-8859-1']
*
* @param {String|Array} charsets...
* @return {String|Array}
* @public
*/
Accepts.prototype.charset =
Accepts.prototype.charsets = function (charsets_) {
var charsets = charsets_
// support flattened arguments
if (charsets && !Array.isArray(charsets)) {
charsets = new Array(arguments.length)
for (var i = 0; i < charsets.length; i++) {
charsets[i] = arguments[i]
}
}
// no charsets, return all requested charsets
if (!charsets || charsets.length === 0) {
return this.negotiator.charsets()
}
return this.negotiator.charsets(charsets)[0] || false
}
/**
* Return accepted languages or best fit based on `langs`.
*
* Given `Accept-Language: en;q=0.8, es, pt`
* an array sorted by quality is returned:
*
* ['es', 'pt', 'en']
*
* @param {String|Array} langs...
* @return {Array|String}
* @public
*/
Accepts.prototype.lang =
Accepts.prototype.langs =
Accepts.prototype.language =
Accepts.prototype.languages = function (languages_) {
var languages = languages_
// support flattened arguments
if (languages && !Array.isArray(languages)) {
languages = new Array(arguments.length)
for (var i = 0; i < languages.length; i++) {
languages[i] = arguments[i]
}
}
// no languages, return all requested languages
if (!languages || languages.length === 0) {
return this.negotiator.languages()
}
return this.negotiator.languages(languages)[0] || false
}
/**
* Convert extnames to mime.
*
* @param {String} type
* @return {String}
* @private
*/
function extToMime (type) {
return type.indexOf('/') === -1
? mime.lookup(type)
: type
}
/**
* Check if mime is valid.
*
* @param {String} type
* @return {Boolean}
* @private
*/
function validMime (type) {
return typeof type === 'string'
}
+47
View File
@@ -0,0 +1,47 @@
{
"name": "accepts",
"description": "Higher-level content negotiation",
"version": "2.0.0",
"contributors": [
"Douglas Christopher Wilson <[email protected]>",
"Jonathan Ong <[email protected]> (http://jongleberry.com)"
],
"license": "MIT",
"repository": "jshttp/accepts",
"dependencies": {
"mime-types": "^3.0.0",
"negotiator": "^1.0.0"
},
"devDependencies": {
"deep-equal": "1.0.1",
"eslint": "7.32.0",
"eslint-config-standard": "14.1.1",
"eslint-plugin-import": "2.25.4",
"eslint-plugin-markdown": "2.2.1",
"eslint-plugin-node": "11.1.0",
"eslint-plugin-promise": "4.3.1",
"eslint-plugin-standard": "4.1.0",
"mocha": "9.2.0",
"nyc": "15.1.0"
},
"files": [
"LICENSE",
"HISTORY.md",
"index.js"
],
"engines": {
"node": ">= 0.6"
},
"scripts": {
"lint": "eslint .",
"test": "mocha --reporter spec --check-leaks --bail test/",
"test-ci": "nyc --reporter=lcov --reporter=text npm test",
"test-cov": "nyc --reporter=html --reporter=text npm test"
},
"keywords": [
"content",
"negotiation",
"accept",
"accepts"
]
}
+5
View File
@@ -0,0 +1,5 @@
{
"root": true,
"extends": "@ljharb",
}
+12
View File
@@ -0,0 +1,12 @@
# These are supported funding model platforms
github: [ljharb]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: npm/available-typed-arrays
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+9
View File
@@ -0,0 +1,9 @@
{
"all": true,
"check-coverage": false,
"reporter": ["text-summary", "text", "html", "json"],
"exclude": [
"coverage",
"test"
]
}
+100
View File
@@ -0,0 +1,100 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.0.7](https://github.com/inspect-js/available-typed-arrays/compare/v1.0.6...v1.0.7) - 2024-02-19
### Commits
- [Refactor] use `possible-typed-array-names` [`ac86abf`](https://github.com/inspect-js/available-typed-arrays/commit/ac86abfd64c4b633fd6523cc4193f1913fd22666)
## [v1.0.6](https://github.com/inspect-js/available-typed-arrays/compare/v1.0.5...v1.0.6) - 2024-01-31
### Commits
- [actions] reuse common workflows [`1850353`](https://github.com/inspect-js/available-typed-arrays/commit/1850353ded0ceb4d02d9d05649da5b7f3a28c89f)
- [meta] use `npmignore` to autogenerate an npmignore file [`5c7de12`](https://github.com/inspect-js/available-typed-arrays/commit/5c7de120d22a5c35f703ba3f0b5287e5c5f38af6)
- [patch] add types [`fcfb0ea`](https://github.com/inspect-js/available-typed-arrays/commit/fcfb0ea21c9dc8459d68f8bb26679abb0bec71ca)
- [actions] update codecov uploader [`d844945`](https://github.com/inspect-js/available-typed-arrays/commit/d84494596881a298aabde9bd87e538ce10c6cd01)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `array.prototype.every`, `safe-publish-latest`, `tape` [`a2be6f4`](https://github.com/inspect-js/available-typed-arrays/commit/a2be6f482010e920692d8f65fe1f193dbb73004d)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`b283a3e`](https://github.com/inspect-js/available-typed-arrays/commit/b283a3e2176fbe8e431a27e20df21c831f216d5a)
- [actions] update rebase action to use reusable workflow [`0ad1f2d`](https://github.com/inspect-js/available-typed-arrays/commit/0ad1f2d82b11713ee48d9b37cb73fcc891bd9f4a)
- [Dev Deps] update `@ljharb/eslint-config`, `array.prototype.every`, `aud`, `tape` [`cd36e81`](https://github.com/inspect-js/available-typed-arrays/commit/cd36e8131076dd4e67a88b259f829067fa56c139)
- [meta] simplify "exports" [`f696e5f`](https://github.com/inspect-js/available-typed-arrays/commit/f696e5ff9ded838e192ade4e8550a890c4f35eb0)
- [Dev Deps] update `aud`, `npmignore`, `tape` [`bf20080`](https://github.com/inspect-js/available-typed-arrays/commit/bf200809aea3107b31fc8817122c693e099be30e)
## [v1.0.5](https://github.com/inspect-js/available-typed-arrays/compare/v1.0.4...v1.0.5) - 2021-08-30
### Fixed
- [Refactor] use `globalThis` if available [`#12`](https://github.com/inspect-js/available-typed-arrays/issues/12)
### Commits
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`1199790`](https://github.com/inspect-js/available-typed-arrays/commit/1199790ab5841517ad04827fab3f135d2dc5cfb7)
## [v1.0.4](https://github.com/inspect-js/available-typed-arrays/compare/v1.0.3...v1.0.4) - 2021-05-25
### Commits
- [Refactor] Remove `array.prototype.filter` dependency [`f39c90e`](https://github.com/inspect-js/available-typed-arrays/commit/f39c90ecb1907de28ee2d3577b7da37ae12aac56)
- [Dev Deps] update `eslint`, `auto-changelog` [`b2e3a03`](https://github.com/inspect-js/available-typed-arrays/commit/b2e3a035e8cd3ddfd7b565249e1651c6419a34d0)
- [meta] create `FUNDING.yml` [`8c0e758`](https://github.com/inspect-js/available-typed-arrays/commit/8c0e758c6ec80adbb3770554653cdc3aa16beb55)
- [Tests] fix harmony test matrix [`ef96549`](https://github.com/inspect-js/available-typed-arrays/commit/ef96549df171776267529413240a2219cb59d5ce)
- [meta] add `sideEffects` flag [`288cca0`](https://github.com/inspect-js/available-typed-arrays/commit/288cca0fbd214bec706447851bb8bccc4b899a48)
## [v1.0.3](https://github.com/inspect-js/available-typed-arrays/compare/v1.0.2...v1.0.3) - 2021-05-19
### Commits
- [Tests] migrate tests to Github Actions [`3ef082c`](https://github.com/inspect-js/available-typed-arrays/commit/3ef082caaa153b49f4c37c85bbd5c4b13fe4f638)
- [meta] do not publish github action workflow files [`fd95ffd`](https://github.com/inspect-js/available-typed-arrays/commit/fd95ffdaca759eca81cb4c5d5772ee863dfea501)
- [actions] use `node/install` instead of `node/run`; use `codecov` action [`eb6bd65`](https://github.com/inspect-js/available-typed-arrays/commit/eb6bd659a31c92a6a178c71a89fe0d5261413e6c)
- [Tests] run `nyc` on all tests [`636c946`](https://github.com/inspect-js/available-typed-arrays/commit/636c94657b532599ef90a214aaa12639d11b0161)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`70a3b61`](https://github.com/inspect-js/available-typed-arrays/commit/70a3b61367b318fb883c2f35b8f2d539849a23b6)
- [actions] add "Allow Edits" workflow [`bd09c45`](https://github.com/inspect-js/available-typed-arrays/commit/bd09c45299e396fa5bbd5be4c58b1aedcb372a82)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `array.prototype.every`, `aud`, `tape` [`8f97523`](https://github.com/inspect-js/available-typed-arrays/commit/8f9752308390a79068cd431436bbfd77bca15647)
- [readme] fix URLs [`75418e2`](https://github.com/inspect-js/available-typed-arrays/commit/75418e20b57f4ad5e65d8c2e1864efd14eaa2e65)
- [readme] add actions and codecov badges [`4a8bc30`](https://github.com/inspect-js/available-typed-arrays/commit/4a8bc30af2ce1f48e2b28ab3db5be9589bd6f2d0)
- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud` [`65198ac`](https://github.com/inspect-js/available-typed-arrays/commit/65198ace335a013ef49b6bd722bc80bbbc6be784)
- [actions] update workflows [`7f816eb`](https://github.com/inspect-js/available-typed-arrays/commit/7f816eb231131e53ced2572ba6c6c6a00f975789)
- [Refactor] use `array.prototype.filter` instead of `array-filter` [`2dd1038`](https://github.com/inspect-js/available-typed-arrays/commit/2dd1038d71ce48b5650687691cf8fe09795a6d30)
- [actions] switch Automatic Rease workflow to `pull_request_target` event [`9b45e91`](https://github.com/inspect-js/available-typed-arrays/commit/9b45e914fcb08bdaaaa0166b41716e51f400d1c6)
- [Dev Deps] update `auto-changelog`, `tape` [`0003a5b`](https://github.com/inspect-js/available-typed-arrays/commit/0003a5b122a0724db5499c114104eeeb396b2f67)
- [meta] use `prepublishOnly` script for npm 7+ [`d884dd1`](https://github.com/inspect-js/available-typed-arrays/commit/d884dd1c1117411f35d9fbc07f513a1a85ccdead)
- [readme] remove travis badge [`9da2b3c`](https://github.com/inspect-js/available-typed-arrays/commit/9da2b3c29706340fada995137aba12cfae4d6f37)
- [Dev Deps] update `auto-changelog`; add `aud` [`41b1336`](https://github.com/inspect-js/available-typed-arrays/commit/41b13369c71b0e3e57b9de0f4fb1e4d67950d74a)
- [Tests] only audit prod deps [`2571826`](https://github.com/inspect-js/available-typed-arrays/commit/2571826a5d121eeeeccf4c711e3f9e4616685d50)
## [v1.0.2](https://github.com/inspect-js/available-typed-arrays/compare/v1.0.1...v1.0.2) - 2020-01-26
### Commits
- [actions] add automatic rebasing / merge commit blocking [`3229a74`](https://github.com/inspect-js/available-typed-arrays/commit/3229a74bda60f24e2257efc40ddff9a3ce98de76)
- [Dev Deps] update `@ljharb/eslint-config` [`9579abe`](https://github.com/inspect-js/available-typed-arrays/commit/9579abecc196088561d3aedf27cad45b56f8e18b)
- [Fix] remove `require` condition to avoid experimental warning [`2cade6b`](https://github.com/inspect-js/available-typed-arrays/commit/2cade6b56d6a508a950c7da27d038bee496e716b)
## [v1.0.1](https://github.com/inspect-js/available-typed-arrays/compare/v1.0.0...v1.0.1) - 2020-01-24
### Commits
- [meta] add "exports" [`5942917`](https://github.com/inspect-js/available-typed-arrays/commit/5942917aafb56c6bce80f01b7ae6a9b46bc72c69)
## v1.0.0 - 2020-01-24
### Commits
- Initial commit [`2bc5144`](https://github.com/inspect-js/available-typed-arrays/commit/2bc514459c9f65756adfbd9964abf433183d78f6)
- readme [`31e4796`](https://github.com/inspect-js/available-typed-arrays/commit/31e4796379eba4a16d3c6a8e9baf6eb3f39e33d1)
- npm init [`9194266`](https://github.com/inspect-js/available-typed-arrays/commit/9194266b471a2a2dd5e6969bc40358ceb346e21e)
- Tests [`b539830`](https://github.com/inspect-js/available-typed-arrays/commit/b539830c3213f90de42b4d6e62803f52daf61a6d)
- Implementation [`6577df2`](https://github.com/inspect-js/available-typed-arrays/commit/6577df244ea146ef5ec16858044c8955e0fc445c)
- [meta] add `auto-changelog` [`7b43310`](https://github.com/inspect-js/available-typed-arrays/commit/7b43310be76f00fe60b74a2fd6d0e46ac1d01f3e)
- [Tests] add `npm run lint` [`dedfbc1`](https://github.com/inspect-js/available-typed-arrays/commit/dedfbc1592f86ac1636267d3965f2345df43815b)
- [Tests] use shared travis-ci configs [`c459d78`](https://github.com/inspect-js/available-typed-arrays/commit/c459d78bf2efa9d777f88599ae71a796dbfcb70f)
- Only apps should have lockfiles [`d294668`](https://github.com/inspect-js/available-typed-arrays/commit/d294668422cf35f5e7716a85bfd204e62b01c056)
- [meta] add `funding` field [`6e70bc1`](https://github.com/inspect-js/available-typed-arrays/commit/6e70bc1fb199c7898165aaf05c25bb49f4062e53)
- [meta] add `safe-publish-latest` [`dd89ca2`](https://github.com/inspect-js/available-typed-arrays/commit/dd89ca2c6842f0f3e82958df2b2bd0fc0c929c51)
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Inspect JS
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+55
View File
@@ -0,0 +1,55 @@
# available-typed-arrays <sup>[![Version Badge][2]][1]</sup>
[![github actions][actions-image]][actions-url]
[![coverage][codecov-image]][codecov-url]
[![dependency status][5]][6]
[![dev dependency status][7]][8]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][11]][1]
Returns an array of Typed Array names that are available in the current environment.
## Example
```js
var availableTypedArrays = require('available-typed-arrays');
var assert = require('assert');
assert.deepStrictEqual(
availableTypedArrays().sort(),
[
'Int8Array',
'Uint8Array',
'Uint8ClampedArray',
'Int16Array',
'Uint16Array',
'Int32Array',
'Uint32Array',
'Float32Array',
'Float64Array',
'BigInt64Array',
'BigUint64Array'
].sort()
);
```
## Tests
Simply clone the repo, `npm install`, and run `npm test`
[1]: https://npmjs.org/package/available-typed-arrays
[2]: https://versionbadg.es/inspect-js/available-typed-arrays.svg
[5]: https://david-dm.org/inspect-js/available-typed-arrays.svg
[6]: https://david-dm.org/inspect-js/available-typed-arrays
[7]: https://david-dm.org/inspect-js/available-typed-arrays/dev-status.svg
[8]: https://david-dm.org/inspect-js/available-typed-arrays#info=devDependencies
[11]: https://nodei.co/npm/available-typed-arrays.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/available-typed-arrays.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/available-typed-arrays.svg
[downloads-url]: https://npm-stat.com/charts.html?package=available-typed-arrays
[codecov-image]: https://codecov.io/gh/inspect-js/available-typed-arrays/branch/main/graphs/badge.svg
[codecov-url]: https://app.codecov.io/gh/inspect-js/available-typed-arrays/
[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/available-typed-arrays
[actions-url]: https://github.com/inspect-js/available-typed-arrays/actions
+8
View File
@@ -0,0 +1,8 @@
type AllPossibleTypedArrays = typeof import('possible-typed-array-names');
declare function availableTypedArrays():
| []
| AllPossibleTypedArrays
| Omit<AllPossibleTypedArrays, 'BigInt64Array' | 'BigUint64Array'>;
export = availableTypedArrays;
+17
View File
@@ -0,0 +1,17 @@
'use strict';
var possibleNames = require('possible-typed-array-names');
var g = typeof globalThis === 'undefined' ? global : globalThis;
/** @type {import('.')} */
module.exports = function availableTypedArrays() {
var /** @type {ReturnType<typeof availableTypedArrays>} */ out = [];
for (var i = 0; i < possibleNames.length; i++) {
if (typeof g[possibleNames[i]] === 'function') {
// @ts-expect-error
out[out.length] = possibleNames[i];
}
}
return out;
};
+93
View File
@@ -0,0 +1,93 @@
{
"name": "available-typed-arrays",
"version": "1.0.7",
"description": "Returns an array of Typed Array names that are available in the current environment",
"main": "index.js",
"type": "commonjs",
"exports": {
".": "./index.js",
"./package.json": "./package.json"
},
"types": "./index.d.ts",
"sideEffects": false,
"scripts": {
"prepack": "npmignore --auto --commentLines=autogenerated",
"prepublish": "not-in-publish || npm run prepublishOnly",
"prepublishOnly": "safe-publish-latest",
"prelint": "evalmd README.md",
"lint": "eslint --ext=js,mjs .",
"postlint": "tsc -p .",
"pretest": "npm run lint",
"tests-only": "nyc tape 'test/**/*.js'",
"test:harmony": "nyc node --harmony --es-staging test",
"test": "npm run tests-only && npm run test:harmony",
"posttest": "aud --production",
"version": "auto-changelog && git add CHANGELOG.md",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
},
"repository": {
"type": "git",
"url": "git+https://github.com/inspect-js/available-typed-arrays.git"
},
"keywords": [
"typed",
"arrays",
"Float32Array",
"Float64Array",
"Int8Array",
"Int16Array",
"Int32Array",
"Uint8Array",
"Uint8ClampedArray",
"Uint16Array",
"Uint32Array",
"BigInt64Array",
"BigUint64Array"
],
"author": "Jordan Harband <[email protected]>",
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/inspect-js/available-typed-arrays/issues"
},
"homepage": "https://github.com/inspect-js/available-typed-arrays#readme",
"engines": {
"node": ">= 0.4"
},
"devDependencies": {
"@ljharb/eslint-config": "^21.1.0",
"@types/array.prototype.every": "^1.1.1",
"@types/isarray": "^2.0.2",
"@types/tape": "^5.6.4",
"array.prototype.every": "^1.1.5",
"aud": "^2.0.4",
"auto-changelog": "^2.4.0",
"eslint": "=8.8.0",
"evalmd": "^0.0.19",
"in-publish": "^2.0.1",
"isarray": "^2.0.5",
"npmignore": "^0.3.1",
"nyc": "^10.3.2",
"safe-publish-latest": "^2.0.0",
"tape": "^5.7.4",
"typescript": "^5.4.0-dev.20240131"
},
"auto-changelog": {
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": false,
"commitLimit": false,
"backfillLimit": false,
"hideCredit": true
},
"publishConfig": {
"ignore": [
".github/workflows"
]
},
"dependencies": {
"possible-typed-array-names": "^1.0.0"
}
}
+18
View File
@@ -0,0 +1,18 @@
'use strict';
var test = require('tape');
var isArray = require('isarray');
var every = require('array.prototype.every');
var availableTypedArrays = require('../');
test('available typed arrays', function (t) {
t.equal(typeof availableTypedArrays, 'function', 'is a function');
var arrays = availableTypedArrays();
t.equal(isArray(arrays), true, 'returns an array');
t.equal(every(arrays, function (array) { return typeof array === 'string'; }), true, 'contains only strings');
t.end();
});
+49
View File
@@ -0,0 +1,49 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
"useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
"typeRoots": ["types"], /* Specify multiple folders that act like './node_modules/@types'. */
"resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
/* JavaScript Support */
"allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
"checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
"maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
"declarationMap": true, /* Create sourcemaps for d.ts files. */
"noEmit": true, /* Disable emitting files from a compilation. */
/* Interop Constraints */
"allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
/* Completeness */
//"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"exclude": [
"coverage"
]
}
+23
View File
@@ -0,0 +1,23 @@
(MIT)
Original code Copyright Julian Gruber <julian@juliangruber.com>
Port to TypeScript Copyright Isaac Z. Schlueter <i@izs.me>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+57
View File
@@ -0,0 +1,57 @@
# balanced-match
Match balanced string pairs, like `{` and `}` or `<b>` and
`</b>`. Supports regular expressions as well!
## Example
Get the first matching pair of braces:
```js
import { balanced } from 'balanced-match'
console.log(balanced('{', '}', 'pre{in{nested}}post'))
console.log(balanced('{', '}', 'pre{first}between{second}post'))
console.log(
balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post'),
)
```
The matches are:
```bash
$ node example.js
{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' }
{ start: 3,
end: 9,
pre: 'pre',
body: 'first',
post: 'between{second}post' }
{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' }
```
## API
### const m = balanced(a, b, str)
For the first non-nested matching pair of `a` and `b` in `str`, return an
object with those keys:
- **start** the index of the first match of `a`
- **end** the index of the matching `b`
- **pre** the preamble, `a` and `b` not included
- **body** the match, `a` and `b` not included
- **post** the postscript, `a` and `b` not included
If there's no match, `undefined` will be returned.
If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`.
### const r = balanced.range(a, b, str)
For the first non-nested matching pair of `a` and `b` in `str`, return an
array with indexes: `[ <a index>, <b index> ]`.
If there's no match, `undefined` will be returned.
If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`.
+9
View File
@@ -0,0 +1,9 @@
export declare const balanced: (a: string | RegExp, b: string | RegExp, str: string) => false | {
start: number;
end: number;
pre: string;
body: string;
post: string;
} | undefined;
export declare const range: (a: string, b: string, str: string) => undefined | [number, number];
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,QAAQ,GACnB,GAAG,MAAM,GAAG,MAAM,EAClB,GAAG,MAAM,GAAG,MAAM,EAClB,KAAK,MAAM;;;;;;aAgBZ,CAAA;AAOD,eAAO,MAAM,KAAK,GAChB,GAAG,MAAM,EACT,GAAG,MAAM,EACT,KAAK,MAAM,KACV,SAAS,GAAG,CAAC,MAAM,EAAE,MAAM,CA2C7B,CAAA"}
+59
View File
@@ -0,0 +1,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.range = exports.balanced = void 0;
const balanced = (a, b, str) => {
const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
const r = ma !== null && mb != null && (0, exports.range)(ma, mb, str);
return (r && {
start: r[0],
end: r[1],
pre: str.slice(0, r[0]),
body: str.slice(r[0] + ma.length, r[1]),
post: str.slice(r[1] + mb.length),
});
};
exports.balanced = balanced;
const maybeMatch = (reg, str) => {
const m = str.match(reg);
return m ? m[0] : null;
};
const range = (a, b, str) => {
let begs, beg, left, right = undefined, result;
let ai = str.indexOf(a);
let bi = str.indexOf(b, ai + 1);
let i = ai;
if (ai >= 0 && bi > 0) {
if (a === b) {
return [ai, bi];
}
begs = [];
left = str.length;
while (i >= 0 && !result) {
if (i === ai) {
begs.push(i);
ai = str.indexOf(a, i + 1);
}
else if (begs.length === 1) {
const r = begs.pop();
if (r !== undefined)
result = [r, bi];
}
else {
beg = begs.pop();
if (beg !== undefined && beg < left) {
left = beg;
right = bi;
}
bi = str.indexOf(b, i + 1);
}
i = ai < bi && ai >= 0 ? ai : bi;
}
if (begs.length && right !== undefined) {
result = [left, right];
}
}
return result;
};
exports.range = range;
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAO,MAAM,QAAQ,GAAG,CACtB,CAAkB,EAClB,CAAkB,EAClB,GAAW,EACX,EAAE;IACF,MAAM,EAAE,GAAG,CAAC,YAAY,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IACvD,MAAM,EAAE,GAAG,CAAC,YAAY,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAEvD,MAAM,CAAC,GAAG,EAAE,KAAK,IAAI,IAAI,EAAE,IAAI,IAAI,IAAI,IAAA,aAAK,EAAC,EAAE,EAAE,EAAE,EAAE,GAAG,CAAC,CAAA;IAEzD,OAAO,CACL,CAAC,IAAI;QACH,KAAK,EAA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AG,GAAG,CAAC,MAAM,CAAA;QAEjB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACzB,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC;gBACb,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;gBACZ,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAA;YAC5B,CAAC;iBAAM,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC7B,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;gBACpB,IAAI,CAAC,KAAK,SAAS;oBAAE,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA;YACvC,CAAC;iBAAM,CAAC;gBACN,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;gBAChB,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,GAAG,IAAI,EAAE,CAAC;oBACpC,IAAI,GAAG,GAAG,CAAA;oBACV,KAAK,GAAG,EAAE,CAAA;gBACZ,CAAC;gBAED,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAA;YAC5B,CAAC;YAED,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;QAClC,CAAC;QAED,IAAI,IAAI,CAAC,MAAM,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACvC,MAAM,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QACxB,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAA;AACf,CAAC,CAAA;AA/CY,QAAA,KAAK,SA+CjB","sourcesContent":["export const balanced = (\n a: string | RegExp,\n b: string | RegExp,\n str: string,\n) => {\n const ma = a instanceof RegExp ? maybeMatch(a, str) : a\n const mb = b instanceof RegExp ? maybeMatch(b, str) : b\n\n const r = ma !== null && mb != null && range(ma, mb, str)\n\n return (\n r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + ma.length, r[1]),\n post: str.slice(r[1] + mb.length),\n }\n )\n}\n\nconst maybeMatch = (reg: RegExp, str: string) => {\n const m = str.match(reg)\n return m ? m[0] : null\n}\n\nexport const range = (\n a: string,\n b: string,\n str: string,\n): undefined | [number, number] => {\n let begs: number[],\n beg: number | undefined,\n left: number,\n right: number | undefined = undefined,\n result: undefined | [number, number]\n let ai = str.indexOf(a)\n let bi = str.indexOf(b, ai + 1)\n let i = ai\n\n if (ai >= 0 && bi > 0) {\n if (a === b) {\n return [ai, bi]\n }\n begs = []\n left = str.length\n\n while (i >= 0 && !result) {\n if (i === ai) {\n begs.push(i)\n ai = str.indexOf(a, i + 1)\n } else if (begs.length === 1) {\n const r = begs.pop()\n if (r !== undefined) result = [r, bi]\n } else {\n beg = begs.pop()\n if (beg !== undefined && beg < left) {\n left = beg\n right = bi\n }\n\n bi = str.indexOf(b, i + 1)\n }\n\n i = ai < bi && ai >= 0 ? ai : bi\n }\n\n if (begs.length && right !== undefined) {\n result = [left, right]\n }\n }\n\n return result\n}\n"]}
+3
View File
@@ -0,0 +1,3 @@
{
"type": "commonjs"
}
+9
View File
@@ -0,0 +1,9 @@
export declare const balanced: (a: string | RegExp, b: string | RegExp, str: string) => false | {
start: number;
end: number;
pre: string;
body: string;
post: string;
} | undefined;
export declare const range: (a: string, b: string, str: string) => undefined | [number, number];
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,QAAQ,GACnB,GAAG,MAAM,GAAG,MAAM,EAClB,GAAG,MAAM,GAAG,MAAM,EAClB,KAAK,MAAM;;;;;;aAgBZ,CAAA;AAOD,eAAO,MAAM,KAAK,GAChB,GAAG,MAAM,EACT,GAAG,MAAM,EACT,KAAK,MAAM,KACV,SAAS,GAAG,CAAC,MAAM,EAAE,MAAM,CA2C7B,CAAA"}
+54
View File
@@ -0,0 +1,54 @@
export const balanced = (a, b, str) => {
const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
const r = ma !== null && mb != null && range(ma, mb, str);
return (r && {
start: r[0],
end: r[1],
pre: str.slice(0, r[0]),
body: str.slice(r[0] + ma.length, r[1]),
post: str.slice(r[1] + mb.length),
});
};
const maybeMatch = (reg, str) => {
const m = str.match(reg);
return m ? m[0] : null;
};
export const range = (a, b, str) => {
let begs, beg, left, right = undefined, result;
let ai = str.indexOf(a);
let bi = str.indexOf(b, ai + 1);
let i = ai;
if (ai >= 0 && bi > 0) {
if (a === b) {
return [ai, bi];
}
begs = [];
left = str.length;
while (i >= 0 && !result) {
if (i === ai) {
begs.push(i);
ai = str.indexOf(a, i + 1);
}
else if (begs.length === 1) {
const r = begs.pop();
if (r !== undefined)
result = [r, bi];
}
else {
beg = begs.pop();
if (beg !== undefined && beg < left) {
left = beg;
right = bi;
}
bi = str.indexOf(b, i + 1);
}
i = ai < bi && ai >= 0 ? ai : bi;
}
if (begs.length && right !== undefined) {
result = [left, right];
}
}
return result;
};
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,CAAkB,EAClB,CAAkB,EAClB,GAAW,EACX,EAAE;IACF,MAAM,EAAE,GAAG,CAAC,YAAY,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IACvD,MAAM,EAAE,GAAG,CAAC,YAAY,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,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,MAAM,CAAA;AACf,CAAC,CAAA","sourcesContent":["export const balanced = (\n a: string | RegExp,\n b: string | RegExp,\n str: string,\n) => {\n const ma = a instanceof RegExp ? maybeMatch(a, str) : a\n const mb = b instanceof RegExp ? maybeMatch(b, str) : b\n\n const r = ma !== null && mb != null && range(ma, mb, str)\n\n return (\n r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + ma.length, r[1]),\n post: str.slice(r[1] + mb.length),\n }\n )\n}\n\nconst maybeMatch = (reg: RegExp, str: string) => {\n const m = str.match(reg)\n return m ? m[0] : null\n}\n\nexport const range = (\n a: string,\n b: string,\n str: string,\n): undefined | [number, number] => {\n let begs: number[],\n beg: number | undefined,\n left: number,\n right: number | undefined = undefined,\n result: undefined | [number, number]\n let ai = str.indexOf(a)\n let bi = str.indexOf(b, ai + 1)\n let i = ai\n\n if (ai >= 0 && bi > 0) {\n if (a === b) {\n return [ai, bi]\n }\n begs = []\n left = str.length\n\n while (i >= 0 && !result) {\n if (i === ai) {\n begs.push(i)\n ai = str.indexOf(a, i + 1)\n } else if (begs.length === 1) {\n const r = begs.pop()\n if (r !== undefined) result = [r, bi]\n } else {\n beg = begs.pop()\n if (beg !== undefined && beg < left) {\n left = beg\n right = bi\n }\n\n bi = str.indexOf(b, i + 1)\n }\n\n i = ai < bi && ai >= 0 ? ai : bi\n }\n\n if (begs.length && right !== undefined) {\n result = [left, right]\n }\n }\n\n return result\n}\n"]}
+3
View File
@@ -0,0 +1,3 @@
{
"type": "module"
}
+68
View File
@@ -0,0 +1,68 @@
{
"name": "balanced-match",
"description": "Match balanced character pairs, like \"{\" and \"}\"",
"version": "4.0.4",
"files": [
"dist"
],
"repository": {
"type": "git",
"url": "git://github.com/juliangruber/balanced-match.git"
},
"exports": {
"./package.json": "./package.json",
".": {
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
},
"require": {
"types": "./dist/commonjs/index.d.ts",
"default": "./dist/commonjs/index.js"
}
}
},
"type": "module",
"scripts": {
"preversion": "npm test",
"postversion": "npm publish",
"prepublishOnly": "git push origin --follow-tags",
"prepare": "tshy",
"pretest": "npm run prepare",
"presnap": "npm run prepare",
"test": "tap",
"snap": "tap",
"format": "prettier --write .",
"benchmark": "node benchmark/index.js",
"typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts"
},
"devDependencies": {
"@types/brace-expansion": "^1.1.2",
"@types/node": "^25.2.1",
"mkdirp": "^3.0.1",
"prettier": "^3.3.2",
"tap": "^21.6.2",
"tshy": "^3.0.2",
"typedoc": "^0.28.5"
},
"keywords": [
"match",
"regexp",
"test",
"balanced",
"parse"
],
"license": "MIT",
"engines": {
"node": "18 || 20 || >=22"
},
"tshy": {
"exports": {
"./package.json": "./package.json",
".": "./src/index.ts"
}
},
"main": "./dist/commonjs/index.js",
"types": "./dist/commonjs/index.d.ts",
"module": "./dist/esm/index.js"
}
+23
View File
@@ -0,0 +1,23 @@
(The MIT License)
Copyright (c) 2014 Jonathan Ong <[email protected]>
Copyright (c) 2014-2015 Douglas Christopher Wilson <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+513
View File
@@ -0,0 +1,513 @@
# body-parser
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-url]
[![Build Status][ci-image]][ci-url]
[![Test Coverage][coveralls-image]][coveralls-url]
[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer]
Node.js body parsing middleware.
Parse incoming request bodies in a middleware before your handlers, available
under the `req.body` property.
**Note** As `req.body`'s shape is based on user-controlled input, all
properties and values in this object are untrusted and should be validated
before trusting. For example, `req.body.foo.toString()` may fail in multiple
ways, for example the `foo` property may not be there or may not be a string,
and `toString` may not be a function and instead a string or other user input.
[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/learn/http/anatomy-of-an-http-transaction).
_This does not handle multipart bodies_, due to their complex and typically
large nature. For multipart bodies, you may be interested in the following
modules:
* [busboy](https://www.npmjs.com/package/busboy#readme) and
[connect-busboy](https://www.npmjs.com/package/connect-busboy#readme)
* [multiparty](https://www.npmjs.com/package/multiparty#readme) and
[connect-multiparty](https://www.npmjs.com/package/connect-multiparty#readme)
* [formidable](https://www.npmjs.com/package/formidable#readme)
* [multer](https://www.npmjs.com/package/multer#readme)
This module provides the following parsers:
* [JSON body parser](#bodyparserjsonoptions)
* [Raw body parser](#bodyparserrawoptions)
* [Text body parser](#bodyparsertextoptions)
* [URL-encoded form body parser](#bodyparserurlencodedoptions)
All parsers support automatic inflation of `gzip`, `br` (brotli), `deflate`
and `zstd` encodings. `zstd` is available in Node.js `^22.15.0` and
`>=23.8.0`.
Other body parsers you might be interested in:
- [body](https://www.npmjs.com/package/body#readme)
- [co-body](https://www.npmjs.com/package/co-body#readme)
## Installation
```sh
$ npm install body-parser
```
## API
```js
// Import all parsers
const bodyParser = require('body-parser')
// Or import individual parsers directly
const json = require('body-parser/json')
const urlencoded = require('body-parser/urlencoded')
const raw = require('body-parser/raw')
const text = require('body-parser/text')
```
The `bodyParser` object exposes various factories to create middlewares. All
middlewares will populate the `req.body` property with the parsed body when
the `Content-Type` request header matches the `type` option.
**Note** As of v2, `req.body` is left `undefined` when no body is parsed (for
example when the request has neither `Content-Length` nor `Transfer-Encoding`,
or when `Content-Type` does not match). In v1, `req.body` was always initialized
to `{}`. Code that assumes `req.body` is always an object should use optional
chaining (for example `req.body?.username`) or set a default.
The various errors returned by this module are described in the
[errors section](#errors).
### bodyParser.json([options])
Returns middleware that only parses `json` and only looks at requests where
the `Content-Type` header matches the `type` option. This parser accepts any
Unicode encoding of the body.
A new `body` object containing the parsed data is populated on the `request`
object after the middleware (i.e. `req.body`).
#### Options
The `json` function takes an optional `options` object that may contain any of
the following keys:
##### defaultCharset
Specify the default character set for the json content if the charset is not
specified in the `Content-Type` header of the request. Defaults to `utf-8`.
##### inflate
When set to `true`, then deflated (compressed) bodies will be inflated; when
`false`, deflated bodies are rejected. Defaults to `true`.
##### limit
Controls the maximum request body size. If this is a number, then the value
specifies the number of bytes; if it is a string, the value is passed to the
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
to `'100kb'`.
> It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur.
##### reviver
The `reviver` option is passed directly to `JSON.parse` as the second
argument. You can find more information on this argument
[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter).
##### strict
When set to `true`, it will only accept arrays and objects; when `false`, it will
accept anything `JSON.parse` accepts. Defaults to `true`.
##### type
The `type` option is used to determine what media type the middleware will
parse. This option can be a string, array of strings, or a function. If not a
function, `type` option is passed directly to the
[type-is](https://www.npmjs.com/package/type-is#readme) library and this can
be an extension name (like `json`), a mime type (like `application/json`), or
a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type`
option is called as `fn(req)` and the request is parsed if it returns a truthy
value. Defaults to `application/json`.
##### verify
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
where `buf` is a `Buffer` of the raw request body and `encoding` is the
encoding of the request. The parsing can be aborted by throwing an error.
### bodyParser.raw([options])
Returns middleware that parses all bodies as a `Buffer` and only looks at
requests where the `Content-Type` header matches the `type` option.
A new `body` object containing the parsed data is populated on the `request`
object after the middleware (i.e. `req.body`). This will be a `Buffer` object
of the body.
#### Options
The `raw` function takes an optional `options` object that may contain any of
the following keys:
##### inflate
When set to `true`, then deflated (compressed) bodies will be inflated; when
`false`, deflated bodies are rejected. Defaults to `true`.
##### limit
Controls the maximum request body size. If this is a number, then the value
specifies the number of bytes; if it is a string, the value is passed to the
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
to `'100kb'`.
> It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur.
##### type
The `type` option is used to determine what media type the middleware will
parse. This option can be a string, array of strings, or a function.
If not a function, `type` option is passed directly to the
[type-is](https://www.npmjs.com/package/type-is#readme) library and this
can be an extension name (like `bin`), a mime type (like
`application/octet-stream`), or a mime type with a wildcard (like `*/*` or
`application/*`). If a function, the `type` option is called as `fn(req)`
and the request is parsed if it returns a truthy value. Defaults to
`application/octet-stream`.
##### verify
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
where `buf` is a `Buffer` of the raw request body and `encoding` is the
encoding of the request. The parsing can be aborted by throwing an error.
### bodyParser.text([options])
Returns middleware that parses all bodies as a string and only looks at
requests where the `Content-Type` header matches the `type` option.
A new `body` string containing the parsed data is populated on the `request`
object after the middleware (i.e. `req.body`). This will be a string of the
body.
#### Options
The `text` function takes an optional `options` object that may contain any of
the following keys:
##### defaultCharset
Specify the default character set for the text content if the charset is not
specified in the `Content-Type` header of the request. Defaults to `utf-8`.
##### inflate
When set to `true`, then deflated (compressed) bodies will be inflated; when
`false`, deflated bodies are rejected. Defaults to `true`.
##### limit
Controls the maximum request body size. If this is a number, then the value
specifies the number of bytes; if it is a string, the value is passed to the
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
to `'100kb'`.
> It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur.
##### type
The `type` option is used to determine what media type the middleware will
parse. This option can be a string, array of strings, or a function. If not
a function, `type` option is passed directly to the
[type-is](https://www.npmjs.com/package/type-is#readme) library and this can
be an extension name (like `txt`), a mime type (like `text/plain`), or a mime
type with a wildcard (like `*/*` or `text/*`). If a function, the `type`
option is called as `fn(req)` and the request is parsed if it returns a
truthy value. Defaults to `text/plain`.
##### verify
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
where `buf` is a `Buffer` of the raw request body and `encoding` is the
encoding of the request. The parsing can be aborted by throwing an error.
### bodyParser.urlencoded([options])
Returns middleware that only parses `urlencoded` bodies and only looks at
requests where the `Content-Type` header matches the `type` option. This
parser accepts only UTF-8 and ISO-8859-1 encodings of the body.
A new `body` object containing the parsed data is populated on the `request`
object after the middleware (i.e. `req.body`). This object will contain
key-value pairs, where the value can be a string or array (when `extended` is
`false`), or any type (when `extended` is `true`).
#### Options
The `urlencoded` function takes an optional `options` object that may contain
any of the following keys:
##### extended
The "extended" syntax allows for rich objects and arrays to be encoded into the
URL-encoded format, allowing for a JSON-like experience with URL-encoded. For
more information, please [see the qs
library](https://www.npmjs.com/package/qs#readme).
Defaults to `false`.
##### inflate
When set to `true`, then deflated (compressed) bodies will be inflated; when
`false`, deflated bodies are rejected. Defaults to `true`.
##### limit
Controls the maximum request body size. If this is a number, then the value
specifies the number of bytes; if it is a string, the value is passed to the
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
to `'100kb'`.
> It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur.
##### parameterLimit
The `parameterLimit` option controls the maximum number of parameters that
are allowed in the URL-encoded data. If a request contains more parameters
than this value, a 413 will be returned to the client. Defaults to `1000`.
##### type
The `type` option is used to determine what media type the middleware will
parse. This option can be a string, array of strings, or a function. If not
a function, `type` option is passed directly to the
[type-is](https://www.npmjs.com/package/type-is#readme) library and this can
be an extension name (like `urlencoded`), a mime type (like
`application/x-www-form-urlencoded`), or a mime type with a wildcard (like
`*/x-www-form-urlencoded`). If a function, the `type` option is called as
`fn(req)` and the request is parsed if it returns a truthy value. Defaults
to `application/x-www-form-urlencoded`.
##### verify
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
where `buf` is a `Buffer` of the raw request body and `encoding` is the
encoding of the request. The parsing can be aborted by throwing an error.
##### defaultCharset
The default charset to parse as, if not specified in content-type. Must be
either `utf-8` or `iso-8859-1`. Defaults to `utf-8`.
##### charsetSentinel
Whether to let the value of the `utf8` parameter take precedence as the charset
selector. It requires the form to contain a parameter named `utf8` with a value
of `✓`. Defaults to `false`.
##### interpretNumericEntities
Whether to decode numeric entities such as `&#9786;` when parsing an iso-8859-1
form. Defaults to `false`.
##### depth
The `depth` option is used to configure the maximum depth of the `qs` library when `extended` is `true`. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to `32`. It is recommended to keep this value as low as possible.
## Errors
The middlewares provided by this module create errors using the
[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors
will typically have a `status`/`statusCode` property that contains the suggested
HTTP response code, an `expose` property to determine if the `message` property
should be displayed to the client, a `type` property to determine the type of
error without matching against the `message`, and a `body` property containing
the read body, if available.
The following are the common errors created, though any error can come through
for various reasons.
### content encoding unsupported
This error will occur when the request had a `Content-Encoding` header that
contained an encoding but the "inflation" option was set to `false`. The
`status` property is set to `415`, the `type` property is set to
`'encoding.unsupported'`, and the `charset` property will be set to the
encoding that is unsupported.
### entity parse failed
This error will occur when the request contained an entity that could not be
parsed by the middleware. The `status` property is set to `400`, the `type`
property is set to `'entity.parse.failed'`, and the `body` property is set to
the entity value that failed parsing.
### entity verify failed
This error will occur when the request contained an entity that could not be
verified by the defined `verify` option. The `status` property is
set to `403`, the `type` property is set to `'entity.verify.failed'`, and the
`body` property is set to the entity value that failed verification.
### request aborted
This error will occur when the request is aborted by the client before reading
the body has finished. The `received` property will be set to the number of
bytes received before the request was aborted and the `expected` property is
set to the number of expected bytes. The `status` property is set to `400`
and `type` property is set to `'request.aborted'`.
### request entity too large
This error will occur when the request body's size is larger than the "limit"
option. The `limit` property will be set to the byte limit and the `length`
property will be set to the request body's length. The `status` property is
set to `413` and the `type` property is set to `'entity.too.large'`.
### request size did not match content length
This error will occur when the request's length did not match the length from
the `Content-Length` header. This typically occurs when the request is malformed,
typically when the `Content-Length` header was calculated based on characters
instead of bytes. The `status` property is set to `400` and the `type` property
is set to `'request.size.invalid'`.
### stream encoding should not be set
This error will occur when something called the `req.setEncoding` method prior
to this middleware. This module operates directly on bytes only and you cannot
call `req.setEncoding` when using this module. The `status` property is set to
`500` and the `type` property is set to `'stream.encoding.set'`.
### stream is not readable
This error will occur when the request is no longer readable when this middleware
attempts to read it. This typically means something other than a middleware from
this module read the request body already and the middleware was also configured to
read the same request. The `status` property is set to `500` and the `type`
property is set to `'stream.not.readable'`.
### too many parameters
This error will occur when the content of the request exceeds the configured
`parameterLimit` for the `urlencoded` parser. The `status` property is set to
`413` and the `type` property is set to `'parameters.too.many'`.
### unsupported charset "BOGUS"
This error will occur when the request had a charset parameter in the
`Content-Type` header, but the `iconv-lite` module does not support it OR the
parser does not support it. The charset is contained in the message as well
as in the `charset` property. The `status` property is set to `415`, the
`type` property is set to `'charset.unsupported'`, and the `charset` property
is set to the charset that is unsupported.
### unsupported content encoding "bogus"
This error will occur when the request had a `Content-Encoding` header that
contained an unsupported encoding. The encoding is contained in the message
as well as in the `encoding` property. The `status` property is set to `415`,
the `type` property is set to `'encoding.unsupported'`, and the `encoding`
property is set to the encoding that is unsupported.
### The input exceeded the depth
This error occurs when using `bodyParser.urlencoded` with the `extended` property set to `true` and the input exceeds the configured `depth` option. The `status` property is set to `400`. It is recommended to review the `depth` option and evaluate if it requires a higher value. With the default `depth` of `32`, an input with 33 or more levels of nesting gets this error.
## Examples
### Express/Connect top-level generic
This example demonstrates adding a generic JSON and URL-encoded parser as a
top-level middleware, which will parse the bodies of all incoming requests.
This is the simplest setup.
```js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded())
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(String(JSON.stringify(req.body, null, 2)))
})
```
### Express route-specific
This example demonstrates adding body parsers specifically to the routes that
need them. In general, this is the most recommended way to use body-parser with
Express.
```js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
// create application/json parser
const jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
const urlencodedParser = bodyParser.urlencoded()
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
if (!req.body || !req.body.username) res.sendStatus(400)
res.send('welcome, ' + req.body.username)
})
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
if (!req.body) res.sendStatus(400)
// create user in req.body
})
```
### Change accepted type for parsers
All the parsers accept a `type` option which allows you to change the
`Content-Type` that the middleware will parse.
```js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))
// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }))
```
## License
[MIT](LICENSE)
[ci-image]: https://img.shields.io/github/actions/workflow/status/expressjs/body-parser/ci.yml?branch=master&label=ci
[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml
[coveralls-image]: https://img.shields.io/coverallsCoverage/github/expressjs/body-parser?branch=master
[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master
[npm-downloads-image]: https://img.shields.io/npm/dm/body-parser
[npm-url]: https://npmjs.com/package/body-parser
[npm-version-image]: https://img.shields.io/npm/v/body-parser
[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge
[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser
Loaded 100 of 1575 files, more files were not shown because too many files have changed in this diff. Show more