first commit

This commit is contained in:
Stefan Hacker
2026-04-03 09:38:48 +02:00
commit 37ad745546
47450 changed files with 3120798 additions and 0 deletions
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 Vadims @streamich Daleckis <vadimsdaleckis@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+87
View File
@@ -0,0 +1,87 @@
# @jsonjoy.com/fs-snapshot
File system snapshot - serialize and deserialize file system trees to binary (CBOR) or JSON format.
## Installation
```bash
npm install @jsonjoy.com/fs-snapshot
```
## Features
- Serialize entire file system trees into compact binary (CBOR) or JSON snapshots
- Restore file system trees from snapshots
- Supports files, directories, and symbolic links
- Both synchronous and asynchronous APIs
- Works with any Node.js-compatible `fs` module
## Usage
### Synchronous API
```ts
import * as fs from 'fs';
import { toSnapshotSync, fromSnapshotSync } from '@jsonjoy.com/fs-snapshot';
// Create a snapshot of a directory
const snapshot = toSnapshotSync({ fs, path: '/path/to/directory' });
// Restore the snapshot to a different location
fromSnapshotSync(snapshot, { fs, path: '/path/to/restore' });
```
### Asynchronous API
```ts
import * as fs from 'fs';
import { toSnapshot, fromSnapshot } from '@jsonjoy.com/fs-snapshot';
// Create a snapshot of a directory
const snapshot = await toSnapshot({ fs: fs.promises, path: '/path/to/directory' });
// Restore the snapshot to a different location
await fromSnapshot(snapshot, { fs: fs.promises, path: '/path/to/restore' });
```
### Binary (CBOR) Snapshots
Binary snapshots are more compact and faster to serialize/deserialize:
```ts
import * as fs from 'fs';
import { toBinarySnapshotSync, fromBinarySnapshotSync } from '@jsonjoy.com/fs-snapshot';
// Create a binary snapshot
const binary = toBinarySnapshotSync({ fs, path: '/path/to/directory' });
// Restore from binary snapshot
fromBinarySnapshotSync(binary, { fs, path: '/path/to/restore' });
```
### JSON Snapshots
JSON snapshots are human-readable and easier to debug:
```ts
import * as fs from 'fs';
import { toJsonSnapshotSync, fromJsonSnapshotSync } from '@jsonjoy.com/fs-snapshot';
// Create a JSON snapshot
const jsonSnapshot = toJsonSnapshotSync({ fs, path: '/path/to/directory' });
// Restore from JSON snapshot
fromJsonSnapshotSync(jsonSnapshot, { fs, path: '/path/to/restore' });
```
## Snapshot Format
Snapshots are represented as tuples with the following structure:
- **Folder**: `[0, metadata, { entries }]`
- **File**: `[1, metadata, Uint8Array]`
- **Symlink**: `[2, { target: string }]`
## License
Apache-2.0
+3
View File
@@ -0,0 +1,3 @@
import type { AsyncSnapshotOptions, SnapshotNode } from './types';
export declare const toSnapshot: ({ fs, path, separator }: AsyncSnapshotOptions) => Promise<SnapshotNode>;
export declare const fromSnapshot: (snapshot: SnapshotNode, { fs, path, separator }: AsyncSnapshotOptions) => Promise<void>;
+59
View File
@@ -0,0 +1,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromSnapshot = exports.toSnapshot = void 0;
const toSnapshot = async ({ fs, path = '/', separator = '/' }) => {
const stats = await fs.lstat(path);
if (stats.isDirectory()) {
const list = await fs.readdir(path);
const entries = {};
const dir = path.endsWith(separator) ? path : path + separator;
const snapshots = await Promise.all(list.map(child => (0, exports.toSnapshot)({ fs, path: `${dir}${child}`, separator })));
for (let i = 0; i < list.length; i++) {
if (snapshots[i])
entries['' + list[i]] = snapshots[i];
}
return [0 /* SnapshotNodeType.Folder */, {}, entries];
}
else if (stats.isFile()) {
const buf = (await fs.readFile(path));
const uint8 = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
return [1 /* SnapshotNodeType.File */, {}, uint8];
}
else if (stats.isSymbolicLink()) {
return [
2 /* SnapshotNodeType.Symlink */,
{
target: (await fs.readlink(path, { encoding: 'utf8' })),
},
];
}
return null;
};
exports.toSnapshot = toSnapshot;
const fromSnapshot = async (snapshot, { fs, path = '/', separator = '/' }) => {
if (!snapshot)
return;
switch (snapshot[0]) {
case 0 /* SnapshotNodeType.Folder */: {
if (!path.endsWith(separator))
path = path + separator;
const [, , entries] = snapshot;
await fs.mkdir(path, { recursive: true });
for (const [name, child] of Object.entries(entries))
await (0, exports.fromSnapshot)(child, { fs, path: `${path}${name}`, separator });
break;
}
case 1 /* SnapshotNodeType.File */: {
const [, , data] = snapshot;
await fs.writeFile(path, data);
break;
}
case 2 /* SnapshotNodeType.Symlink */: {
const [, { target }] = snapshot;
await fs.symlink(target, path);
break;
}
}
};
exports.fromSnapshot = fromSnapshot;
//# sourceMappingURL=async.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"async.js","sourceRoot":"","sources":["../src/async.ts"],"names":[],"mappings":";;;AAGO,MAAM,UAAU,GAAG,KAAK,EAAE,EAAE,EAAE,EAAE,IAAI,GAAG,GAAG,EAAE,SAAS,GAAG,GAAG,EAAwB,EAAyB,EAAE;IACnH,MAAM,KAAK,GAAG,MAAM,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACnC,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE,CAAC;QACxB,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACpC,MAAM,OAAO,GAAsC,EAAE,CAAC;QACtD,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG,SAAS,CAAC;QAC/D,MAAM,SAAS,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,IAAA,kBAAU,EAAC,EAAE,EAAE,EAAE,IAAI,EAAE,GAAG,GAAG,GAAG,KAAK,EAAE,EAAE,SAAS,EAAE,CAAC,C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AE,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;YACvD,MAAM,CAAC,EAAE,AAAD,EAAG,OAAO,CAAC,GAAG,QAAQ,CAAC;YAC/B,MAAM,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YAC1C,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;gBACjD,MAAM,IAAA,oBAAY,EAAC,KAAK,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,GAAG,IAAI,GAAG,IAAI,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC;YACvE,MAAM;QACR,CAAC;QACD,kCAA0B,CAAC,CAAC,CAAC;YAC3B,MAAM,CAAC,EAAE,AAAD,EAAG,IAAI,CAAC,GAAG,QAAQ,CAAC;YAC5B,MAAM,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAC/B,MAAM;QACR,CAAC;QACD,qCAA6B,CAAC,CAAC,CAAC;YAC9B,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC,GAAG,QAAQ,CAAC;YAChC,MAAM,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;YAC/B,MAAM;QACR,CAAC;IACH,CAAC;AACH,CAAC,CAAC;AAzBW,QAAA,YAAY,gBAyBvB"}
+6
View File
@@ -0,0 +1,6 @@
import type { CborUint8Array } from '@jsonjoy.com/json-pack/lib/cbor/types';
import type { AsyncSnapshotOptions, SnapshotNode, SnapshotOptions } from './types';
export declare const toBinarySnapshotSync: (options: SnapshotOptions) => CborUint8Array<SnapshotNode>;
export declare const fromBinarySnapshotSync: (uint8: CborUint8Array<SnapshotNode>, options: SnapshotOptions) => void;
export declare const toBinarySnapshot: (options: AsyncSnapshotOptions) => Promise<CborUint8Array<SnapshotNode>>;
export declare const fromBinarySnapshot: (uint8: CborUint8Array<SnapshotNode>, options: AsyncSnapshotOptions) => Promise<void>;
+31
View File
@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromBinarySnapshot = exports.toBinarySnapshot = exports.fromBinarySnapshotSync = exports.toBinarySnapshotSync = void 0;
const CborEncoder_1 = require("@jsonjoy.com/json-pack/lib/cbor/CborEncoder");
const CborDecoder_1 = require("@jsonjoy.com/json-pack/lib/cbor/CborDecoder");
const sync_1 = require("./sync");
const async_1 = require("./async");
const shared_1 = require("./shared");
const encoder = new CborEncoder_1.CborEncoder(shared_1.writer);
const decoder = new CborDecoder_1.CborDecoder();
const toBinarySnapshotSync = (options) => {
const snapshot = (0, sync_1.toSnapshotSync)(options);
return encoder.encode(snapshot);
};
exports.toBinarySnapshotSync = toBinarySnapshotSync;
const fromBinarySnapshotSync = (uint8, options) => {
const snapshot = decoder.decode(uint8);
(0, sync_1.fromSnapshotSync)(snapshot, options);
};
exports.fromBinarySnapshotSync = fromBinarySnapshotSync;
const toBinarySnapshot = async (options) => {
const snapshot = await (0, async_1.toSnapshot)(options);
return encoder.encode(snapshot);
};
exports.toBinarySnapshot = toBinarySnapshot;
const fromBinarySnapshot = async (uint8, options) => {
const snapshot = decoder.decode(uint8);
await (0, async_1.fromSnapshot)(snapshot, options);
};
exports.fromBinarySnapshot = fromBinarySnapshot;
//# sourceMappingURL=binary.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"binary.js","sourceRoot":"","sources":["../src/binary.ts"],"names":[],"mappings":";;;AAAA,6EAA0E;AAC1E,6EAA0E;AAC1E,iCAA0D;AAC1D,mCAAmD;AACnD,qCAAkC;AAIlC,MAAM,OAAO,GAAG,IAAI,yBAAW,CAAC,eAAM,CAAC,CAAC;AACxC,MAAM,OAAO,GAAG,IAAI,yBAAW,EAAE,CAAC;AAE3B,MAAM,oBAAoB,GAAG,CAAC,OAAwB,EAAgC,EAAE;IAC7F,MAAM,QAAQ,GAAG,IAAA,qBAAc,EAAC,OAAO,CAAC,CAAC;IACzC,OAAO,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAiC,CAAC;AAClE,CAAC,CAAC;AAHW,QAAA,oBAAoB,wBAG/B;AAEK,MAAM,sBAAsB,GAAG,CAAC,KAAmC,EAAE,OAAwB,EAAQ,EAAE;IAC5G,MAAM,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,KAAK,CAAiB,CAAC;IACvD,IAAA,uBAAgB,EAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;AACtC,CAAC,CAAC;AAHW,QAAA,sBAAsB,0BAGjC;AAEK,MAAM,gBAAgB,GAAG,KAAK,EAAE,OAA6B,EAAyC,EAAE;IAC7G,MAAM,QAAQ,GAAG,MAAM,IAAA,kBAAU,EAAC,OAAO,CAAC,CAAC;IAC3C,OAAO,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAiC,CAAC;AAClE,CAAC,CAAC;AAHW,QAAA,gBAAgB,oBAG3B;AAEK,MAAM,kBAAkB,GAAG,KAAK,EACrC,KAAmC,EACnC,OAA6B,EACd,EAAE;IACjB,MAAM,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,KAAK,CAAiB,CAAC;IACvD,MAAM,IAAA,oBAAY,EAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;AACxC,CAAC,CAAC;AANW,QAAA,kBAAkB,sBAM7B"}
+5
View File
@@ -0,0 +1,5 @@
export declare const enum SnapshotNodeType {
Folder = 0,
File = 1,
Symlink = 2
}
+3
View File
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=constants.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":""}
+5
View File
@@ -0,0 +1,5 @@
export type * from './types';
export * from './constants';
export * from './sync';
export * from './binary';
export * from './json';
+8
View File
@@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("./constants"), exports);
tslib_1.__exportStar(require("./sync"), exports);
tslib_1.__exportStar(require("./binary"), exports);
tslib_1.__exportStar(require("./json"), exports);
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AACA,sDAA4B;AAC5B,iDAAuB;AACvB,mDAAyB;AACzB,iDAAuB"}
+10
View File
@@ -0,0 +1,10 @@
import type { AsyncSnapshotOptions, SnapshotNode, SnapshotOptions } from './types';
/** @todo Import this type from `json-joy` once it is available. */
export type JsonUint8Array<T> = Uint8Array & {
__BRAND__: 'json';
__TYPE__: T;
};
export declare const toJsonSnapshotSync: (options: SnapshotOptions) => JsonUint8Array<SnapshotNode>;
export declare const fromJsonSnapshotSync: (uint8: JsonUint8Array<SnapshotNode>, options: SnapshotOptions) => void;
export declare const toJsonSnapshot: (options: AsyncSnapshotOptions) => Promise<JsonUint8Array<SnapshotNode>>;
export declare const fromJsonSnapshot: (uint8: JsonUint8Array<SnapshotNode>, options: AsyncSnapshotOptions) => Promise<void>;
+31
View File
@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromJsonSnapshot = exports.toJsonSnapshot = exports.fromJsonSnapshotSync = exports.toJsonSnapshotSync = void 0;
const JsonEncoder_1 = require("@jsonjoy.com/json-pack/lib/json/JsonEncoder");
const JsonDecoder_1 = require("@jsonjoy.com/json-pack/lib/json/JsonDecoder");
const sync_1 = require("./sync");
const async_1 = require("./async");
const shared_1 = require("./shared");
const encoder = new JsonEncoder_1.JsonEncoder(shared_1.writer);
const decoder = new JsonDecoder_1.JsonDecoder();
const toJsonSnapshotSync = (options) => {
const snapshot = (0, sync_1.toSnapshotSync)(options);
return encoder.encode(snapshot);
};
exports.toJsonSnapshotSync = toJsonSnapshotSync;
const fromJsonSnapshotSync = (uint8, options) => {
const snapshot = decoder.read(uint8);
(0, sync_1.fromSnapshotSync)(snapshot, options);
};
exports.fromJsonSnapshotSync = fromJsonSnapshotSync;
const toJsonSnapshot = async (options) => {
const snapshot = await (0, async_1.toSnapshot)(options);
return encoder.encode(snapshot);
};
exports.toJsonSnapshot = toJsonSnapshot;
const fromJsonSnapshot = async (uint8, options) => {
const snapshot = decoder.read(uint8);
await (0, async_1.fromSnapshot)(snapshot, options);
};
exports.fromJsonSnapshot = fromJsonSnapshot;
//# sourceMappingURL=json.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"json.js","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":";;;AAAA,6EAA0E;AAC1E,6EAA0E;AAC1E,iCAA0D;AAC1D,mCAAmD;AACnD,qCAAkC;AAMlC,MAAM,OAAO,GAAG,IAAI,yBAAW,CAAC,eAAM,CAAC,CAAC;AACxC,MAAM,OAAO,GAAG,IAAI,yBAAW,EAAE,CAAC;AAE3B,MAAM,kBAAkB,GAAG,CAAC,OAAwB,EAAgC,EAAE;IAC3F,MAAM,QAAQ,GAAG,IAAA,qBAAc,EAAC,OAAO,CAAC,CAAC;IACzC,OAAO,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAiC,CAAC;AAClE,CAAC,CAAC;AAHW,QAAA,kBAAkB,sBAG7B;AAEK,MAAM,oBAAoB,GAAG,CAAC,KAAmC,EAAE,OAAwB,EAAQ,EAAE;IAC1G,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAiB,CAAC;IACrD,IAAA,uBAAgB,EAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;AACtC,CAAC,CAAC;AAHW,QAAA,oBAAoB,wBAG/B;AAEK,MAAM,cAAc,GAAG,KAAK,EAAE,OAA6B,EAAyC,EAAE;IAC3G,MAAM,QAAQ,GAAG,MAAM,IAAA,kBAAU,EAAC,OAAO,CAAC,CAAC;IAC3C,OAAO,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAiC,CAAC;AAClE,CAAC,CAAC;AAHW,QAAA,cAAc,kBAGzB;AAEK,MAAM,gBAAgB,GAAG,KAAK,EACnC,KAAmC,EACnC,OAA6B,EACd,EAAE;IACjB,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAiB,CAAC;IACrD,MAAM,IAAA,oBAAY,EAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;AACxC,CAAC,CAAC;AANW,QAAA,gBAAgB,oBAM3B"}
+2
View File
@@ -0,0 +1,2 @@
import { Writer } from '@jsonjoy.com/buffers/lib/Writer';
export declare const writer: Writer;
+6
View File
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.writer = void 0;
const Writer_1 = require("@jsonjoy.com/buffers/lib/Writer");
exports.writer = new Writer_1.Writer(1024 * 32);
//# sourceMappingURL=shared.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"shared.js","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"mappings":";;;AAAA,4DAAyD;AAE5C,QAAA,MAAM,GAAG,IAAI,eAAM,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC"}
+3
View File
@@ -0,0 +1,3 @@
import type { SnapshotNode, SnapshotOptions } from './types';
export declare const toSnapshotSync: ({ fs, path, separator }: SnapshotOptions) => SnapshotNode;
export declare const fromSnapshotSync: (snapshot: SnapshotNode, { fs, path, separator }: SnapshotOptions) => void;
+59
View File
@@ -0,0 +1,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromSnapshotSync = exports.toSnapshotSync = void 0;
const toSnapshotSync = ({ fs, path = '/', separator = '/' }) => {
const stats = fs.lstatSync(path);
if (stats.isDirectory()) {
const list = fs.readdirSync(path);
const entries = {};
const dir = path.endsWith(separator) ? path : path + separator;
for (const child of list) {
const childSnapshot = (0, exports.toSnapshotSync)({ fs, path: `${dir}${child}`, separator });
if (childSnapshot)
entries['' + child] = childSnapshot;
}
return [0 /* SnapshotNodeType.Folder */, {}, entries];
}
else if (stats.isFile()) {
const buf = fs.readFileSync(path);
const uint8 = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
return [1 /* SnapshotNodeType.File */, {}, uint8];
}
else if (stats.isSymbolicLink()) {
return [
2 /* SnapshotNodeType.Symlink */,
{
target: fs.readlinkSync(path).toString(),
},
];
}
return null;
};
exports.toSnapshotSync = toSnapshotSync;
const fromSnapshotSync = (snapshot, { fs, path = '/', separator = '/' }) => {
if (!snapshot)
return;
switch (snapshot[0]) {
case 0 /* SnapshotNodeType.Folder */: {
if (!path.endsWith(separator))
path = path + separator;
const [, , entries] = snapshot;
fs.mkdirSync(path, { recursive: true });
for (const [name, child] of Object.entries(entries))
(0, exports.fromSnapshotSync)(child, { fs, path: `${path}${name}`, separator });
break;
}
case 1 /* SnapshotNodeType.File */: {
const [, , data] = snapshot;
fs.writeFileSync(path, data);
break;
}
case 2 /* SnapshotNodeType.Symlink */: {
const [, { target }] = snapshot;
fs.symlinkSync(target, path);
break;
}
}
};
exports.fromSnapshotSync = fromSnapshotSync;
//# sourceMappingURL=sync.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"sync.js","sourceRoot":"","sources":["../src/sync.ts"],"names":[],"mappings":";;;AAGO,MAAM,cAAc,GAAG,CAAC,EAAE,EAAE,EAAE,IAAI,GAAG,GAAG,EAAE,SAAS,GAAG,GAAG,EAAmB,EAAgB,EAAE;IACnG,MAAM,KAAK,GAAG,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IACjC,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE,CAAC;QACxB,MAAM,IAAI,GAAG,EAAE,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QAClC,MAAM,OAAO,GAAsC,EAAE,CAAC;QACtD,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG,SAAS,CAAC;QAC/D,KAAK,MAAM,KAAK,IAAI,IAAI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,GAAG,QAAQ,CAAC;YAC/B,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YACxC,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;gBACjD,IAAA,wBAAgB,EAAC,KAAK,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,GAAG,IAAI,GAAG,IAAI,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC;YACrE,MAAM;QACR,CAAC;QACD,kCAA0B,CAAC,CAAC,CAAC;YAC3B,MAAM,CAAC,EAAE,AAAD,EAAG,IAAI,CAAC,GAAG,QAAQ,CAAC;YAC5B,EAAE,CAAC,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAC7B,MAAM;QACR,CAAC;QACD,qCAA6B,CAAC,CAAC,CAAC;YAC9B,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC,GAAG,QAAQ,CAAC;YAChC,EAAE,CAAC,WAAW,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;YAC7B,MAAM;QACR,CAAC;IACH,CAAC;AACH,CAAC,CAAC;AAzBW,QAAA,gBAAgB,oBAyB3B"}
+30
View File
@@ -0,0 +1,30 @@
import type { FsPromisesApi, FsSynchronousApi } from '@jsonjoy.com/fs-node-utils';
import type { SnapshotNodeType } from './constants';
export interface SnapshotOptions {
fs: FsSynchronousApi;
path?: string;
separator?: '/' | '\\';
}
export interface AsyncSnapshotOptions {
fs: FsPromisesApi;
path?: string;
separator?: '/' | '\\';
}
export type SnapshotNode = FolderNode | FileNode | SymlinkNode | UnknownNode;
export type FolderNode = [
type: SnapshotNodeType.Folder,
meta: FolderMetadata,
entries: {
[child: string]: SnapshotNode;
}
];
export interface FolderMetadata {
}
export type FileNode = [type: SnapshotNodeType.File, meta: FileMetadata, data: Uint8Array];
export interface FileMetadata {
}
export type SymlinkNode = [type: SnapshotNodeType.Symlink, meta: SymlinkMetadata];
export interface SymlinkMetadata {
target: string;
}
export type UnknownNode = null;
+3
View File
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2024 jsonjoy.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,93 @@
# Base64
Fast Base64 encoder and decoder for browser and Node.js.
## Encoder
- Implements Base64 encoding algorithm compatible with Node's Buffer.
- Isomorphic&mdash;it can be used in, both, Node and the browser.
- Faster than the Node's implementation for short blobs, smaller than 40 bytes.
- Uses Node's implementation for long blobs, if available. Hence, it also works
in browser, but in Node environment will perform faster for short strings.
- Can encode into Base64 text or Base64 `Uint8Array`.
### Usage
Use encoder compatible with Node's Buffer:
```ts
import {toBase64} from '@jsonjoy.com/base64';
toBase64(new Uint8Array([1, 2, 3]));
```
Create your custom encoder:
```ts
import {createToBase64} from '@jsonjoy.com/base64';
const encode = createToBase64('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_');
encode(new Uint8Array([1, 2, 3]));
```
### Benchmark
Below benchmark encodes random binary blobs of sizes 8, 16, 32, 64, 128, 256, 512, and 1024 byes.
`@jsonjoy.com/base64` is faster, because for short strings (less than 40 chars) it uses a
native JavaScript implementation, which is faster and also works in browsers. For blobs larger
than 40 chars, it falls back to Node `Buffer` implementation, if available.
Encoding:
```
node src/__bench__/encode.js
util/base64 toBase64(uint8) x 1,531,283 ops/sec ±0.30% (92 runs sampled), 653 ns/op
util/base64 createToBase64()(uint8) x 946,364 ops/sec ±0.76% (100 runs sampled), 1057 ns/op
js-base64 x 1,103,190 ops/sec ±1.27% (96 runs sampled), 906 ns/op
fast-base64-encode x 500,225 ops/sec ±0.64% (96 runs sampled), 1999 ns/op
base64-js x 328,368 ops/sec ±0.25% (95 runs sampled), 3045 ns/op
Buffer.from(uint8).toString('base64'); x 1,099,420 ops/sec ±0.20% (100 runs sampled), 910 ns/op
Fastest is util/base64 toBase64(uint8)
```
Decoding:
```
node src/__bench__/decode.js
@jsonjoy.com/base64 fromBase64(str) x 756,989 ops/sec ±0.46% (97 runs sampled), 1321 ns/op
@jsonjoy.com/base64 createFromBase64()(str) x 475,591 ops/sec ±0.37% (96 runs sampled), 2103 ns/op
Buffer.from(str, 'base64') x 545,012 ops/sec ±0.33% (101 runs sampled), 1835 ns/op
base64-js x 487,015 ops/sec ±1.19% (94 runs sampled), 2053 ns/op
js-base64 x 173,049 ops/sec ±0.20% (99 runs sampled), 5779 ns/op
Fastest is @jsonjoy.com/base64 fromBase64(str)
```
## Decoder
- Uses Node.js built-in `Buffer`, if available.
- When `Buffer` is not available, uses JavaScript implementation.
### Usage
Use decoder compatible with Node's Buffer:
```ts
import {toBase64, fromBase64} from '@jsonjoy.com/base64';
fromBase64(toBase64(new Uint8Array([1, 2, 3])));
```
Create your custom encoder:
```ts
import {createFromBase64} from '@jsonjoy.com/base64';
const decoder = createFromBase64('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_');
decoder(toBase64(new Uint8Array([1, 2, 3])));
```
@@ -0,0 +1,2 @@
export declare const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
export declare const hasBuffer: boolean;
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasBuffer = exports.alphabet = void 0;
exports.alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
exports.hasBuffer = typeof Buffer === 'function' && typeof Buffer.from === 'function';
//# sourceMappingURL=constants.js.map
@@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,QAAQ,GAAG,kEAAkE,CAAC;AAC9E,QAAA,SAAS,GAAG,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,IAAI,KAAK,UAAU,CAAC"}
@@ -0,0 +1 @@
export declare const createFromBase64: (chars?: string, noPadding?: boolean) => (encoded: string) => Uint8Array;
@@ -0,0 +1,80 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createFromBase64 = void 0;
const constants_1 = require("./constants");
const E = '=';
const createFromBase64 = (chars = constants_1.alphabet, noPadding = false) => {
if (chars.length !== 64)
throw new Error('chars must be 64 characters long');
let max = 0;
for (let i = 0; i < chars.length; i++)
max = Math.max(max, chars.charCodeAt(i));
const table = [];
for (let i = 0; i <= max; i += 1)
table[i] = -1;
for (let i = 0; i < chars.length; i++)
table[chars.charCodeAt(i)] = i;
return (encoded) => {
if (!encoded)
return new Uint8Array(0);
let length = encoded.length;
if (noPadding) {
const mod = length % 4;
if (mod === 2) {
encoded += '==';
length += 2;
}
else if (mod === 3) {
encoded += '=';
length += 1;
}
}
if (length % 4 !== 0)
throw new Error('Base64 string length must be a multiple of 4');
const mainLength = encoded[length - 1] !== E ? length : length - 4;
let bufferLength = (length >> 2) * 3;
let padding = 0;
if (encoded[length - 2] === E) {
padding = 2;
bufferLength -= 2;
}
else if (encoded[length - 1] === E) {
padding = 1;
bufferLength -= 1;
}
const buf = new Uint8Array(bufferLength);
let j = 0;
let i = 0;
for (; i < mainLength; i += 4) {
const sextet0 = table[encoded.charCodeAt(i)];
const sextet1 = table[encoded.charCodeAt(i + 1)];
const sextet2 = table[encoded.charCodeAt(i + 2)];
const sextet3 = table[encoded.charCodeAt(i + 3)];
if (sextet0 < 0 || sextet1 < 0 || sextet2 < 0 || sextet3 < 0)
throw new Error('INVALID_BASE64_STRING');
buf[j] = (sextet0 << 2) | (sextet1 >> 4);
buf[j + 1] = (sextet1 << 4) | (sextet2 >> 2);
buf[j + 2] = (sextet2 << 6) | sextet3;
j += 3;
}
if (padding === 2) {
const sextet0 = table[encoded.charCodeAt(mainLength)];
const sextet1 = table[encoded.charCodeAt(mainLength + 1)];
if (sextet0 < 0 || sextet1 < 0)
throw new Error('INVALID_BASE64_STRING');
buf[j] = (sextet0 << 2) | (sextet1 >> 4);
}
else if (padding === 1) {
const sextet0 = table[encoded.charCodeAt(mainLength)];
const sextet1 = table[encoded.charCodeAt(mainLength + 1)];
const sextet2 = table[encoded.charCodeAt(mainLength + 2)];
if (sextet0 < 0 || sextet1 < 0 || sextet2 < 0)
throw new Error('INVALID_BASE64_STRING');
buf[j] = (sextet0 << 2) | (sextet1 >> 4);
buf[j + 1] = (sextet1 << 4) | (sextet2 >> 2);
}
return buf;
};
};
exports.createFromBase64 = createFromBase64;
//# sourceMappingURL=createFromBase64.js.map
@@ -0,0 +1 @@
{"version":3,"file":"createFromBase64.js","sourceRoot":"","sources":["../src/createFromBase64.ts"],"names":[],"mappings":";;;AAAA,2CAAqC;AAErC,MAAM,CAAC,GAAG,GAAG,CAAC;AAEP,MAAM,gBAAgB,GAAG,CAAC,QAAgB,oBAAQ,EAAE,YAAqB,KAAK,EAAE,EAAE;IACvF,IAAI,KAAK,CAAC,MAAM,KAAK,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IAC7E,IAAI,GAAG,GAAG,CAAC,CAAC;IACZ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG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AAO,IAAI,CAAC,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC,CAAC;AACJ,CAAC,CAAC;AA7DW,QAAA,gBAAgB,oBA6D3B"}
@@ -0,0 +1 @@
export declare const createFromBase64Bin: (chars?: string, pad?: string) => (view: DataView, offset: number, length: number) => Uint8Array;
@@ -0,0 +1,87 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createFromBase64Bin = void 0;
const constants_1 = require("./constants");
const createFromBase64Bin = (chars = constants_1.alphabet, pad = '=') => {
if (chars.length !== 64)
throw new Error('chars must be 64 characters long');
let max = 0;
for (let i = 0; i < chars.length; i++)
max = Math.max(max, chars.charCodeAt(i));
const table = [];
for (let i = 0; i <= max; i += 1)
table[i] = -1;
for (let i = 0; i < chars.length; i++)
table[chars.charCodeAt(i)] = i;
const doExpectPadding = pad.length === 1;
const PAD = doExpectPadding ? pad.charCodeAt(0) : 0;
return (view, offset, length) => {
if (!length)
return new Uint8Array(0);
let padding = 0;
if (length % 4 !== 0) {
padding = 4 - (length % 4);
length += padding;
}
else {
const end = offset + length;
const last = end - 1;
if (view.getUint8(last) === PAD) {
padding = 1;
if (length > 1 && view.getUint8(last - 1) === PAD)
padding = 2;
}
}
if (length % 4 !== 0)
throw new Error('Base64 string length must be a multiple of 4');
const mainEnd = offset + length - (padding ? 4 : 0);
const bufferLength = (length >> 2) * 3 - padding;
const buf = new Uint8Array(bufferLength);
let j = 0;
let i = offset;
for (; i < mainEnd; i += 4) {
const word = view.getUint32(i);
const octet0 = word >>> 24;
const octet1 = (word >>> 16) & 0xff;
const octet2 = (word >>> 8) & 0xff;
const octet3 = word & 0xff;
const sextet0 = table[octet0];
const sextet1 = table[octet1];
const sextet2 = table[octet2];
const sextet3 = table[octet3];
if (sextet0 < 0 || sextet1 < 0 || sextet2 < 0 || sextet3 < 0)
throw new Error('INVALID_BASE64_SEQ');
buf[j] = (sextet0 << 2) | (sextet1 >> 4);
buf[j + 1] = (sextet1 << 4) | (sextet2 >> 2);
buf[j + 2] = (sextet2 << 6) | sextet3;
j += 3;
}
if (!padding)
return buf;
if (padding === 1) {
const word = view.getUint16(mainEnd);
const octet0 = word >> 8;
const octet1 = word & 0xff;
const octet2 = view.getUint8(mainEnd + 2);
const sextet0 = table[octet0];
const sextet1 = table[octet1];
const sextet2 = table[octet2];
if (sextet0 < 0 || sextet1 < 0 || sextet2 < 0)
throw new Error('INVALID_BASE64_SEQ');
buf[j] = (sextet0 << 2) | (sextet1 >> 4);
buf[j + 1] = (sextet1 << 4) | (sextet2 >> 2);
return buf;
}
const word = view.getUint16(mainEnd);
const octet0 = word >> 8;
const octet1 = word & 0xff;
const sextet0 = table[octet0];
const sextet1 = table[octet1];
if (sextet0 < 0 || sextet1 < 0)
throw new Error('INVALID_BASE64_SEQ');
buf[j] = (sextet0 << 2) | (sextet1 >> 4);
return buf;
};
};
exports.createFromBase64Bin = createFromBase64Bin;
//# sourceMappingURL=createFromBase64Bin.js.map
@@ -0,0 +1 @@
{"version":3,"file":"createFromBase64Bin.js","sourceRoot":"","sources":["../src/createFromBase64Bin.ts"],"names":[],"mappings":";;;AAAA,2CAAqC;AAE9B,MAAM,mBAAmB,GAAG,CAAC,QAAgB,oBAAQ,EAAE,MAAc,GAAG,EAAE,EAAE;IACjF,IAAI,KAAK,CAAC,MAAM,KAAK,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IAC7E,IAAI,GAAG,GAAG,CAAC,CAAC;IACZ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;IAChF,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,GAAG,EAAE,CA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GAAG,IAAI,CAAC;QAC3B,MAAM,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC;QAC9B,MAAM,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC;QAC9B,IAAI,OAAO,GAAG,CAAC,IAAI,OAAO,GAAG,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;QACtE,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,IAAI,CAAC,CAAC,GAAG,CAAC,OAAO,IAAI,CAAC,CAAC,CAAC;QACzC,OAAO,GAAG,CAAC;IACb,CAAC,CAAC;AACJ,CAAC,CAAC;AAtEW,QAAA,mBAAmB,uBAsE9B"}
@@ -0,0 +1 @@
export declare const createToBase64: (chars?: string, pad?: string) => (uint8: Uint8Array, length: number) => string;
@@ -0,0 +1,48 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createToBase64 = void 0;
const flatstr_1 = require("./util/strings/flatstr");
const constants_1 = require("./constants");
const createToBase64 = (chars = constants_1.alphabet, pad = '=') => {
if (chars.length !== 64)
throw new Error('chars must be 64 characters long');
const table = chars.split('');
const table2 = [];
for (const c1 of table) {
for (const c2 of table) {
const two = (0, flatstr_1.flatstr)(c1 + c2);
table2.push(two);
}
}
const E = pad;
const EE = (0, flatstr_1.flatstr)(pad + pad);
return (uint8, length) => {
let out = '';
const extraLength = length % 3;
const baseLength = length - extraLength;
for (let i = 0; i < baseLength; i += 3) {
const o1 = uint8[i];
const o2 = uint8[i + 1];
const o3 = uint8[i + 2];
const v1 = (o1 << 4) | (o2 >> 4);
const v2 = ((o2 & 0b1111) << 8) | o3;
out += table2[v1] + table2[v2];
}
if (!extraLength)
return out;
if (extraLength === 1) {
const o1 = uint8[baseLength];
out += table2[o1 << 4] + EE;
}
else {
const o1 = uint8[baseLength];
const o2 = uint8[baseLength + 1];
const v1 = (o1 << 4) | (o2 >> 4);
const v2 = (o2 & 0b1111) << 2;
out += table2[v1] + table[v2] + E;
}
return out;
};
};
exports.createToBase64 = createToBase64;
//# sourceMappingURL=createToBase64.js.map
@@ -0,0 +1 @@
{"version":3,"file":"createToBase64.js","sourceRoot":"","sources":["../src/createToBase64.ts"],"names":[],"mappings":";;;AAAA,oDAA+C;AAC/C,2CAAqC;AAE9B,MAAM,cAAc,GAAG,CAAC,QAAgB,oBAAQ,EAAE,MAAc,GAAG,EAAE,EAAE;IAC5E,IAAI,KAAK,CAAC,MAAM,KAAK,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IAE7E,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC9B,MAAM,MAAM,GAAa,EAAE,CAAC;IAE5B,KAAK,MAAM,EAAE,IAAI,KAAK,EAAE,CAAC;QACvB,KAAK,MAAM,EAAE,IAAI,KAAK,EAAE,CAAC;YACvB,MAAM,GAAG,GAAG,IAAA,iBAAO,EAAC,EAAE,GAAG,EAAE,CAAC,CAAC;YAC7B,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACnB,CAAC;IACH,CAAC;IAED,MAAM,CAAC,GAAW,GAAG,CAAC;IACtB,MAAM,EAAE,GAAW,IAAA,iBAAO,EAAC,GAAG,GAAG,GAAG,CAAC,CAAC;IAEtC,OAAO,CAAC,KAAiB,EAAE,MAAc,EAAU,EAAE;QACnD,IAAI,GAAG,GAAG,EAAE,CAAC;QACb,MAAM,WAAW,GAAG,MAAM,GAAG,CAAC,CAAC;QAC/B,MAAM,UAAU,GAAG,MAAM,GAAG,WAAW,CAAC;QACxC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;YACvC,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;YACpB,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;YACxB,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;YACxB,MAAM,EAAE,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;YACjC,MAAM,EAAE,GAAG,CAAC,CAAC,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,CAAC;YACrC,GAAG,IAAI,MAAM,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;QACjC,CAAC;QACD,IAAI,CAAC,WAAW;YAAE,OAAO,GAAG,CAAC;QAC7B,IAAI,WAAW,KAAK,CAAC,EAAE,CAAC;YACtB,MAAM,EAAE,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC;YAC7B,GAAG,IAAI,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,EAAE,CAAC;QAC9B,CAAC;aAAM,CAAC;YACN,MAAM,EAAE,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC;YAC7B,MAAM,EAAE,GAAG,KAAK,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC;YACjC,MAAM,EAAE,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;YACjC,MAAM,EAAE,GAAG,CAAC,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;YAC9B,GAAG,IAAI,MAAM,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;QACpC,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC,CAAC;AACJ,CAAC,CAAC;AAzCW,QAAA,cAAc,kBAyCzB"}
@@ -0,0 +1 @@
export declare const createToBase64Bin: (chars?: string, pad?: string) => (uint8: Uint8Array, start: number, length: number, dest: DataView, offset: number) => number;
@@ -0,0 +1,62 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createToBase64Bin = void 0;
const constants_1 = require("./constants");
const createToBase64Bin = (chars = constants_1.alphabet, pad = '=') => {
if (chars.length !== 64)
throw new Error('chars must be 64 characters long');
const table = chars.split('').map((c) => c.charCodeAt(0));
const table2 = [];
for (const c1 of table) {
for (const c2 of table) {
const two = (c1 << 8) + c2;
table2.push(two);
}
}
const doAddPadding = pad.length === 1;
const E = doAddPadding ? pad.charCodeAt(0) : 0;
const EE = doAddPadding ? (E << 8) | E : 0;
return (uint8, start, length, dest, offset) => {
const extraLength = length % 3;
const baseLength = length - extraLength;
for (; start < baseLength; start += 3) {
const o1 = uint8[start];
const o2 = uint8[start + 1];
const o3 = uint8[start + 2];
const v1 = (o1 << 4) | (o2 >> 4);
const v2 = ((o2 & 0b1111) << 8) | o3;
dest.setInt32(offset, (table2[v1] << 16) + table2[v2]);
offset += 4;
}
if (extraLength === 1) {
const o1 = uint8[baseLength];
if (doAddPadding) {
dest.setInt32(offset, (table2[o1 << 4] << 16) + EE);
offset += 4;
}
else {
dest.setInt16(offset, table2[o1 << 4]);
offset += 2;
}
}
else if (extraLength) {
const o1 = uint8[baseLength];
const o2 = uint8[baseLength + 1];
const v1 = (o1 << 4) | (o2 >> 4);
const v2 = (o2 & 0b1111) << 2;
if (doAddPadding) {
dest.setInt32(offset, (table2[v1] << 16) + (table[v2] << 8) + E);
offset += 4;
}
else {
dest.setInt16(offset, table2[v1]);
offset += 2;
dest.setInt8(offset, table[v2]);
offset += 1;
}
}
return offset;
};
};
exports.createToBase64Bin = createToBase64Bin;
//# sourceMappingURL=createToBase64Bin.js.map
@@ -0,0 +1 @@
{"version":3,"file":"createToBase64Bin.js","sourceRoot":"","sources":["../src/createToBase64Bin.ts"],"names":[],"mappings":";;;AAAA,2CAAqC;AAE9B,MAAM,iBAAiB,GAAG,CAAC,QAAgB,oBAAQ,EAAE,MAAc,GAAG,EAAE,EAAE;IAC/E,IAAI,KAAK,CAAC,MAAM,KAAK,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IAE7E,MAAM,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CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;gBACjE,MAAM,IAAI,CAAC,CAAC;YACd,CAAC;iBAAM,CAAC;gBACN,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC;gBAClC,MAAM,IAAI,CAAC,CAAC;gBACZ,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;gBAChC,MAAM,IAAI,CAAC,CAAC;YACd,CAAC;QACH,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC,CAAC;AAvDW,QAAA,iBAAiB,qBAuD5B"}
@@ -0,0 +1 @@
export declare const createToBase64BinUint8: (chars?: string, pad?: string) => (uint8: Uint8Array, start: number, length: number, dest: Uint8Array, offset: number) => number;
@@ -0,0 +1,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createToBase64BinUint8 = void 0;
const constants_1 = require("./constants");
const createToBase64BinUint8 = (chars = constants_1.alphabet, pad = '=') => {
if (chars.length !== 64)
throw new Error('chars must be 64 characters long');
const table = chars.split('').map((c) => c.charCodeAt(0));
const table2 = [];
for (const c1 of table) {
for (const c2 of table) {
const two = (c1 << 8) + c2;
table2.push(two);
}
}
const PAD = pad.length === 1 ? pad.charCodeAt(0) : 0;
return (uint8, start, length, dest, offset) => {
const extraLength = length % 3;
const baseLength = length - extraLength;
for (; start < baseLength; start += 3) {
const o1 = uint8[start];
const o2 = uint8[start + 1];
const o3 = uint8[start + 2];
const v1 = (o1 << 4) | (o2 >> 4);
const v2 = ((o2 & 0b1111) << 8) | o3;
let u16 = table2[v1];
dest[offset++] = u16 >> 8;
dest[offset++] = u16;
u16 = table2[v2];
dest[offset++] = u16 >> 8;
dest[offset++] = u16;
}
if (extraLength === 1) {
const o1 = uint8[baseLength];
const u16 = table2[o1 << 4];
dest[offset++] = u16 >> 8;
dest[offset++] = u16;
if (PAD) {
dest[offset++] = PAD;
dest[offset++] = PAD;
}
}
else if (extraLength) {
const o1 = uint8[baseLength];
const o2 = uint8[baseLength + 1];
const v1 = (o1 << 4) | (o2 >> 4);
const v2 = (o2 & 0b1111) << 2;
const u16 = table2[v1];
dest[offset++] = u16 >> 8;
dest[offset++] = u16;
dest[offset++] = table[v2];
if (PAD)
dest[offset++] = PAD;
}
return offset;
};
};
exports.createToBase64BinUint8 = createToBase64BinUint8;
//# sourceMappingURL=createToBase64BinUint8.js.map
@@ -0,0 +1 @@
{"version":3,"file":"createToBase64BinUint8.js","sourceRoot":"","sources":["../src/createToBase64BinUint8.ts"],"names":[],"mappings":";;;AAAA,2CAAqC;AAE9B,MAAM,sBAAsB,GAAG,CAAC,QAAgB,oBAAQ,EAAE,MAAc,GAAG,EAAE,EAAE;IACpF,IAAI,KAAK,CAAC,MAAM,KAAK,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IAE7E,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1D,MAAM,MAAM,GAAa,EAAE,CAAC;IAE5B,KAAK,MAAM,EAAE,IAAI,KAAK,EAAE,CAAC;QACvB,KAAK,MAAM,EAAE,IAAI,KAAK,EAAE,CAAC;YACvB,MAAM,GAAG,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,EAAE,CAAC;YAC3B,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACnB,CAAC;IACH,CAAC;IAED,MAAM,GAAG,GAAW,GAAG,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAE7D,OAAO,CAAC,KAAiB,EAAE,KAAa,EAAE,MAAc,EAAE,IAAgB,EAAE,MAAc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BACR,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,GAAG,CAAC;gBACrB,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,GAAG,CAAC;YACvB,CAAC;QACH,CAAC;aAAM,IAAI,WAAW,EAAE,CAAC;YACvB,MAAM,EAAE,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC;YAC7B,MAAM,EAAE,GAAG,KAAK,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC;YACjC,MAAM,EAAE,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;YACjC,MAAM,EAAE,GAAG,CAAC,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;YAC9B,MAAM,GAAG,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;YACvB,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;YAC1B,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,GAAG,CAAC;YACrB,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,KAAK,CAAC,EAAE,CAAC,CAAC;YAC3B,IAAI,GAAG;gBAAE,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,GAAG,CAAC;QAChC,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC,CAAC;AArDW,QAAA,sBAAsB,0BAqDjC"}
@@ -0,0 +1 @@
export declare const fromBase64: (encoded: string) => Uint8Array;
@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromBase64 = void 0;
const bufferToUint8Array_1 = require("./util/buffers/bufferToUint8Array");
const constants_1 = require("./constants");
const createFromBase64_1 = require("./createFromBase64");
const fromBase64Cpp = constants_1.hasBuffer ? (encoded) => (0, bufferToUint8Array_1.bufferToUint8Array)(Buffer.from(encoded, 'base64')) : null;
const fromBase64Native = (0, createFromBase64_1.createFromBase64)();
exports.fromBase64 = !fromBase64Cpp
? fromBase64Native
: (encoded) => (encoded.length > 48 ? fromBase64Cpp(encoded) : fromBase64Native(encoded));
//# sourceMappingURL=fromBase64.js.map
@@ -0,0 +1 @@
{"version":3,"file":"fromBase64.js","sourceRoot":"","sources":["../src/fromBase64.ts"],"names":[],"mappings":";;;AAAA,0EAAqE;AACrE,2CAAsC;AACtC,yDAAoD;AAEpD,MAAM,aAAa,GAAG,qBAAS,CAAC,CAAC,CAAC,CAAC,OAAe,EAAE,EAAE,CAAC,IAAA,uCAAkB,EAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACjH,MAAM,gBAAgB,GAAG,IAAA,mCAAgB,GAAE,CAAC;AAE/B,QAAA,UAAU,GAAG,CAAC,aAAa;IACtC,CAAC,CAAC,gBAAgB;IAClB,CAAC,CAAC,CAAC,OAAe,EAAc,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC"}
@@ -0,0 +1 @@
export declare const fromBase64Bin: (view: DataView, offset: number, length: number) => Uint8Array;
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromBase64Bin = void 0;
const createFromBase64Bin_1 = require("./createFromBase64Bin");
exports.fromBase64Bin = (0, createFromBase64Bin_1.createFromBase64Bin)();
//# sourceMappingURL=fromBase64Bin.js.map
@@ -0,0 +1 @@
{"version":3,"file":"fromBase64Bin.js","sourceRoot":"","sources":["../src/fromBase64Bin.ts"],"names":[],"mappings":";;;AAAA,+DAA0D;AAE7C,QAAA,aAAa,GAAG,IAAA,yCAAmB,GAAE,CAAC"}
@@ -0,0 +1 @@
export declare const fromBase64Url: (encoded: string) => Uint8Array;
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromBase64Url = void 0;
const createFromBase64_1 = require("./createFromBase64");
exports.fromBase64Url = (0, createFromBase64_1.createFromBase64)('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', true);
//# sourceMappingURL=fromBase64Url.js.map
@@ -0,0 +1 @@
{"version":3,"file":"fromBase64Url.js","sourceRoot":"","sources":["../src/fromBase64Url.ts"],"names":[],"mappings":";;;AAAA,yDAAoD;AAEvC,QAAA,aAAa,GAAG,IAAA,mCAAgB,EAAC,kEAAkE,EAAE,IAAI,CAAC,CAAC"}
@@ -0,0 +1,7 @@
export * from './createToBase64';
export * from './createToBase64Bin';
export * from './createFromBase64';
export * from './toBase64';
export * from './toBase64Bin';
export * from './fromBase64';
export * from './fromBase64Bin';
@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("./createToBase64"), exports);
tslib_1.__exportStar(require("./createToBase64Bin"), exports);
tslib_1.__exportStar(require("./createFromBase64"), exports);
tslib_1.__exportStar(require("./toBase64"), exports);
tslib_1.__exportStar(require("./toBase64Bin"), exports);
tslib_1.__exportStar(require("./fromBase64"), exports);
tslib_1.__exportStar(require("./fromBase64Bin"), exports);
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,2DAAiC;AACjC,8DAAoC;AACpC,6DAAmC;AACnC,qDAA2B;AAC3B,wDAA8B;AAC9B,uDAA6B;AAC7B,0DAAgC"}
@@ -0,0 +1 @@
export declare const toBase64: (uint8: Uint8Array) => string;
@@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toBase64 = void 0;
const constants_1 = require("./constants");
const createToBase64_1 = require("./createToBase64");
const encodeSmall = (0, createToBase64_1.createToBase64)();
exports.toBase64 = !constants_1.hasBuffer
? (uint8) => encodeSmall(uint8, uint8.length)
: (uint8) => {
const length = uint8.length;
if (length <= 48)
return encodeSmall(uint8, length);
return Buffer.from(uint8).toString('base64');
};
//# sourceMappingURL=toBase64.js.map
@@ -0,0 +1 @@
{"version":3,"file":"toBase64.js","sourceRoot":"","sources":["../src/toBase64.ts"],"names":[],"mappings":";;;AAAA,2CAAsC;AACtC,qDAAgD;AAEhD,MAAM,WAAW,GAAG,IAAA,+BAAc,GAAE,CAAC;AAExB,QAAA,QAAQ,GAAG,CAAC,qBAAS;IAChC,CAAC,CAAC,CAAC,KAAiB,EAAE,EAAE,CAAC,WAAW,CAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC;IACzD,CAAC,CAAC,CAAC,KAAiB,EAAU,EAAE;QAC5B,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;QAC5B,IAAI,MAAM,IAAI,EAAE;YAAE,OAAO,WAAW,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACpD,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAC/C,CAAC,CAAC"}
@@ -0,0 +1 @@
export declare const toBase64Bin: (uint8: Uint8Array, start: number, length: number, dest: DataView, offset: number) => number;
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toBase64Bin = void 0;
const createToBase64Bin_1 = require("./createToBase64Bin");
exports.toBase64Bin = (0, createToBase64Bin_1.createToBase64Bin)();
//# sourceMappingURL=toBase64Bin.js.map
@@ -0,0 +1 @@
{"version":3,"file":"toBase64Bin.js","sourceRoot":"","sources":["../src/toBase64Bin.ts"],"names":[],"mappings":";;;AAAA,2DAAsD;AAEzC,QAAA,WAAW,GAAG,IAAA,qCAAiB,GAAE,CAAC"}
@@ -0,0 +1 @@
export declare const toBase64Url: (uint8: Uint8Array, length: number) => string;
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toBase64Url = void 0;
const createToBase64_1 = require("./createToBase64");
exports.toBase64Url = (0, createToBase64_1.createToBase64)('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', '');
//# sourceMappingURL=toBase64Url.js.map
@@ -0,0 +1 @@
{"version":3,"file":"toBase64Url.js","sourceRoot":"","sources":["../src/toBase64Url.ts"],"names":[],"mappings":";;;AAAA,qDAAgD;AAEnC,QAAA,WAAW,GAAG,IAAA,+BAAc,EAAC,kEAAkE,EAAE,EAAE,CAAC,CAAC"}
@@ -0,0 +1 @@
export declare const b: (...args: number[]) => Uint8Array<ArrayBuffer>;
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.b = void 0;
const b = (...args) => new Uint8Array(args);
exports.b = b;
//# sourceMappingURL=b.js.map
@@ -0,0 +1 @@
{"version":3,"file":"b.js","sourceRoot":"","sources":["../../../src/util/buffers/b.ts"],"names":[],"mappings":";;;AAAO,MAAM,CAAC,GAAG,CAAC,GAAG,IAAc,EAAE,EAAE,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC;AAAhD,QAAA,CAAC,KAA+C"}
@@ -0,0 +1 @@
export declare const bufferToUint8Array: (buf: Buffer) => Uint8Array;
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bufferToUint8Array = void 0;
const bufferToUint8Array = (buf) => new Uint8Array(buf.buffer, buf.byteOffset, buf.length);
exports.bufferToUint8Array = bufferToUint8Array;
//# sourceMappingURL=bufferToUint8Array.js.map
@@ -0,0 +1 @@
{"version":3,"file":"bufferToUint8Array.js","sourceRoot":"","sources":["../../../src/util/buffers/bufferToUint8Array.ts"],"names":[],"mappings":";;;AAAO,MAAM,kBAAkB,GAAG,CAAC,GAAW,EAAc,EAAE,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;AAAzG,QAAA,kBAAkB,sBAAuF"}
@@ -0,0 +1 @@
export declare const copy: <T extends Uint8Array>(arr: T) => T;
@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.copy = void 0;
const copy = (arr) => {
const dupe = new Uint8Array(arr.length);
dupe.set(arr);
return dupe;
};
exports.copy = copy;
//# sourceMappingURL=copy.js.map
@@ -0,0 +1 @@
{"version":3,"file":"copy.js","sourceRoot":"","sources":["../../../src/util/buffers/copy.ts"],"names":[],"mappings":";;;AAAO,MAAM,IAAI,GAAG,CAAuB,GAAM,EAAK,EAAE;IACtD,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,CAAM,CAAC;IAC7C,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACd,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AAJW,QAAA,IAAI,QAIf"}
@@ -0,0 +1 @@
export declare const flatstr: (s: string) => string;
@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.flatstr = void 0;
const flatstr = (s) => {
s | 0;
Number(s);
return s;
};
exports.flatstr = flatstr;
//# sourceMappingURL=flatstr.js.map
@@ -0,0 +1 @@
{"version":3,"file":"flatstr.js","sourceRoot":"","sources":["../../../src/util/strings/flatstr.ts"],"names":[],"mappings":";;;AAAO,MAAM,OAAO,GAAG,CAAC,CAAS,EAAU,EAAE;IACtC,CAAC,GAAG,CAAC,CAAC;IACX,MAAM,CAAC,CAAC,CAAC,CAAC;IACV,OAAO,CAAC,CAAC;AACX,CAAC,CAAC;AAJW,QAAA,OAAO,WAIlB"}
@@ -0,0 +1,76 @@
{
"name": "@jsonjoy.com/base64",
"publishConfig": {
"access": "public"
},
"version": "17.67.0",
"description": "High-performance Base64 encoder and decoder",
"author": {
"name": "streamich",
"url": "https://github.com/streamich"
},
"homepage": "https://github.com/jsonjoy-com/base64",
"repository": "jsonjoy-com/base64",
"license": "Apache-2.0",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/streamich"
},
"keywords": [
"base64",
"base64url",
"base64-url",
"base64urlsafe",
"base64url-safe"
],
"engines": {
"node": ">=10.0"
},
"main": "lib/index.js",
"types": "lib/index.d.ts",
"typings": "lib/index.d.ts",
"files": [
"LICENSE",
"lib/"
],
"scripts": {
"clean": "rimraf lib typedocs coverage gh-pages yarn-error.log",
"build": "tsc --project tsconfig.build.json --module commonjs --target es2020 --outDir lib",
"jest": "node -r ts-node/register ./node_modules/.bin/jest",
"test": "jest --maxWorkers 7",
"test:ci": "yarn jest --maxWorkers 3 --no-cache",
"coverage": "yarn test --collectCoverage",
"typedoc": "typedoc",
"build:pages": "rimraf gh-pages && mkdir -p gh-pages && cp -r typedocs/* gh-pages && cp -r coverage gh-pages/coverage",
"deploy:pages": "gh-pages -d gh-pages",
"publish-coverage-and-typedocs": "yarn typedoc && yarn coverage && yarn build:pages && yarn deploy:pages",
"typecheck": "tsc -p ."
},
"jest": {
"preset": "ts-jest",
"testEnvironment": "node",
"moduleFileExtensions": [
"ts",
"js",
"tsx"
],
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"transformIgnorePatterns": [
".*/node_modules/.*"
],
"testRegex": ".*/(__tests__|__jest__|demo)/.*\\.(test|spec)\\.tsx?$",
"rootDir": ".",
"testPathIgnorePatterns": [
"node_modules"
]
},
"peerDependencies": {
"tslib": "2"
},
"devDependencies": {
"base64-js": "^1.5.1",
"js-base64": "^3.7.2"
}
}
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2024 jsonjoy.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,39 @@
# @jsonjoy.com/codegen
A no-dependencies, low-level, high-performance JIT code generation package for JavaScript.
## Features
- **Zero dependencies** - Lightweight and fast to install
- **High performance** - Generates optimized JavaScript functions at runtime
- **Type safe** - Full TypeScript support with comprehensive type definitions
- **Flexible** - Supports various code generation patterns and techniques
- **Production ready** - Battle-tested and optimized for real-world usage
## Use Cases
- Deep equality comparison functions with known schemas
- JSON Patch execution with pre-known patches
- Optimized validation and serialization functions
- Custom function generation based on runtime data
- Performance-critical code that benefits from JIT compilation
## Installation
```bash
npm install @jsonjoy.com/codegen
```
## Quick Start
```typescript
import { Codegen } from '@jsonjoy.com/codegen';
const codegen = new Codegen();
// Add your code generation logic here
const optimizedFunction = codegen.compile();
```
## License
Apache-2.0
@@ -0,0 +1,182 @@
import type { JavaScriptLinked } from './types';
/**
* Inline JavaScript statements that are executed in main function body.
*/
export declare class CodegenStepExecJs {
readonly js: string;
constructor(js: string);
}
/**
* A step can be `CodegenStepExecJs` or some application specific step, which
* will later will need to be converted to `CodegenStepExecJs`.
*/
type JsonSerializerStep = CodegenStepExecJs | unknown;
/**
* Configuration options for {@link Codegen} instances.
*/
export interface CodegenOptions<Linkable = Record<string, unknown>> {
/**
* Inline JavaScript string that represents the arguments that will be passed
* to the main function body. Defaults to "r0", i.e. the first register.
*/
args?: string[];
/**
* Name of the generated function.
*/
name?: string;
/**
* Inline JavaScript statements, that execute at the beginning of the main
* function body.
*/
prologue?: string;
/**
* Inline JavaScript statements, that execute at the end of the main
* function body.
*/
epilogue?: string | (() => string);
/**
* Converts all steps to `CodegenStepExecJs`.
*/
processSteps?: (steps: JsonSerializerStep[]) => CodegenStepExecJs[];
/**
* Predefined list of dependencies that can be linked on demand. Dependency is
* linked with the name of the property and is linked only once.
*/
linkable?: Linkable;
}
export type CodegenGenerateOptions = Pick<CodegenOptions, 'name' | 'args' | 'prologue' | 'epilogue'>;
/**
* A helper class which helps with building JavaScript code for a single
* function. It keeps track of external dependencies, internally generated
* constants, and execution steps, which at the end are all converted to
* to an executable JavaScript function.
*
* The final output is a JavaScript function enclosed in a closure:
*
* ```js
* (function(d1, d2, d3) {
* var c1 = something;
* var c2 = something;
* var c3 = something;
* return function(r0) {
* var r1 = something;
* var r2 = something;
* var r3 = something;
* return something;
* }
* })
* ```
*
* Where `d*` are the external dependencies, `c*` are the internal constants,
* and `r*` are the local immutable infinite registers.
*/
export declare class Codegen<Fn extends (...deps: any[]) => any = (...deps: unknown[]) => unknown, Linkable = Record<string, unknown>> {
/** @ignore */
protected steps: JsonSerializerStep[];
/** @ignore */
options: Required<CodegenOptions<Linkable>>;
constructor(opts: CodegenOptions<Linkable>);
/**
* Add one or more JavaScript statements to the main function body.
*/
js(js: string): void;
var(expression?: string): string;
if(condition: string, then: () => void, otherwise?: () => void): void;
while(condition: string, block: () => void): void;
doWhile(block: () => void, condition: string): void;
switch(expression: string, cases: [match: string | number | boolean | null, block: () => void, noBreak?: boolean][], def?: () => void): void;
return(expression: string): void;
/**
* Add any application specific execution step. Steps of `unknown` type
* later need to converted to `CodegenStepExecJs` steps in the `.processStep`
* callback.
*
* @param step A step in function execution logic.
*/
step(step: unknown): void;
protected registerCounter: number;
/**
* Codegen uses the idea of infinite registers. It starts with `0` and
* increments it by one for each new register. Best practice is to use
* a new register for each new variable and keep them immutable.
*
* Usage:
*
* ```js
* const r = codegen.getRegister();
* codegen.js(`const ${r} = 1;`);
* ```
*
* @returns a unique identifier for a variable.
*/
getRegister(): string;
r(): string;
/** @ignore */
protected dependencies: unknown[];
protected dependencyNames: string[];
/**
* Allows to wire up dependencies to the generated code.
*
* @param dep Any JavaScript dependency, could be a function, an object,
* or anything else.
* @param name Optional name of the dependency. If not provided, a unique
* name will be generated, which starts with `d` and a counter
* appended.
* @returns Returns the dependency name, a code symbol which can be used as
* variable name.
*/
linkDependency(dep: unknown, name?: string): string;
/**
* Sames as {@link Codegen#linkDependency}, but allows to wire up multiple
* dependencies at once.
*/
linkDependencies(deps: unknown[]): string[];
protected linked: {
[key: string]: 1;
};
/**
* Link a dependency from the pre-defined `options.linkable` object. This method
* can be called many times with the same dependency name, the dependency will
* be linked only once.
*
* @param name Linkable dependency name.
*/
link(name: keyof Linkable): void;
/** @ignore */
protected constants: string[];
protected constantNames: string[];
/**
* Allows to encode any code or value in the closure of the generated
* function.
*
* @param constant Any JavaScript value in string form.
* @param name Optional name of the constant. If not provided, a unique
* name will be generated, which starts with `c` and a counter
* appended.
* @returns Returns the constant name, a code symbol which can be used as
* variable name.
*/
addConstant(constant: string, name?: string): string;
/**
* Sames as {@link Codegen#addConstant}, but allows to create multiple
* constants at once.
*/
addConstants(constants: string[]): string[];
/**
* Returns generated JavaScript code with the dependency list.
*
* ```js
* const code = codegen.generate();
* const fn = eval(code.js)(...code.deps);
* const result = fn(...args);
* ```
*/
generate(opts?: CodegenGenerateOptions): JavaScriptLinked<Fn>;
/**
* Compiles the generated JavaScript code into a function.
*
* @returns JavaScript function ready for execution.
*/
compile(opts?: CodegenGenerateOptions): Fn;
}
export {};
@@ -0,0 +1,238 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Codegen = exports.CodegenStepExecJs = void 0;
const compile_1 = require("./compile");
/**
* Inline JavaScript statements that are executed in main function body.
*/
class CodegenStepExecJs {
constructor(js) {
this.js = js;
}
}
exports.CodegenStepExecJs = CodegenStepExecJs;
/**
* A helper class which helps with building JavaScript code for a single
* function. It keeps track of external dependencies, internally generated
* constants, and execution steps, which at the end are all converted to
* to an executable JavaScript function.
*
* The final output is a JavaScript function enclosed in a closure:
*
* ```js
* (function(d1, d2, d3) {
* var c1 = something;
* var c2 = something;
* var c3 = something;
* return function(r0) {
* var r1 = something;
* var r2 = something;
* var r3 = something;
* return something;
* }
* })
* ```
*
* Where `d*` are the external dependencies, `c*` are the internal constants,
* and `r*` are the local immutable infinite registers.
*/
class Codegen {
constructor(opts) {
/** @ignore */
this.steps = [];
/** @ignore */
this.dependencies = [];
this.dependencyNames = [];
this.linked = {};
/** @ignore */
this.constants = [];
this.constantNames = [];
this.options = {
args: ['r0'],
name: '',
prologue: '',
epilogue: '',
processSteps: (steps) => steps.filter((step) => step instanceof CodegenStepExecJs),
linkable: {},
...opts,
};
this.registerCounter = this.options.args.length;
}
/**
* Add one or more JavaScript statements to the main function body.
*/
js(js) {
this.steps.push(new CodegenStepExecJs(js));
}
var(expression) {
const r = this.getRegister();
if (expression)
this.js('var ' + r + ' = ' + expression + ';');
else
this.js('var ' + r + ';');
return r;
}
if(condition, then, otherwise) {
this.js('if (' + condition + ') {');
then();
if (otherwise) {
this.js('} else {');
otherwise();
}
this.js('}');
}
while(condition, block) {
this.js('while (' + condition + ') {');
block();
this.js('}');
}
doWhile(block, condition) {
this.js('do {');
block();
this.js('} while (' + condition + ');');
}
switch(expression, cases, def) {
this.js('switch (' + expression + ') {');
for (const [match, block, noBreak] of cases) {
this.js('case ' + match + ': {');
block();
if (!noBreak)
this.js('break;');
this.js('}');
}
if (def) {
this.js('default: {');
def();
this.js('}');
}
this.js('}');
}
return(expression) {
this.js('return ' + expression + ';');
}
/**
* Add any application specific execution step. Steps of `unknown` type
* later need to converted to `CodegenStepExecJs` steps in the `.processStep`
* callback.
*
* @param step A step in function execution logic.
*/
step(step) {
this.steps.push(step);
}
/**
* Codegen uses the idea of infinite registers. It starts with `0` and
* increments it by one for each new register. Best practice is to use
* a new register for each new variable and keep them immutable.
*
* Usage:
*
* ```js
* const r = codegen.getRegister();
* codegen.js(`const ${r} = 1;`);
* ```
*
* @returns a unique identifier for a variable.
*/
getRegister() {
return `r${this.registerCounter++}`;
}
r() {
return this.getRegister();
}
/**
* Allows to wire up dependencies to the generated code.
*
* @param dep Any JavaScript dependency, could be a function, an object,
* or anything else.
* @param name Optional name of the dependency. If not provided, a unique
* name will be generated, which starts with `d` and a counter
* appended.
* @returns Returns the dependency name, a code symbol which can be used as
* variable name.
*/
linkDependency(dep, name = 'd' + this.dependencies.length) {
this.dependencies.push(dep);
this.dependencyNames.push(name);
return name;
}
/**
* Sames as {@link Codegen#linkDependency}, but allows to wire up multiple
* dependencies at once.
*/
linkDependencies(deps) {
return deps.map((dep) => this.linkDependency(dep));
}
/**
* Link a dependency from the pre-defined `options.linkable` object. This method
* can be called many times with the same dependency name, the dependency will
* be linked only once.
*
* @param name Linkable dependency name.
*/
link(name) {
if (this.linked[name])
return;
this.linked[name] = 1;
this.linkDependency(this.options.linkable[name], name);
}
/**
* Allows to encode any code or value in the closure of the generated
* function.
*
* @param constant Any JavaScript value in string form.
* @param name Optional name of the constant. If not provided, a unique
* name will be generated, which starts with `c` and a counter
* appended.
* @returns Returns the constant name, a code symbol which can be used as
* variable name.
*/
addConstant(constant, name = 'c' + this.constants.length) {
this.constants.push(constant);
this.constantNames.push(name);
return name;
}
/**
* Sames as {@link Codegen#addConstant}, but allows to create multiple
* constants at once.
*/
addConstants(constants) {
return constants.map((constant) => this.addConstant(constant));
}
/**
* Returns generated JavaScript code with the dependency list.
*
* ```js
* const code = codegen.generate();
* const fn = eval(code.js)(...code.deps);
* const result = fn(...args);
* ```
*/
generate(opts = {}) {
const { name, args, prologue, epilogue } = { ...this.options, ...opts };
const steps = this.options.processSteps(this.steps);
const js = `(function(${this.dependencyNames.join(', ')}) {
${this.constants.map((constant, index) => `var ${this.constantNames[index]} = (${constant});`).join('\n')}
return ${name ? `function ${name}` : 'function'}(${args.join(',')}){
${prologue}
${steps.map((step) => step.js).join('\n')}
${typeof epilogue === 'function' ? epilogue() : epilogue || ''}
}})`;
// console.log(js);
return {
deps: this.dependencies,
js: js,
};
}
/**
* Compiles the generated JavaScript code into a function.
*
* @returns JavaScript function ready for execution.
*/
compile(opts) {
const closure = this.generate(opts);
return (0, compile_1.compileClosure)(closure);
}
}
exports.Codegen = Codegen;
//# sourceMappingURL=Codegen.js.map
@@ -0,0 +1 @@
{"version":3,"file":"Codegen.js","sourceRoot":"","sources":["../src/Codegen.ts"],"names":[],"mappings":";;;AAAA,uCAAyC;AAGzC;;GAEG;AACH,MAAa,iB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AQ,KAAK,UAAU,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,QAAQ,IAAI,EAAE;IAC1D,CAAC;QACD,mBAAmB;QACnB,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,YAAY;YACvB,EAAE,EAAE,EAAgC;SACrC,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACI,OAAO,CAAC,IAA6B;QAC1C,MAAM,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QACpC,OAAO,IAAA,wBAAc,EAAC,OAAO,CAAC,CAAC;IACjC,CAAC;CACF;AAjOD,0BAiOC"}
@@ -0,0 +1,4 @@
import type { JavaScriptLinked } from '.';
import type { JavaScript } from './types';
export declare const compile: <T>(js: JavaScript<T>) => T;
export declare const compileClosure: <T>(fn: JavaScriptLinked<T, any>) => T;
@@ -0,0 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compileClosure = exports.compile = void 0;
// tslint:disable-next-line
const compile = (js) => eval(js);
exports.compile = compile;
const compileClosure = (fn) => (0, exports.compile)(fn.js)(...fn.deps);
exports.compileClosure = compileClosure;
//# sourceMappingURL=compile.js.map
@@ -0,0 +1 @@
{"version":3,"file":"compile.js","sourceRoot":"","sources":["../src/compile.ts"],"names":[],"mappings":";;;AAGA,2BAA2B;AACpB,MAAM,OAAO,GAAG,CAAI,EAAiB,EAAK,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAAhD,QAAA,OAAO,WAAyC;AAEtD,MAAM,cAAc,GAAG,CAAI,EAA4B,EAAK,EAAE,CAAC,IAAA,eAAO,EAAC,EAAE,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;AAApF,QAAA,cAAc,kBAAsE"}
@@ -0,0 +1,8 @@
/**
* Wraps a function into a proxy function with the same signature, but which can
* be re-implemented by the user at runtime.
*
* @param implementation Initial implementation.
* @returns Proxy function and implementation setter.
*/
export declare const dynamicFunction: <F extends (...args: any[]) => any>(implementation: F) => [fn: F, set: (fn: F) => void];
@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dynamicFunction = void 0;
/**
* Wraps a function into a proxy function with the same signature, but which can
* be re-implemented by the user at runtime.
*
* @param implementation Initial implementation.
* @returns Proxy function and implementation setter.
*/
const dynamicFunction = (implementation) => {
const proxy = ((...args) => implementation(...args));
const set = (f) => {
implementation = f;
};
return [proxy, set];
};
exports.dynamicFunction = dynamicFunction;
//# sourceMappingURL=dynamicFunction.js.map
@@ -0,0 +1 @@
{"version":3,"file":"dynamicFunction.js","sourceRoot":"","sources":["../src/dynamicFunction.ts"],"names":[],"mappings":";;;AAAA;;;;;;GAMG;AACI,MAAM,eAAe,GAAG,CAC7B,cAAiB,EACc,EAAE;IACjC,MAAM,KAAK,GAAG,CAAC,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,cAAc,CAAC,GAAG,IAAI,CAAC,CAAM,CAAC;IAC1D,MAAM,GAAG,GAAG,CAAC,CAAI,EAAE,EAAE;QACnB,cAAc,GAAG,CAAC,CAAC;IACrB,CAAC,CAAC;IACF,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AACtB,CAAC,CAAC;AARW,QAAA,eAAe,mBAQ1B"}
@@ -0,0 +1,3 @@
export * from './types';
export * from './compile';
export * from './Codegen';
@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("./types"), exports);
tslib_1.__exportStar(require("./compile"), exports);
tslib_1.__exportStar(require("./Codegen"), exports);
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,kDAAwB;AACxB,oDAA0B;AAC1B,oDAA0B"}
@@ -0,0 +1,5 @@
/**
* Switcher for code generation. It first executes "evaluation" function
* 3 times, and then generates optimized code.
*/
export declare const createSwitch: <F extends (...args: any[]) => any>(fn: F, codegen: () => F) => F;
@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSwitch = void 0;
const dynamicFunction_1 = require("./dynamicFunction");
/**
* Switcher for code generation. It first executes "evaluation" function
* 3 times, and then generates optimized code.
*/
const createSwitch = (fn, codegen) => {
let counter = 0;
const [proxy, set] = (0, dynamicFunction_1.dynamicFunction)((...args) => {
if (counter > 2)
set(codegen());
counter++;
return fn(...args);
});
return proxy;
};
exports.createSwitch = createSwitch;
//# sourceMappingURL=switch.js.map
@@ -0,0 +1 @@
{"version":3,"file":"switch.js","sourceRoot":"","sources":["../src/switch.ts"],"names":[],"mappings":";;;AAAA,uDAAkD;AAElD;;;GAGG;AACI,MAAM,YAAY,GAAG,CAAoC,EAAK,EAAE,OAAgB,EAAK,EAAE;IAC5F,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,MAAM,CAAC,KAAK,EAAE,GAAG,CAAC,GAAG,IAAA,iCAAe,EAAC,CAAC,GAAG,IAAI,EAAE,EAAE;QAC/C,IAAI,OAAO,GAAG,CAAC;YAAE,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC;QAChC,OAAO,EAAE,CAAC;QACV,OAAO,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;IACrB,CAAC,CAAC,CAAC;IACH,OAAO,KAAU,CAAC;AACpB,CAAC,CAAC;AARW,QAAA,YAAY,gBAQvB"}
@@ -0,0 +1,40 @@
/**
* Brand type for creating nominal types in TypeScript.
*/
export type Brand<T, B, N extends string> = T & {
[K in N]: B;
};
/**
* Represents a string which contains JavaScript code, which can be
* executed by the `eval` function.
*
* ```ts
* const code: JavaScript<() => {}> = `() => {}`;
* const fn = eval(code); // () => {}
* ```
*/
export type JavaScript<T> = Brand<string, T, 'JavaScript'>;
/**
* Represents a string which contains JavaScript code, which is enclosed
* in a JavaScript closure function. The dependencies can be "linked" to
* the JavaScript code, by executing the outer closure function with the
* list of dependencies as arguments.
*
* ```ts
* const multBy: JavaScriptClosure<(x: number) => number, [by: number]> =
* 'function(by) { return function (x) { return x * by }}';
*
* const multBy3 = eval(multBy)(3);
*
* multBy3(5); // 15
* ```
*/
export type JavaScriptClosure<Js, D extends unknown[] = unknown[]> = JavaScript<(...deps: D) => Js>;
/**
* Represents a {@link JavaScriptClosure} with a fixed list of dependencies,
* that can be linked to the JavaScript code-generated closure.
*/
export interface JavaScriptLinked<Js, Dependencies extends unknown[] = unknown[]> {
deps: Dependencies;
js: JavaScriptClosure<Js, Dependencies>;
}
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}

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