@fgv/ts-utils 5.0.0-21 → 5.0.0-23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/ts-utils.d.ts +307 -33
  2. package/lib/index.d.ts +2 -1
  3. package/lib/index.js +3 -1
  4. package/lib/packlets/base/index.d.ts +0 -2
  5. package/lib/packlets/base/index.js +1 -25
  6. package/lib/packlets/base/result.d.ts +49 -0
  7. package/lib/packlets/base/result.js +36 -0
  8. package/lib/packlets/collections/collector.d.ts +9 -0
  9. package/lib/packlets/collections/collector.js +6 -0
  10. package/lib/packlets/collections/validatingCollector.d.ts +5 -1
  11. package/lib/packlets/hash/hashingNormalizer.js +4 -3
  12. package/lib/packlets/logging/index.d.ts +3 -0
  13. package/{src/packlets/hash/index.ts → lib/packlets/logging/index.js} +19 -3
  14. package/lib/packlets/logging/logReporter.d.ts +69 -0
  15. package/lib/packlets/logging/logReporter.js +72 -0
  16. package/lib/packlets/logging/logger.d.ts +183 -0
  17. package/lib/packlets/logging/logger.js +237 -0
  18. package/lib/test/unit/consoleLogger.test.d.ts +2 -0
  19. package/lib/test/unit/hashingNormalizerCollisions.test.d.ts +2 -0
  20. package/package.json +1 -1
  21. package/lib/packlets/base/logger.d.ts +0 -52
  22. package/lib/packlets/base/logger.js +0 -128
  23. package/src/index.ts +0 -63
  24. package/src/packlets/base/brand.ts +0 -28
  25. package/src/packlets/base/index.ts +0 -31
  26. package/src/packlets/base/logger.ts +0 -156
  27. package/src/packlets/base/mapResults.ts +0 -302
  28. package/src/packlets/base/messageAggregator.ts +0 -120
  29. package/src/packlets/base/normalize.ts +0 -144
  30. package/src/packlets/base/result.ts +0 -961
  31. package/src/packlets/base/utils.ts +0 -236
  32. package/src/packlets/collections/collectible.ts +0 -238
  33. package/src/packlets/collections/collector.ts +0 -273
  34. package/src/packlets/collections/collectorValidator.ts +0 -178
  35. package/src/packlets/collections/common.ts +0 -27
  36. package/src/packlets/collections/convertingCollector.ts +0 -223
  37. package/src/packlets/collections/convertingCollectorValidator.ts +0 -164
  38. package/src/packlets/collections/index.ts +0 -39
  39. package/src/packlets/collections/keyValueConverters.ts +0 -142
  40. package/src/packlets/collections/readonlyResultMap.ts +0 -99
  41. package/src/packlets/collections/resultMap.ts +0 -322
  42. package/src/packlets/collections/resultMapValidator.ts +0 -188
  43. package/src/packlets/collections/utils.ts +0 -33
  44. package/src/packlets/collections/validatingCollector.ts +0 -123
  45. package/src/packlets/collections/validatingConvertingCollector.ts +0 -113
  46. package/src/packlets/collections/validatingResultMap.ts +0 -94
  47. package/src/packlets/conversion/baseConverter.ts +0 -330
  48. package/src/packlets/conversion/converter.ts +0 -260
  49. package/src/packlets/conversion/converters.ts +0 -1039
  50. package/src/packlets/conversion/defaultingConverter.ts +0 -188
  51. package/src/packlets/conversion/index.ts +0 -30
  52. package/src/packlets/conversion/objectConverter.ts +0 -259
  53. package/src/packlets/conversion/stringConverter.ts +0 -165
  54. package/src/packlets/file-tree/directoryItem.ts +0 -84
  55. package/src/packlets/file-tree/fileItem.ts +0 -119
  56. package/src/packlets/file-tree/fileTree.ts +0 -152
  57. package/src/packlets/file-tree/fileTreeAccessors.ts +0 -176
  58. package/src/packlets/file-tree/fsTree.ts +0 -118
  59. package/src/packlets/file-tree/in-memory/inMemoryTree.ts +0 -171
  60. package/src/packlets/file-tree/in-memory/index.ts +0 -23
  61. package/src/packlets/file-tree/in-memory/treeBuilder.ts +0 -203
  62. package/src/packlets/file-tree/index.ts +0 -31
  63. package/src/packlets/hash/crcNormalizer.ts +0 -81
  64. package/src/packlets/hash/hashingNormalizer.ts +0 -102
  65. package/src/packlets/validation/array.ts +0 -84
  66. package/src/packlets/validation/boolean.ts +0 -63
  67. package/src/packlets/validation/classes.ts +0 -38
  68. package/src/packlets/validation/common.ts +0 -28
  69. package/src/packlets/validation/field.ts +0 -99
  70. package/src/packlets/validation/genericValidator.ts +0 -204
  71. package/src/packlets/validation/index.ts +0 -31
  72. package/src/packlets/validation/number.ts +0 -66
  73. package/src/packlets/validation/object.ts +0 -208
  74. package/src/packlets/validation/oneOf.ts +0 -78
  75. package/src/packlets/validation/string.ts +0 -66
  76. package/src/packlets/validation/traits.ts +0 -113
  77. package/src/packlets/validation/typeGuard.ts +0 -83
  78. package/src/packlets/validation/validator.ts +0 -157
  79. package/src/packlets/validation/validatorBase.ts +0 -66
  80. package/src/packlets/validation/validators.ts +0 -254
@@ -1,171 +0,0 @@
1
- /*
2
- * Copyright (c) 2025 Erik Fortune
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to deal
6
- * in the Software without restriction, including without limitation the rights
7
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- * copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in all
12
- * copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
- * SOFTWARE.
21
- */
22
-
23
- import { captureResult, fail, Result, succeed } from '../../base';
24
- import { DirectoryItem } from '../directoryItem';
25
- import { FileItem } from '../fileItem';
26
- import { FileTreeItem, IFileTreeAccessors } from '../fileTreeAccessors';
27
- import { InMemoryDirectory, InMemoryFile, TreeBuilder } from './treeBuilder';
28
-
29
- /**
30
- * Represents a single file in an in-memory {@link FileTree.FileTree | file tree}.
31
- * @public
32
- */
33
- export interface IInMemoryFile {
34
- /**
35
- * The absolute path of the file in the tree.
36
- */
37
- readonly path: string;
38
-
39
- /**
40
- * The contents of the file
41
- */
42
- readonly contents: unknown;
43
- }
44
-
45
- /**
46
- * Implementation of {@link FileTree.IFileTreeAccessors | IFileTreeAccessors} that uses an in-memory
47
- * tree to access files and directories.
48
- * @public
49
- */
50
- export class InMemoryTreeAccessors implements IFileTreeAccessors {
51
- private readonly _tree: TreeBuilder;
52
-
53
- /**
54
- * Protected constructor for derived classes.
55
- * @param files - An array of {@link FileTree.IInMemoryFile | in-memory files} to include in the tree.
56
- * @param prefix - Optional prefix for the tree.
57
- * @public
58
- */
59
- protected constructor(files: IInMemoryFile[], prefix?: string) {
60
- this._tree = TreeBuilder.create(prefix).orThrow();
61
- for (const file of files) {
62
- this._tree.addFile(file.path, file.contents).orThrow();
63
- }
64
- }
65
-
66
- /**
67
- * Creates a new {@link FileTree.InMemoryTreeAccessors | InMemoryTreeAccessors} instance with the supplied
68
- * in-memory files.
69
- * @param files - An array of {@link FileTree.IInMemoryFile | in-memory files} to include in the tree.
70
- * @param prefix - Optional prefix for the tree.
71
- */
72
- public static create(files: IInMemoryFile[], prefix?: string): Result<InMemoryTreeAccessors> {
73
- return captureResult(() => new InMemoryTreeAccessors(files, prefix));
74
- }
75
-
76
- /**
77
- * {@inheritDoc FileTree.IFileTreeAccessors.resolveAbsolutePath}
78
- */
79
- public resolveAbsolutePath(...paths: string[]): string {
80
- const parts = paths[0].startsWith('/') ? paths : [this._tree.prefix, ...paths];
81
- const joined = parts.flatMap((p) => p.split('/').filter((s) => s.length > 0)).join('/');
82
- return `/${joined}`;
83
- }
84
-
85
- /**
86
- * {@inheritdoc FileTree.IFileTreeAccessors.getExtension}
87
- */
88
- public getExtension(path: string): string {
89
- const parts = path.split('.');
90
- if (parts.length === 1) {
91
- return '';
92
- }
93
- return `.${parts.pop()}`;
94
- }
95
-
96
- /**
97
- * {@inheritdoc FileTree.IFileTreeAccessors.getBaseName}
98
- */
99
- public getBaseName(path: string, suffix?: string): string {
100
- /* c8 ignore next 1 - ?? is defense in depth should never happen */
101
- const base = path.split('/').pop() ?? '';
102
- if (suffix && base.endsWith(suffix)) {
103
- return base.slice(0, base.length - suffix.length);
104
- }
105
- return base;
106
- }
107
-
108
- /**
109
- * {@inheritdoc FileTree.IFileTreeAccessors.joinPaths}
110
- */
111
- public joinPaths(...paths: string[]): string {
112
- return paths.join('/');
113
- }
114
-
115
- /**
116
- * {@inheritDoc FileTree.IFileTreeAccessors.getItem}
117
- */
118
- public getItem(itemPath: string): Result<FileTreeItem> {
119
- const existing = this._tree.byAbsolutePath.get(itemPath);
120
- if (existing) {
121
- if (existing instanceof InMemoryFile) {
122
- return FileItem.create(existing.absolutePath, this);
123
- } else if (existing instanceof InMemoryDirectory) {
124
- return DirectoryItem.create(existing.absolutePath, this);
125
- }
126
- }
127
- return fail(`${itemPath}: not found`);
128
- }
129
-
130
- /**
131
- * {@inheritDoc FileTree.IFileTreeAccessors.getFileContents}
132
- */
133
- public getFileContents(path: string): Result<string> {
134
- const item = this._tree.byAbsolutePath.get(path);
135
- if (item === undefined) {
136
- return fail(`${path}: not found`);
137
- }
138
- if (!(item instanceof InMemoryFile)) {
139
- return fail(`${path}: not a file`);
140
- }
141
- // if the body is a string we don't want to add quotes
142
- if (typeof item.contents === 'string') {
143
- return succeed(item.contents);
144
- }
145
- return captureResult(() => JSON.stringify(item.contents));
146
- }
147
-
148
- /**
149
- * {@inheritDoc FileTree.IFileTreeAccessors.getChildren}
150
- */
151
- public getChildren(path: string): Result<ReadonlyArray<FileTreeItem>> {
152
- const item = this._tree.byAbsolutePath.get(path);
153
- if (item === undefined) {
154
- return fail(`${path}: not found`);
155
- }
156
- if (!(item instanceof InMemoryDirectory)) {
157
- return fail(`${path}: not a directory`);
158
- }
159
- return captureResult(() => {
160
- const children: FileTreeItem[] = [];
161
- for (const child of item.children.values()) {
162
- if (child instanceof InMemoryFile) {
163
- children.push(FileItem.create(child.absolutePath, this).orThrow());
164
- } else if (child instanceof InMemoryDirectory) {
165
- children.push(DirectoryItem.create(child.absolutePath, this).orThrow());
166
- }
167
- }
168
- return children;
169
- });
170
- }
171
- }
@@ -1,23 +0,0 @@
1
- /*
2
- * Copyright (c) 2025 Erik Fortune
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to deal
6
- * in the Software without restriction, including without limitation the rights
7
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- * copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in all
12
- * copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
- * SOFTWARE.
21
- */
22
-
23
- export * from './inMemoryTree';
@@ -1,203 +0,0 @@
1
- /*
2
- * Copyright (c) 2025 Erik Fortune
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to deal
6
- * in the Software without restriction, including without limitation the rights
7
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- * copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in all
12
- * copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
- * SOFTWARE.
21
- */
22
-
23
- import { Result, captureResult, fail, succeed } from '../../base';
24
-
25
- /**
26
- * Represents a file in an in-memory file tree.
27
- * @public
28
- */
29
- export class InMemoryFile {
30
- /**
31
- * The absolute path of the file.
32
- */
33
- public readonly absolutePath: string;
34
- /**
35
- * The contents of the file.
36
- */
37
- public readonly contents: unknown;
38
-
39
- /**
40
- * Creates a new {@link InMemoryFile | InMemoryFile} instance.
41
- * @param absolutePath - The absolute path of the file.
42
- * @param contents - The contents of the file.
43
- */
44
- public constructor(absolutePath: string, contents: unknown) {
45
- this.absolutePath = absolutePath;
46
- this.contents = contents;
47
- }
48
- }
49
-
50
- /**
51
- * Represents a directory in an in-memory file tree.
52
- * @public
53
- */
54
- export class InMemoryDirectory {
55
- /**
56
- * The absolute path of the directory.
57
- */
58
- public readonly absolutePath: string;
59
- protected _children: Map<string, InMemoryDirectory | InMemoryFile>;
60
-
61
- /**
62
- * The children of the directory.
63
- */
64
- public get children(): ReadonlyMap<string, InMemoryDirectory | InMemoryFile> {
65
- return this._children;
66
- }
67
-
68
- /**
69
- * Creates an empty new {@link InMemoryDirectory | InMemoryDirectory} instance.
70
- * @param absolutePath - The absolute path of the directory.
71
- */
72
- public constructor(absolutePath: string) {
73
- this.absolutePath = absolutePath;
74
- this._children = new Map<string, InMemoryDirectory | InMemoryFile>();
75
- }
76
-
77
- /**
78
- * Gets or adds a child directory with the specified name.
79
- * @param name - The name of the child directory.
80
- * @returns {@link Success | Success} with the child directory if successful, or
81
- * {@link Failure | Failure} with an error message otherwise.
82
- */
83
- public getOrAddDirectory(name: string): Result<InMemoryDirectory> {
84
- const existing = this._children.get(name);
85
- if (existing) {
86
- if (existing instanceof InMemoryDirectory) {
87
- return succeed(existing);
88
- }
89
- return fail(`${name}: not a directory`);
90
- }
91
- const child = new InMemoryDirectory(this.getChildPath(name));
92
- this._children.set(name, child);
93
- return succeed(child);
94
- }
95
-
96
- /**
97
- * Adds a file to the directory.
98
- * @param name - The name of the file.
99
- * @param contents - The contents of the file.
100
- * @returns {@link Success | Success} with the new file if successful, or
101
- * {@link Failure | Failure} with an error message otherwise.
102
- */
103
- public addFile(name: string, contents: unknown): Result<InMemoryFile> {
104
- if (this._children.has(name)) {
105
- return fail(`${name}: already exists`);
106
- }
107
- const child = new InMemoryFile(this.getChildPath(name), contents);
108
- this._children.set(name, child);
109
- return succeed(child);
110
- }
111
-
112
- /**
113
- * Gets the absolute path for a child of this directory with the supplied
114
- * name.
115
- * @param name - The name of the child.
116
- * @returns {@link Success | Success} with the absolute path if successful, or
117
- * {@link Failure | Failure} with an error message otherwise.
118
- */
119
- public getChildPath(name: string): string {
120
- if (this.absolutePath === '/') {
121
- return `/${name}`;
122
- }
123
- return [this.absolutePath, name].join('/');
124
- }
125
- }
126
-
127
- /**
128
- * Helper class to build an in-memory file tree.
129
- * @public
130
- */
131
- export class TreeBuilder {
132
- /**
133
- * The prefix for all paths in the tree.
134
- */
135
- public readonly prefix: string;
136
-
137
- /**
138
- * The root directory of the tree.
139
- */
140
- public readonly root: InMemoryDirectory;
141
-
142
- /**
143
- * A map of all directories and files in the tree by absolute path.
144
- */
145
- public readonly byAbsolutePath: Map<string, InMemoryDirectory | InMemoryFile>;
146
-
147
- /**
148
- * Protected constructor for derived classes.
149
- * @param prefix - The prefix for all paths in the tree.
150
- * @public
151
- */
152
- protected constructor(prefix?: string) {
153
- this.prefix = prefix ?? '/';
154
- if (!this.prefix.startsWith('/')) {
155
- throw new Error(`${prefix}: not an absolute path`);
156
- }
157
- this.root = new InMemoryDirectory(this.prefix);
158
- this.byAbsolutePath = new Map<string, InMemoryDirectory | InMemoryFile>();
159
- this.byAbsolutePath.set(this.prefix, this.root);
160
- }
161
-
162
- /**
163
- * Creates a new {@link TreeBuilder | TreeBuilder} instance.
164
- * @param prefix - The prefix for all paths in the tree.
165
- * @returns {@link Success | Success} with the new {@link TreeBuilder | TreeBuilder} instance if successful,
166
- * or {@link Failure | Failure} with an error message otherwise.
167
- * @public
168
- */
169
- public static create(prefix?: string): Result<TreeBuilder> {
170
- return captureResult(() => new TreeBuilder(prefix));
171
- }
172
-
173
- /**
174
- * Adds a file to the tree.
175
- * @param absolutePath - The absolute path of the file.
176
- * @param contents - The contents of the file.
177
- * @returns {@link Success | Success} with the new file if successful, or
178
- * {@link Failure | Failure} with an error message otherwise.
179
- * @public
180
- */
181
- public addFile(absolutePath: string, contents: unknown): Result<InMemoryFile> {
182
- const parts = absolutePath.split('/').filter((p) => p.length > 0);
183
- if (parts.length === 0) {
184
- return fail(`${absolutePath}: invalid file path`);
185
- }
186
- let dir = this.root;
187
- while (parts.length > 1) {
188
- const part = parts.shift()!;
189
- const result = dir.getOrAddDirectory(part);
190
- if (result.isFailure()) {
191
- return fail(result.message);
192
- }
193
- dir = result.value;
194
- if (!this.byAbsolutePath.has(dir.absolutePath)) {
195
- this.byAbsolutePath.set(dir.absolutePath, dir);
196
- }
197
- }
198
- return dir.addFile(parts[0], contents).onSuccess((file) => {
199
- this.byAbsolutePath.set(file.absolutePath, file);
200
- return succeed(file);
201
- });
202
- }
203
- }
@@ -1,31 +0,0 @@
1
- /*
2
- * Copyright (c) 2025 Erik Fortune
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to deal
6
- * in the Software without restriction, including without limitation the rights
7
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- * copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in all
12
- * copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
- * SOFTWARE.
21
- */
22
-
23
- import { IInMemoryFile, InMemoryTreeAccessors } from './in-memory';
24
-
25
- export * from './directoryItem';
26
- export * from './fileItem';
27
- export * from './fileTreeAccessors';
28
- export * from './fsTree';
29
- export * from './fileTree';
30
-
31
- export { IInMemoryFile, InMemoryTreeAccessors };
@@ -1,81 +0,0 @@
1
- /*
2
- * Copyright (c) 2023 Erik Fortune
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to deal
6
- * in the Software without restriction, including without limitation the rights
7
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- * copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in all
12
- * copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
- * SOFTWARE.
21
- */
22
-
23
- import { HashingNormalizer } from './hashingNormalizer';
24
-
25
- const textEncoder: TextEncoder = new TextEncoder();
26
-
27
- const POLYNOMIAL: number = 0xedb88320;
28
-
29
- const crc32Table: number[] = [];
30
-
31
- function crc32(bytes: Uint8Array, crc: number = 0xffffffff): number {
32
- if (crc32Table.length === 0) {
33
- buildCrc32Table();
34
- }
35
- for (let i = 0; i < bytes.length; ++i) {
36
- // eslint-disable-next-line no-bitwise
37
- crc = crc32Table[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
38
- }
39
- return (crc ^ -1) >>> 0;
40
- }
41
-
42
- const toUInt32 = (n: number): number => {
43
- if (n >= 0) {
44
- return n;
45
- }
46
- return 0xffffffff - n * -1 + 1;
47
- };
48
-
49
- function buildCrc32Table(): void {
50
- if (crc32Table.length === 0) {
51
- for (let n = 0; n < 256; n++) {
52
- let r = n;
53
- for (let i = 0; i < 8; i++) {
54
- // eslint-disable-next-line no-bitwise
55
- if (r & 1) {
56
- r = (r >>> 1) ^ POLYNOMIAL;
57
- } else {
58
- r = r >>> 1;
59
- }
60
- }
61
- crc32Table.push(toUInt32(r));
62
- }
63
- }
64
- }
65
-
66
- /**
67
- * A {@link Hash.HashingNormalizer | hashing normalizer} which computes object
68
- * hash using the CRC32 algorithm.
69
- * @public
70
- */
71
- export class Crc32Normalizer extends HashingNormalizer {
72
- public constructor() {
73
- super(Crc32Normalizer.crc32Hash);
74
- }
75
-
76
- public static crc32Hash(parts: string[]): string {
77
- return crc32(textEncoder.encode(parts.join('|')))
78
- .toString(16)
79
- .padStart(8, '0');
80
- }
81
- }
@@ -1,102 +0,0 @@
1
- /*
2
- * Copyright (c) 2021 Erik Fortune
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to deal
6
- * in the Software without restriction, including without limitation the rights
7
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- * copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in all
12
- * copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
- * SOFTWARE.
21
- */
22
-
23
- import { Normalizer, Result, captureResult, fail, mapResults, succeed } from '../base';
24
-
25
- /**
26
- * Function to compute a hash from a pre-normalized array of strings.
27
- * @public
28
- */
29
- export type HashFunction = (parts: string[]) => string;
30
-
31
- /**
32
- * Normalizes an arbitrary JSON object
33
- * @public
34
- */
35
- export class HashingNormalizer extends Normalizer {
36
- private _hash: HashFunction;
37
-
38
- public constructor(hash: HashFunction) {
39
- super();
40
- this._hash = hash;
41
- }
42
-
43
- public computeHash(from: unknown): Result<string> {
44
- switch (typeof from) {
45
- case 'string':
46
- case 'bigint':
47
- case 'boolean':
48
- case 'number':
49
- case 'symbol':
50
- case 'undefined':
51
- return this._normalizeLiteralToString(from).onSuccess((v) => {
52
- return captureResult(() => this._hash([v]));
53
- });
54
- case 'object':
55
- if (from === null || from instanceof Date || from instanceof RegExp) {
56
- return this._normalizeLiteralToString(from).onSuccess((v) => {
57
- return captureResult(() => this._hash([v]));
58
- });
59
- } else if (Array.isArray(from)) {
60
- return mapResults(from.map((e) => this.computeHash(e))).onSuccess((a) => {
61
- return captureResult(() => this._hash(a));
62
- });
63
- } else if (from instanceof Map || from instanceof Set) {
64
- return this.computeHash(this.normalizeEntries(from.entries()));
65
- }
66
- return this.computeHash(this.normalizeEntries(Object.entries(from)));
67
- }
68
- return fail(`computeHash: Unexpected type - cannot hash '${typeof from}'`);
69
- }
70
-
71
- /**
72
- * Constructs a normalized string representation of some literal value.
73
- * @param from - The literal value to be normalized.
74
- * @returns A normalized string representation of the literal.
75
- * @internal
76
- */
77
- protected _normalizeLiteralToString(
78
- from: string | number | bigint | boolean | symbol | undefined | Date | RegExp | null
79
- ): Result<string> {
80
- switch (typeof from) {
81
- case 'string':
82
- return succeed(from);
83
- case 'bigint':
84
- case 'boolean':
85
- case 'number':
86
- case 'symbol':
87
- case 'undefined':
88
- return succeed(`${typeof from}:[[[${String(from)}]]]`);
89
- }
90
- if (from === null) {
91
- return succeed('object:[[[null]]');
92
- }
93
- if (from instanceof Date) {
94
- return succeed(`Date:[[[${String(from.valueOf())}]]]`);
95
- }
96
- if (from instanceof RegExp) {
97
- return succeed(`RegExp:[[[${from.toString()}]]]`);
98
- }
99
- /* c8 ignore next 2 */
100
- return fail(`cannot normalize ${JSON.stringify(from)}`);
101
- }
102
- }
@@ -1,84 +0,0 @@
1
- /*
2
- * Copyright (c) 2022 Erik Fortune
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to deal
6
- * in the Software without restriction, including without limitation the rights
7
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- * copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in all
12
- * copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
- * SOFTWARE.
21
- */
22
-
23
- import { Failure, fail } from '../base';
24
- import { Validator, ValidatorOptions } from './validator';
25
- import { ValidatorBase, ValidatorBaseConstructorParams } from './validatorBase';
26
-
27
- /**
28
- * Parameters used to construct a {@link Validation.Classes.ArrayValidator | ArrayValidator}.
29
- * @public
30
- */
31
- // eslint-disable-next-line @typescript-eslint/naming-convention
32
- export interface ArrayValidatorConstructorParams<T, TC = unknown>
33
- extends ValidatorBaseConstructorParams<T[], TC> {
34
- validateElement: Validator<T, TC>;
35
- }
36
-
37
- /**
38
- * An in-place {@link Validator | Validator} for arrays of validated
39
- * values or objects.
40
- * @public
41
- */
42
- export class ArrayValidator<T, TC = unknown> extends ValidatorBase<T[], TC> {
43
- /**
44
- * {@link Validation.ValidatorOptions | Options} which apply to this
45
- * validator.
46
- */
47
- public readonly options: ValidatorOptions<TC>;
48
-
49
- protected readonly _validateElement: Validator<T, TC>;
50
-
51
- /**
52
- * Constructs a new {@link Validation.Classes.ArrayValidator | ArrayValidator}.
53
- * @param params - Optional {@link Validation.Classes.ArrayValidatorConstructorParams | init params} for the
54
- * new {@link Validation.Classes.ArrayValidator | ArrayValidator}.
55
- */
56
- public constructor(params: ArrayValidatorConstructorParams<T, TC>) {
57
- super(params);
58
- this._validateElement = params.validateElement;
59
- this.options = params.options ?? {};
60
- }
61
-
62
- /**
63
- * Static method which validates that a supplied `unknown` value is a `array`
64
- * and that every element of the array can be validated by the supplied array
65
- * validator.
66
- * @param from - The `unknown` value to be tested.
67
- * @param context - Optional validation context will be propagated to element validator.
68
- * @param self - Optional self-reference for recursive validation.
69
- * @returns Returns `true` if `from` is an `array` of valid elements, or
70
- * {@link Failure} with an error message if not.
71
- */
72
- protected _validate(from: unknown, context?: TC, self?: Validator<T[], TC>): boolean | Failure<T[]> {
73
- if (Array.isArray(from)) {
74
- for (const elem of from) {
75
- const result = this._validateElement.validate(elem, context);
76
- if (!result.isSuccess()) {
77
- return fail(result.message);
78
- }
79
- }
80
- return true;
81
- }
82
- return fail<T[]>(`"${from}": not an array`);
83
- }
84
- }