This commit is contained in:
Lukian LEIZOUR 2023-01-29 00:57:47 +01:00
parent a15c733e45
commit 2a5130cbda
2838 changed files with 288613 additions and 0 deletions

15
node_modules/strtok3/LICENSE generated vendored Normal file
View file

@ -0,0 +1,15 @@
Copyright (c) 2017, Borewit
All rights reserved.
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.

306
node_modules/strtok3/README.md generated vendored Normal file
View file

@ -0,0 +1,306 @@
![Node.js CI](https://github.com/Borewit/strtok3/workflows/Node.js%20CI/badge.svg)
[![NPM version](https://badge.fury.io/js/strtok3.svg)](https://npmjs.org/package/strtok3)
[![npm downloads](http://img.shields.io/npm/dm/strtok3.svg)](https://npmcharts.com/compare/strtok3,token-types?start=1200&interval=30)
[![DeepScan grade](https://deepscan.io/api/teams/5165/projects/8526/branches/103329/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=5165&pid=8526&bid=103329)
[![Known Vulnerabilities](https://snyk.io/test/github/Borewit/strtok3/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/strtok3?targetFile=package.json)
[![Total alerts](https://img.shields.io/lgtm/alerts/g/Borewit/strtok3.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Borewit/strtok3/alerts/)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/59dd6795e61949fb97066ca52e6097ef)](https://www.codacy.com/app/Borewit/strtok3?utm_source=github.com&utm_medium=referral&utm_content=Borewit/strtok3&utm_campaign=Badge_Grade)
[![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/Borewit/strtok3.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Borewit/strtok3/context:javascript)
# strtok3
A promise based streaming [*tokenizer*](#tokenizer) for [Node.js](http://nodejs.org) and browsers.
This node module is a successor of [strtok2](https://github.com/Borewit/strtok2).
The `strtok3` contains a few methods to turn different input into a [*tokenizer*](#tokenizer). Designed to
* Support a streaming environment
* Decoding of binary data, strings and numbers in mind
* Read [predefined](https://github.com/Borewit/token-types) or custom tokens.
* Optimized [*tokenizers*](#tokenizer) for reading from [file](#method-strtok3fromfile), [stream](#method-strtok3fromstream) or [buffer](#method-strtok3frombuffer).
It can read from:
* A file (taking a file path as an input)
* A Node.js [stream](https://nodejs.org/api/stream.html).
* A [Buffer](https://nodejs.org/api/buffer.html) or [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* HTTP chunked transfer provided by [@tokenizer/http](https://github.com/Borewit/tokenizer-http).
* Chunked [Amazon S3](https://aws.amazon.com/s3) access provided by [@tokenizer/s3](https://github.com/Borewit/tokenizer-s3).
## Installation
```sh
npm install strtok3
```
### Compatibility
Module: version 7 migrated from [CommonJS](https://en.wikipedia.org/wiki/CommonJS) to [pure ECMAScript Module (ESM)](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c).
JavaScript is compliant with [ECMAScript 2019 (ES10)](https://en.wikipedia.org/wiki/ECMAScript#10th_Edition_%E2%80%93_ECMAScript_2019).
Requires Node.js ≥ 14.16 engine.
## API
Use one of the methods to instantiate an [*abstract tokenizer*](#tokenizer):
* [strtok3.fromFile](#method-strtok3fromfile)
* [strtok3.fromStream](#method-strtok3fromstream)
* [strtok3.fromBuffer](#method-strtok3fromBuffer)
* [strtok3.fromUint8Array](#method-strtok3fromUint8Array)
### strtok3 methods
All of the strtok3 methods return a [*tokenizer*](#tokenizer), either directly or via a promise.
#### Method `strtok3.fromFile()`
| Parameter | Type | Description |
|-----------|-----------------------|----------------------------|
| path | Path to file (string) | Path to file to read from |
> __Note__: that [file-information](#file-information) is automatically added.
Returns, via a promise, a [*tokenizer*](#tokenizer) which can be used to parse a file.
```js
import * as strtok3 from 'strtok3';
import * as Token from 'token-types';
(async () => {
const tokenizer = await strtok3.fromFile("somefile.bin");
try {
const myNumber = await tokenizer.readToken(Token.UINT8);
console.log(`My number: ${myNumber}`);
} finally {
tokenizer.close(); // Close the file
}
})();
```
#### Method `strtok3.fromStream()`
Create [*tokenizer*](#tokenizer) from a node.js [readable stream](https://nodejs.org/api/stream.html#stream_class_stream_readable).
| Parameter | Optional | Type | Description |
|-----------|-----------|-----------------------------------------------------------------------------|--------------------------|
| stream | no | [Readable](https://nodejs.org/api/stream.html#stream_class_stream_readable) | Stream to read from |
| fileInfo | yes | [IFileInfo](#IFileInfo) | Provide file information |
Returns a [*tokenizer*](#tokenizer), via a Promise, which can be used to parse a buffer.
```js
import strtok3 from 'strtok3';
import * as Token from 'token-types';
strtok3.fromStream(stream).then(tokenizer => {
return tokenizer.readToken(Token.UINT8).then(myUint8Number => {
console.log(`My number: ${myUint8Number}`);
});
});
```
#### Method `strtok3.fromBuffer()`
| Parameter | Optional | Type | Description |
|------------|----------|--------------------------------------------------|----------------------------------------|
| uint8Array | no | [Uint8Array](https://nodejs.org/api/buffer.html) | Uint8Array or Buffer to read from |
| fileInfo | yes | [IFileInfo](#IFileInfo) | Provide file information |
Returns a [*tokenizer*](#tokenizer) which can be used to parse the provided buffer.
```js
import * as strtok3 from 'strtok3';
const tokenizer = strtok3.fromBuffer(buffer);
tokenizer.readToken(Token.UINT8).then(myUint8Number => {
console.log(`My number: ${myUint8Number}`);
});
```
## Tokenizer
The tokenizer allows us to *read* or *peek* from the *tokenizer-stream*. The *tokenizer-stream* is an abstraction of a [stream](https://nodejs.org/api/stream.html), file or [Buffer](https://nodejs.org/api/buffer.html).
It can also be translated in chunked reads, as done in [@tokenizer/http](https://github.com/Borewit/tokenizer-http);
What is the difference with Nodejs.js stream?
* The *tokenizer-stream* supports jumping / seeking in a the *tokenizer-stream* using [`tokenizer.ignore()`](#method-tokenizerignore)
* In addition to *read* methods, it has *peek* methods, to read a ahead and check what is coming.
The [tokenizer.position](#attribute-tokenizerposition) keeps tracks of the read position.
### strtok3 attributes
#### Attribute `tokenizer.fileInfo`
Optional attribute describing the file information, see [IFileInfo](#IFileInfo)
#### Attribute `tokenizer.position`
Pointer to the current position in the [*tokenizer*](#tokenizer) stream.
If a *position* is provided to a *read* or *peek* method, is should be, at least, equal or greater than this value.
### Tokenizer methods
There are two kind of methods:
1. *read* methods: used to read a *token* of [Buffer](https://nodejs.org/api/buffer.html) from the [*tokenizer*](#tokenizer). The position of the *tokenizer-stream* will advance with the size of the token.
2. *peek* methods: same as the read, but it will *not* advance the pointer. It allows to read (peek) ahead.
#### Method `tokenizer.readBuffer()`
Read buffer from stream.
`readBuffer(buffer, options?)`
| Parameter | Type | Description |
|------------|----------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| buffer | [Buffer](https://nodejs.org/api/buffer.html) | Uint8Array | Target buffer to write the data read to |
| options | [IReadChunkOptions](#ireadchunkoptions) | An integer specifying the number of bytes to read |
Return value `Promise<number>` Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set.
#### Method `tokenizer.peekBuffer()`
Peek (read ahead) buffer from [*tokenizer*](#tokenizer)
`peekBuffer(buffer, options?)`
| Parameter | Type | Description |
|------------|-----------------------------------------|-----------------------------------------------------|
| buffer | Buffer &#124; Uint8Array | Target buffer to write the data read (peeked) to. |
| options | [IReadChunkOptions](#ireadchunkoptions) | An integer specifying the number of bytes to read. | |
Return value `Promise<number>` Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set.
#### Method `tokenizer.readToken()`
Read a *token* from the tokenizer-stream.
`readToken(token, position?)`
| Parameter | Type | Description |
|------------|-------------------------|---------------------------------------------------------------------------------------------------------------------- |
| token | [IGetToken](#IGetToken) | Token to read from the tokenizer-stream. |
| position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. |
Return value `Promise<number>`. Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set.
#### Method `tokenizer.peekToken()`
Peek a *token* from the [*tokenizer*](#tokenizer).
`peekToken(token, position?)`
| Parameter | Type | Description |
|------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------|
| token | [IGetToken<T>](#IGetToken) | Token to read from the tokenizer-stream. |
| position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. |
Return value `Promise<T>` Promise with token value peeked from the [*tokenizer*](#tokenizer).
#### Method `tokenizer.readNumber()`
Peek a numeric [*token*](#token) from the [*tokenizer*](#tokenizer).
`readNumber(token)`
| Parameter | Type | Description |
|------------|---------------------------------|----------------------------------------------------|
| token | [IGetToken<number>](#IGetToken) | Numeric token to read from the tokenizer-stream. |
Return value `Promise<number>` Promise with number peeked from the *tokenizer-stream*.
#### Method `tokenizer.ignore()`
Advanse the offset pointer with the number of bytes provided.
`ignore(length)`
| Parameter | Type | Description |
|------------|--------|----------------------------------------------------------------------|
| ignore | number | Numeric of bytes to ignore. Will advance the `tokenizer.position` |
Return value `Promise<number>` Promise with number peeked from the *tokenizer-stream*.
#### Method `tokenizer.close()`
Clean up resources, such as closing a file pointer if applicable.
### IReadChunkOptions
Each attribute is optional:
| Attribute | Type | Description |
|-----------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| offset | number | The offset in the buffer to start writing at; if not provided, start at 0 |
| length | number | Requested number of bytes to read. |
| position | number | Position where to peek from the file. If position is null, data will be read from the [current file position](#attribute-tokenizerposition). Position may not be less then [tokenizer.position](#attribute-tokenizerposition) |
| mayBeLess | boolean | If and only if set, will not throw an EOF error if less then the requested *mayBeLess* could be read. |
Example:
```js
tokenizer.peekBuffer(buffer, {mayBeLess: true});
```
## IFileInfo
File information interface which describes the underlying file, each attribute is optional.
| Attribute | Type | Description |
|-----------|---------|---------------------------------------------------------------------------------------------------|
| size | number | File size in bytes |
| mimeType | number | [MIME-type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) of file. |
| path | number | File path |
| url | boolean | File URL |
## Token
The *token* is basically a description what to read form the [*tokenizer-stream*](#tokenizer).
A basic set of *token types* can be found here: [*token-types*](https://github.com/Borewit/token-types).
A token is something which implements the following interface:
```ts
export interface IGetToken<T> {
/**
* Length in bytes of encoded value
*/
len: number;
/**
* Decode value from buffer at offset
* @param buf Buffer to read the decoded value from
* @param off Decode offset
*/
get(buf: Buffer, off: number): T;
}
```
The *tokenizer* reads `token.len` bytes from the *tokenizer-stream* into a Buffer.
The `token.get` will be called with the Buffer. `token.get` is responsible for conversion from the buffer to the desired output type.
## Browser compatibility
To exclude fs based dependencies, you can use a submodule-import from 'strtok3/lib/core'.
| function | 'strtok3' | 'strtok3/lib/core' |
| ----------------------| --------------------|---------------------|
| `parseBuffer` | ✓ | ✓ |
| `parseStream` | ✓ | ✓ |
| `fromFile` | ✓ | |
### Working with Web-API readable stream
To convert a [Web-API readable stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader) into a [Node.js readable stream]((https://nodejs.org/api/stream.html#stream_readable_streams)), you can use [readable-web-to-node-stream](https://github.com/Borewit/readable-web-to-node-stream) to convert one in another.
Example submodule-import:
```js
import * as strtok3core from 'strtok3/core'; // Submodule-import to prevent Node.js specific dependencies
import { ReadableWebToNodeStream } from 'readable-web-to-node-stream';
(async () => {
const response = await fetch(url);
const readableWebStream = response.body; // Web-API readable stream
const nodeStream = new ReadableWebToNodeStream(readableWebStream); // convert to Node.js readable stream
const tokenizer = strtok3core.fromStream(nodeStream); // And we now have tokenizer in a web environment
})();
```
## Licence
(The MIT License)
Copyright (c) 2020 Borewit
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.

69
node_modules/strtok3/lib/AbstractTokenizer.d.ts generated vendored Normal file
View file

@ -0,0 +1,69 @@
import { ITokenizer, IFileInfo, IReadChunkOptions } from './types.js';
import { IGetToken, IToken } from '@tokenizer/token';
interface INormalizedReadChunkOptions extends IReadChunkOptions {
offset: number;
length: number;
position: number;
mayBeLess?: boolean;
}
/**
* Core tokenizer
*/
export declare abstract class AbstractTokenizer implements ITokenizer {
fileInfo: IFileInfo;
protected constructor(fileInfo?: IFileInfo);
/**
* Tokenizer-stream position
*/
position: number;
private numBuffer;
/**
* Read buffer from tokenizer
* @param buffer - Target buffer to fill with data read from the tokenizer-stream
* @param options - Additional read options
* @returns Promise with number of bytes read
*/
abstract readBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise<number>;
/**
* Peek (read ahead) buffer from tokenizer
* @param uint8Array- Target buffer to fill with data peek from the tokenizer-stream
* @param options - Peek behaviour options
* @returns Promise with number of bytes read
*/
abstract peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise<number>;
/**
* Read a token from the tokenizer-stream
* @param token - The token to read
* @param position - If provided, the desired position in the tokenizer-stream
* @returns Promise with token data
*/
readToken<Value>(token: IGetToken<Value>, position?: number): Promise<Value>;
/**
* Peek a token from the tokenizer-stream.
* @param token - Token to peek from the tokenizer-stream.
* @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position.
* @returns Promise with token data
*/
peekToken<Value>(token: IGetToken<Value>, position?: number): Promise<Value>;
/**
* Read a numeric token from the stream
* @param token - Numeric token
* @returns Promise with number
*/
readNumber(token: IToken<number>): Promise<number>;
/**
* Read a numeric token from the stream
* @param token - Numeric token
* @returns Promise with number
*/
peekNumber(token: IToken<number>): Promise<number>;
/**
* Ignore number of bytes, advances the pointer in under tokenizer-stream.
* @param length - Number of bytes to ignore
* @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available
*/
ignore(length: number): Promise<number>;
close(): Promise<void>;
protected normalizeOptions(uint8Array: Uint8Array, options?: IReadChunkOptions): INormalizedReadChunkOptions;
}
export {};

101
node_modules/strtok3/lib/AbstractTokenizer.js generated vendored Normal file
View file

@ -0,0 +1,101 @@
import { EndOfStreamError } from 'peek-readable';
import { Buffer } from 'node:buffer';
/**
* Core tokenizer
*/
export class AbstractTokenizer {
constructor(fileInfo) {
/**
* Tokenizer-stream position
*/
this.position = 0;
this.numBuffer = new Uint8Array(8);
this.fileInfo = fileInfo ? fileInfo : {};
}
/**
* Read a token from the tokenizer-stream
* @param token - The token to read
* @param position - If provided, the desired position in the tokenizer-stream
* @returns Promise with token data
*/
async readToken(token, position = this.position) {
const uint8Array = Buffer.alloc(token.len);
const len = await this.readBuffer(uint8Array, { position });
if (len < token.len)
throw new EndOfStreamError();
return token.get(uint8Array, 0);
}
/**
* Peek a token from the tokenizer-stream.
* @param token - Token to peek from the tokenizer-stream.
* @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position.
* @returns Promise with token data
*/
async peekToken(token, position = this.position) {
const uint8Array = Buffer.alloc(token.len);
const len = await this.peekBuffer(uint8Array, { position });
if (len < token.len)
throw new EndOfStreamError();
return token.get(uint8Array, 0);
}
/**
* Read a numeric token from the stream
* @param token - Numeric token
* @returns Promise with number
*/
async readNumber(token) {
const len = await this.readBuffer(this.numBuffer, { length: token.len });
if (len < token.len)
throw new EndOfStreamError();
return token.get(this.numBuffer, 0);
}
/**
* Read a numeric token from the stream
* @param token - Numeric token
* @returns Promise with number
*/
async peekNumber(token) {
const len = await this.peekBuffer(this.numBuffer, { length: token.len });
if (len < token.len)
throw new EndOfStreamError();
return token.get(this.numBuffer, 0);
}
/**
* Ignore number of bytes, advances the pointer in under tokenizer-stream.
* @param length - Number of bytes to ignore
* @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available
*/
async ignore(length) {
if (this.fileInfo.size !== undefined) {
const bytesLeft = this.fileInfo.size - this.position;
if (length > bytesLeft) {
this.position += bytesLeft;
return bytesLeft;
}
}
this.position += length;
return length;
}
async close() {
// empty
}
normalizeOptions(uint8Array, options) {
if (options && options.position !== undefined && options.position < this.position) {
throw new Error('`options.position` must be equal or greater than `tokenizer.position`');
}
if (options) {
return {
mayBeLess: options.mayBeLess === true,
offset: options.offset ? options.offset : 0,
length: options.length ? options.length : (uint8Array.length - (options.offset ? options.offset : 0)),
position: options.position ? options.position : this.position
};
}
return {
mayBeLess: false,
offset: 0,
length: uint8Array.length,
position: this.position
};
}
}

26
node_modules/strtok3/lib/BufferTokenizer.d.ts generated vendored Normal file
View file

@ -0,0 +1,26 @@
import { IFileInfo, IReadChunkOptions } from './types.js';
import { AbstractTokenizer } from './AbstractTokenizer.js';
export declare class BufferTokenizer extends AbstractTokenizer {
private uint8Array;
/**
* Construct BufferTokenizer
* @param uint8Array - Uint8Array to tokenize
* @param fileInfo - Pass additional file information to the tokenizer
*/
constructor(uint8Array: Uint8Array, fileInfo?: IFileInfo);
/**
* Read buffer from tokenizer
* @param uint8Array - Uint8Array to tokenize
* @param options - Read behaviour options
* @returns {Promise<number>}
*/
readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise<number>;
/**
* Peek (read ahead) buffer from tokenizer
* @param uint8Array
* @param options - Read behaviour options
* @returns {Promise<number>}
*/
peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise<number>;
close(): Promise<void>;
}

51
node_modules/strtok3/lib/BufferTokenizer.js generated vendored Normal file
View file

@ -0,0 +1,51 @@
import { EndOfStreamError } from 'peek-readable';
import { AbstractTokenizer } from './AbstractTokenizer.js';
export class BufferTokenizer extends AbstractTokenizer {
/**
* Construct BufferTokenizer
* @param uint8Array - Uint8Array to tokenize
* @param fileInfo - Pass additional file information to the tokenizer
*/
constructor(uint8Array, fileInfo) {
super(fileInfo);
this.uint8Array = uint8Array;
this.fileInfo.size = this.fileInfo.size ? this.fileInfo.size : uint8Array.length;
}
/**
* Read buffer from tokenizer
* @param uint8Array - Uint8Array to tokenize
* @param options - Read behaviour options
* @returns {Promise<number>}
*/
async readBuffer(uint8Array, options) {
if (options && options.position) {
if (options.position < this.position) {
throw new Error('`options.position` must be equal or greater than `tokenizer.position`');
}
this.position = options.position;
}
const bytesRead = await this.peekBuffer(uint8Array, options);
this.position += bytesRead;
return bytesRead;
}
/**
* Peek (read ahead) buffer from tokenizer
* @param uint8Array
* @param options - Read behaviour options
* @returns {Promise<number>}
*/
async peekBuffer(uint8Array, options) {
const normOptions = this.normalizeOptions(uint8Array, options);
const bytes2read = Math.min(this.uint8Array.length - normOptions.position, normOptions.length);
if ((!normOptions.mayBeLess) && bytes2read < normOptions.length) {
throw new EndOfStreamError();
}
else {
uint8Array.set(this.uint8Array.subarray(normOptions.position, normOptions.position + bytes2read), normOptions.offset);
return bytes2read;
}
}
async close() {
// empty
}
}

22
node_modules/strtok3/lib/FileTokenizer.d.ts generated vendored Normal file
View file

@ -0,0 +1,22 @@
import { AbstractTokenizer } from './AbstractTokenizer.js';
import { IFileInfo, IReadChunkOptions } from './types.js';
export declare class FileTokenizer extends AbstractTokenizer {
private fd;
constructor(fd: number, fileInfo: IFileInfo);
/**
* Read buffer from file
* @param uint8Array - Uint8Array to write result to
* @param options - Read behaviour options
* @returns Promise number of bytes read
*/
readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise<number>;
/**
* Peek buffer from file
* @param uint8Array - Uint8Array (or Buffer) to write data to
* @param options - Read behaviour options
* @returns Promise number of bytes read
*/
peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise<number>;
close(): Promise<void>;
}
export declare function fromFile(sourceFilePath: string): Promise<FileTokenizer>;

50
node_modules/strtok3/lib/FileTokenizer.js generated vendored Normal file
View file

@ -0,0 +1,50 @@
import { AbstractTokenizer } from './AbstractTokenizer.js';
import { EndOfStreamError } from 'peek-readable';
import * as fs from './FsPromise.js';
export class FileTokenizer extends AbstractTokenizer {
constructor(fd, fileInfo) {
super(fileInfo);
this.fd = fd;
}
/**
* Read buffer from file
* @param uint8Array - Uint8Array to write result to
* @param options - Read behaviour options
* @returns Promise number of bytes read
*/
async readBuffer(uint8Array, options) {
const normOptions = this.normalizeOptions(uint8Array, options);
this.position = normOptions.position;
const res = await fs.read(this.fd, uint8Array, normOptions.offset, normOptions.length, normOptions.position);
this.position += res.bytesRead;
if (res.bytesRead < normOptions.length && (!options || !options.mayBeLess)) {
throw new EndOfStreamError();
}
return res.bytesRead;
}
/**
* Peek buffer from file
* @param uint8Array - Uint8Array (or Buffer) to write data to
* @param options - Read behaviour options
* @returns Promise number of bytes read
*/
async peekBuffer(uint8Array, options) {
const normOptions = this.normalizeOptions(uint8Array, options);
const res = await fs.read(this.fd, uint8Array, normOptions.offset, normOptions.length, normOptions.position);
if ((!normOptions.mayBeLess) && res.bytesRead < normOptions.length) {
throw new EndOfStreamError();
}
return res.bytesRead;
}
async close() {
return fs.close(this.fd);
}
}
export async function fromFile(sourceFilePath) {
const stat = await fs.stat(sourceFilePath);
if (!stat.isFile) {
throw new Error(`File not a file: ${sourceFilePath}`);
}
const fd = await fs.open(sourceFilePath, 'r');
return new FileTokenizer(fd, { path: sourceFilePath, size: stat.size });
}

19
node_modules/strtok3/lib/FsPromise.d.ts generated vendored Normal file
View file

@ -0,0 +1,19 @@
/**
* Module convert fs functions to promise based functions
*/
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
import fs from 'node:fs';
export interface IReadResult {
bytesRead: number;
buffer: Uint8Array;
}
export declare const pathExists: typeof fs.existsSync;
export declare const createReadStream: typeof fs.createReadStream;
export declare function stat(path: fs.PathLike): Promise<fs.Stats>;
export declare function close(fd: number): Promise<void>;
export declare function open(path: fs.PathLike, mode: fs.Mode): Promise<number>;
export declare function read(fd: number, buffer: Uint8Array, offset: number, length: number, position: number): Promise<IReadResult>;
export declare function writeFile(path: fs.PathLike, data: Buffer | string): Promise<void>;
export declare function writeFileSync(path: fs.PathLike, data: Buffer | string): void;
export declare function readFile(path: fs.PathLike): Promise<Buffer>;

69
node_modules/strtok3/lib/FsPromise.js generated vendored Normal file
View file

@ -0,0 +1,69 @@
/**
* Module convert fs functions to promise based functions
*/
import fs from 'node:fs';
export const pathExists = fs.existsSync;
export const createReadStream = fs.createReadStream;
export async function stat(path) {
return new Promise((resolve, reject) => {
fs.stat(path, (err, stats) => {
if (err)
reject(err);
else
resolve(stats);
});
});
}
export async function close(fd) {
return new Promise((resolve, reject) => {
fs.close(fd, err => {
if (err)
reject(err);
else
resolve();
});
});
}
export async function open(path, mode) {
return new Promise((resolve, reject) => {
fs.open(path, mode, (err, fd) => {
if (err)
reject(err);
else
resolve(fd);
});
});
}
export async function read(fd, buffer, offset, length, position) {
return new Promise((resolve, reject) => {
fs.read(fd, buffer, offset, length, position, (err, bytesRead, _buffer) => {
if (err)
reject(err);
else
resolve({ bytesRead, buffer: _buffer });
});
});
}
export async function writeFile(path, data) {
return new Promise((resolve, reject) => {
fs.writeFile(path, data, err => {
if (err)
reject(err);
else
resolve();
});
});
}
export function writeFileSync(path, data) {
fs.writeFileSync(path, data);
}
export async function readFile(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, (err, buffer) => {
if (err)
reject(err);
else
resolve(buffer);
});
});
}

28
node_modules/strtok3/lib/ReadStreamTokenizer.d.ts generated vendored Normal file
View file

@ -0,0 +1,28 @@
/// <reference types="node" resolution-mode="require"/>
import { AbstractTokenizer } from './AbstractTokenizer.js';
import { Readable } from 'node:stream';
import { IFileInfo, IReadChunkOptions } from './types.js';
export declare class ReadStreamTokenizer extends AbstractTokenizer {
private streamReader;
constructor(stream: Readable, fileInfo?: IFileInfo);
/**
* Get file information, an HTTP-client may implement this doing a HEAD request
* @return Promise with file information
*/
getFileInfo(): Promise<IFileInfo>;
/**
* Read buffer from tokenizer
* @param uint8Array - Target Uint8Array to fill with data read from the tokenizer-stream
* @param options - Read behaviour options
* @returns Promise with number of bytes read
*/
readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise<number>;
/**
* Peek (read ahead) buffer from tokenizer
* @param uint8Array - Uint8Array (or Buffer) to write data to
* @param options - Read behaviour options
* @returns Promise with number of bytes peeked
*/
peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise<number>;
ignore(length: number): Promise<number>;
}

94
node_modules/strtok3/lib/ReadStreamTokenizer.js generated vendored Normal file
View file

@ -0,0 +1,94 @@
import { AbstractTokenizer } from './AbstractTokenizer.js';
import { EndOfStreamError, StreamReader } from 'peek-readable';
const maxBufferSize = 256000;
export class ReadStreamTokenizer extends AbstractTokenizer {
constructor(stream, fileInfo) {
super(fileInfo);
this.streamReader = new StreamReader(stream);
}
/**
* Get file information, an HTTP-client may implement this doing a HEAD request
* @return Promise with file information
*/
async getFileInfo() {
return this.fileInfo;
}
/**
* Read buffer from tokenizer
* @param uint8Array - Target Uint8Array to fill with data read from the tokenizer-stream
* @param options - Read behaviour options
* @returns Promise with number of bytes read
*/
async readBuffer(uint8Array, options) {
const normOptions = this.normalizeOptions(uint8Array, options);
const skipBytes = normOptions.position - this.position;
if (skipBytes > 0) {
await this.ignore(skipBytes);
return this.readBuffer(uint8Array, options);
}
else if (skipBytes < 0) {
throw new Error('`options.position` must be equal or greater than `tokenizer.position`');
}
if (normOptions.length === 0) {
return 0;
}
const bytesRead = await this.streamReader.read(uint8Array, normOptions.offset, normOptions.length);
this.position += bytesRead;
if ((!options || !options.mayBeLess) && bytesRead < normOptions.length) {
throw new EndOfStreamError();
}
return bytesRead;
}
/**
* Peek (read ahead) buffer from tokenizer
* @param uint8Array - Uint8Array (or Buffer) to write data to
* @param options - Read behaviour options
* @returns Promise with number of bytes peeked
*/
async peekBuffer(uint8Array, options) {
const normOptions = this.normalizeOptions(uint8Array, options);
let bytesRead = 0;
if (normOptions.position) {
const skipBytes = normOptions.position - this.position;
if (skipBytes > 0) {
const skipBuffer = new Uint8Array(normOptions.length + skipBytes);
bytesRead = await this.peekBuffer(skipBuffer, { mayBeLess: normOptions.mayBeLess });
uint8Array.set(skipBuffer.subarray(skipBytes), normOptions.offset);
return bytesRead - skipBytes;
}
else if (skipBytes < 0) {
throw new Error('Cannot peek from a negative offset in a stream');
}
}
if (normOptions.length > 0) {
try {
bytesRead = await this.streamReader.peek(uint8Array, normOptions.offset, normOptions.length);
}
catch (err) {
if (options && options.mayBeLess && err instanceof EndOfStreamError) {
return 0;
}
throw err;
}
if ((!normOptions.mayBeLess) && bytesRead < normOptions.length) {
throw new EndOfStreamError();
}
}
return bytesRead;
}
async ignore(length) {
// debug(`ignore ${this.position}...${this.position + length - 1}`);
const bufSize = Math.min(maxBufferSize, length);
const buf = new Uint8Array(bufSize);
let totBytesRead = 0;
while (totBytesRead < length) {
const remaining = length - totBytesRead;
const bytesRead = await this.readBuffer(buf, { length: Math.min(bufSize, remaining) });
if (bytesRead < 0) {
return bytesRead;
}
totBytesRead += bytesRead;
}
return totBytesRead;
}
}

23
node_modules/strtok3/lib/core.d.ts generated vendored Normal file
View file

@ -0,0 +1,23 @@
/// <reference types="node" resolution-mode="require"/>
import { ReadStreamTokenizer } from './ReadStreamTokenizer.js';
import { Readable } from 'node:stream';
import { BufferTokenizer } from './BufferTokenizer.js';
import { IFileInfo } from './types.js';
export { EndOfStreamError } from 'peek-readable';
export { ITokenizer, IFileInfo } from './types.js';
export { IToken, IGetToken } from '@tokenizer/token';
/**
* Construct ReadStreamTokenizer from given Stream.
* Will set fileSize, if provided given Stream has set the .path property/
* @param stream - Read from Node.js Stream.Readable
* @param fileInfo - Pass the file information, like size and MIME-type of the corresponding stream.
* @returns ReadStreamTokenizer
*/
export declare function fromStream(stream: Readable, fileInfo?: IFileInfo): ReadStreamTokenizer;
/**
* Construct ReadStreamTokenizer from given Buffer.
* @param uint8Array - Uint8Array to tokenize
* @param fileInfo - Pass additional file information to the tokenizer
* @returns BufferTokenizer
*/
export declare function fromBuffer(uint8Array: Uint8Array, fileInfo?: IFileInfo): BufferTokenizer;

23
node_modules/strtok3/lib/core.js generated vendored Normal file
View file

@ -0,0 +1,23 @@
import { ReadStreamTokenizer } from './ReadStreamTokenizer.js';
import { BufferTokenizer } from './BufferTokenizer.js';
export { EndOfStreamError } from 'peek-readable';
/**
* Construct ReadStreamTokenizer from given Stream.
* Will set fileSize, if provided given Stream has set the .path property/
* @param stream - Read from Node.js Stream.Readable
* @param fileInfo - Pass the file information, like size and MIME-type of the corresponding stream.
* @returns ReadStreamTokenizer
*/
export function fromStream(stream, fileInfo) {
fileInfo = fileInfo ? fileInfo : {};
return new ReadStreamTokenizer(stream, fileInfo);
}
/**
* Construct ReadStreamTokenizer from given Buffer.
* @param uint8Array - Uint8Array to tokenize
* @param fileInfo - Pass additional file information to the tokenizer
* @returns BufferTokenizer
*/
export function fromBuffer(uint8Array, fileInfo) {
return new BufferTokenizer(uint8Array, fileInfo);
}

15
node_modules/strtok3/lib/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,15 @@
/// <reference types="node" resolution-mode="require"/>
import { Readable } from 'node:stream';
import { ReadStreamTokenizer } from './ReadStreamTokenizer.js';
import * as core from './core.js';
export { fromFile } from './FileTokenizer.js';
export { ITokenizer, EndOfStreamError, fromBuffer, IFileInfo } from './core.js';
export { IToken, IGetToken } from '@tokenizer/token';
/**
* Construct ReadStreamTokenizer from given Stream.
* Will set fileSize, if provided given Stream has set the .path property.
* @param stream - Node.js Stream.Readable
* @param fileInfo - Pass additional file information to the tokenizer
* @returns Tokenizer
*/
export declare function fromStream(stream: Readable, fileInfo?: core.IFileInfo): Promise<ReadStreamTokenizer>;

20
node_modules/strtok3/lib/index.js generated vendored Normal file
View file

@ -0,0 +1,20 @@
import * as fs from './FsPromise.js';
import * as core from './core.js';
export { fromFile } from './FileTokenizer.js';
export { EndOfStreamError, fromBuffer } from './core.js';
/**
* Construct ReadStreamTokenizer from given Stream.
* Will set fileSize, if provided given Stream has set the .path property.
* @param stream - Node.js Stream.Readable
* @param fileInfo - Pass additional file information to the tokenizer
* @returns Tokenizer
*/
export async function fromStream(stream, fileInfo) {
fileInfo = fileInfo ? fileInfo : {};
if (stream.path) {
const stat = await fs.stat(stream.path);
fileInfo.path = stream.path;
fileInfo.size = stat.size;
}
return core.fromStream(stream, fileInfo);
}

103
node_modules/strtok3/lib/types.d.ts generated vendored Normal file
View file

@ -0,0 +1,103 @@
/// <reference types="node" resolution-mode="require"/>
import { IGetToken } from '@tokenizer/token';
export interface IFileInfo {
/**
* File size in bytes
*/
size?: number;
/**
* MIME-type of file
*/
mimeType?: string;
/**
* File path
*/
path?: string;
/**
* File URL
*/
url?: string;
}
export interface IReadChunkOptions {
/**
* The offset in the buffer to start writing at; default is 0
*/
offset?: number;
/**
* Number of bytes to read.
*/
length?: number;
/**
* Position where to begin reading from the file.
* Default it is `tokenizer.position`.
* Position may not be less then `tokenizer.position`.
*/
position?: number;
/**
* If set, will not throw an EOF error if not all of the requested data could be read
*/
mayBeLess?: boolean;
}
/**
* The tokenizer allows us to read or peek from the tokenizer-stream.
* The tokenizer-stream is an abstraction of a stream, file or Buffer.
*/
export interface ITokenizer {
/**
* Provide access to information of the underlying information stream or file.
*/
fileInfo: IFileInfo;
/**
* Offset in bytes (= number of bytes read) since beginning of file or stream
*/
position: number;
/**
* Peek (read ahead) buffer from tokenizer
* @param buffer - Target buffer to fill with data peek from the tokenizer-stream
* @param options - Read behaviour options
* @returns Promise with number of bytes read
*/
peekBuffer(buffer: Buffer, options?: IReadChunkOptions): Promise<number>;
/**
* Peek (read ahead) buffer from tokenizer
* @param buffer - Target buffer to fill with data peeked from the tokenizer-stream
* @param options - Additional read options
* @returns Promise with number of bytes read
*/
readBuffer(buffer: Buffer, options?: IReadChunkOptions): Promise<number>;
/**
* Peek a token from the tokenizer-stream.
* @param token - Token to peek from the tokenizer-stream.
* @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position.
* @param maybeless - If set, will not throw an EOF error if the less then the requested length could be read.
*/
peekToken<T>(token: IGetToken<T>, position?: number | null, maybeless?: boolean): Promise<T>;
/**
* Read a token from the tokenizer-stream.
* @param token - Token to peek from the tokenizer-stream.
* @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position.
*/
readToken<T>(token: IGetToken<T>, position?: number): Promise<T>;
/**
* Peek a numeric token from the stream
* @param token - Numeric token
* @returns Promise with number
*/
peekNumber(token: IGetToken<number>): Promise<number>;
/**
* Read a numeric token from the stream
* @param token - Numeric token
* @returns Promise with number
*/
readNumber(token: IGetToken<number>): Promise<number>;
/**
* Ignore given number of bytes
* @param length - Number of bytes ignored
*/
ignore(length: number): Promise<number>;
/**
* Clean up resources.
* It does not close the stream for StreamReader, but is does close the file-descriptor.
*/
close(): Promise<void>;
}

1
node_modules/strtok3/lib/types.js generated vendored Normal file
View file

@ -0,0 +1 @@
export {};

94
node_modules/strtok3/package.json generated vendored Normal file
View file

@ -0,0 +1,94 @@
{
"name": "strtok3",
"version": "7.0.0",
"description": "A promise based streaming tokenizer",
"author": {
"name": "Borewit",
"url": "https://github.com/Borewit"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Borewit"
},
"scripts": {
"clean": "del-cli lib/**/*.js lib/**/*.js.map lib/**/*.d.ts test/**/*.js test/**/*.js.map",
"compile-src": "tsc -p lib",
"compile-test": "tsc -p test",
"compile": "npm run compile-src && npm run compile-test",
"build": "npm run clean && npm run compile",
"eslint": "eslint lib test --ext .ts --ignore-pattern *.d.ts",
"lint-md": "remark -u preset-lint-recommended .",
"lint": "npm run lint-md && npm run eslint",
"fix": "eslint lib test --ext .ts --ignore-pattern *.d.ts --fix",
"test": "mocha",
"test-coverage": "c8 npm run test",
"send-codacy": "c8 report --reporter=text-lcov | codacy-coverage",
"start": "npm run compile && npm run lint && npm run cover-test"
},
"engines": {
"node": ">=14.16"
},
"repository": {
"type": "git",
"url": "https://github.com/Borewit/strtok3.git"
},
"license": "MIT",
"type": "module",
"exports": {
".": {
"node": "./lib/index.js",
"default": "./lib/core.js"
},
"./core": "./lib/core.js"
},
"types": "lib/index.d.ts",
"files": [
"lib/**/*.js",
"lib/**/*.d.ts"
],
"bugs": {
"url": "https://github.com/Borewit/strtok3/issues"
},
"devDependencies": {
"@types/chai": "^4.3.1",
"@types/debug": "^4.1.7",
"@types/mocha": "^9.1.0",
"@types/node": "^18.6.3",
"@typescript-eslint/eslint-plugin": "^5.32.0",
"@typescript-eslint/parser": "^5.32.0",
"c8": "^7.12.0",
"chai": "^4.3.6",
"del-cli": "^5.0.0",
"eslint": "^8.21.0",
"eslint-config-prettier": "^8.5.0",
"eslint-import-resolver-typescript": "^3.4.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-jsdoc": "^39.3.4",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-unicorn": "^43.0.2",
"mocha": "^10.0.0",
"remark-cli": "^11.0.0",
"remark-preset-lint-recommended": "^6.1.2",
"token-types": "^5.0.0",
"ts-node": "^10.9.1",
"typescript": "^4.7.4"
},
"dependencies": {
"@tokenizer/token": "^0.3.0",
"peek-readable": "^5.0.0"
},
"keywords": [
"tokenizer",
"reader",
"token",
"async",
"promise",
"parser",
"decoder",
"binary",
"endian",
"uint",
"stream",
"streaming"
]
}