@fgv/ts-extras 2.0.1

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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +48 -0
  3. package/dist/ts-extras.d.ts +445 -0
  4. package/dist/tsdoc-metadata.json +11 -0
  5. package/lib/index.d.ts +7 -0
  6. package/lib/index.d.ts.map +1 -0
  7. package/lib/index.js +58 -0
  8. package/lib/index.js.map +1 -0
  9. package/lib/packlets/conversion/converters.d.ts +28 -0
  10. package/lib/packlets/conversion/converters.d.ts.map +1 -0
  11. package/lib/packlets/conversion/converters.js +72 -0
  12. package/lib/packlets/conversion/converters.js.map +1 -0
  13. package/lib/packlets/conversion/index.d.ts +3 -0
  14. package/lib/packlets/conversion/index.d.ts.map +1 -0
  15. package/lib/packlets/conversion/index.js +50 -0
  16. package/lib/packlets/conversion/index.js.map +1 -0
  17. package/lib/packlets/csv/csvHelpers.d.ts +17 -0
  18. package/lib/packlets/csv/csvHelpers.d.ts.map +1 -0
  19. package/lib/packlets/csv/csvHelpers.js +69 -0
  20. package/lib/packlets/csv/csvHelpers.js.map +1 -0
  21. package/lib/packlets/csv/index.d.ts +2 -0
  22. package/lib/packlets/csv/index.d.ts.map +1 -0
  23. package/lib/packlets/csv/index.js +39 -0
  24. package/lib/packlets/csv/index.js.map +1 -0
  25. package/lib/packlets/experimental/extendedArray.d.ts +56 -0
  26. package/lib/packlets/experimental/extendedArray.d.ts.map +1 -0
  27. package/lib/packlets/experimental/extendedArray.js +106 -0
  28. package/lib/packlets/experimental/extendedArray.js.map +1 -0
  29. package/lib/packlets/experimental/formatter.d.ts +66 -0
  30. package/lib/packlets/experimental/formatter.d.ts.map +1 -0
  31. package/lib/packlets/experimental/formatter.js +75 -0
  32. package/lib/packlets/experimental/formatter.js.map +1 -0
  33. package/lib/packlets/experimental/index.d.ts +4 -0
  34. package/lib/packlets/experimental/index.d.ts.map +1 -0
  35. package/lib/packlets/experimental/index.js +41 -0
  36. package/lib/packlets/experimental/index.js.map +1 -0
  37. package/lib/packlets/experimental/rangeOf.d.ts +122 -0
  38. package/lib/packlets/experimental/rangeOf.d.ts.map +1 -0
  39. package/lib/packlets/experimental/rangeOf.js +185 -0
  40. package/lib/packlets/experimental/rangeOf.js.map +1 -0
  41. package/lib/packlets/hash/hash.d.ts +51 -0
  42. package/lib/packlets/hash/hash.d.ts.map +1 -0
  43. package/lib/packlets/hash/hash.js +166 -0
  44. package/lib/packlets/hash/hash.js.map +1 -0
  45. package/lib/packlets/hash/index.d.ts +2 -0
  46. package/lib/packlets/hash/index.d.ts.map +1 -0
  47. package/lib/packlets/hash/index.js +39 -0
  48. package/lib/packlets/hash/index.js.map +1 -0
  49. package/lib/packlets/record-jar/index.d.ts +2 -0
  50. package/lib/packlets/record-jar/index.d.ts.map +1 -0
  51. package/lib/packlets/record-jar/index.js +39 -0
  52. package/lib/packlets/record-jar/index.js.map +1 -0
  53. package/lib/packlets/record-jar/recordJarHelpers.d.ts +37 -0
  54. package/lib/packlets/record-jar/recordJarHelpers.d.ts.map +1 -0
  55. package/lib/packlets/record-jar/recordJarHelpers.js +263 -0
  56. package/lib/packlets/record-jar/recordJarHelpers.js.map +1 -0
  57. package/package.json +69 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formatter.js","sourceRoot":"","sources":["../../../src/packlets/experimental/formatter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;AAEH,4CAA2E;AAC3E,wDAAgC;AAEhC,kBAAQ,CAAC,MAAM,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC;AAuBnC;;;GAGG;AACH,MAAa,eAAe;IAC1B;;;;;;OAMG;IACO,MAAM,CAAC,aAAa,CAAC,OAAiB,EAAE,KAAa,EAAE,KAAyB;QACxF,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,MAAM,MAAM,GAAG,KAAK,KAAK,GAAG,CAAC,MAAM,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;YAC7C,OAAO,CAAC,IAAI,CAAC,GAAG,MAAM,IAAI,KAAK,EAAE,CAAC,CAAC;QACrC,CAAC;IACH,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,QAAgB;QAC5B,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,kBAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC;IAC9D,CAAC;CACF;AArBD,0CAqBC;AAsBD;;;;;;;;GAQG;AACH,SAAgB,UAAU,CAAI,MAAc,EAAE,KAAU,EAAE,aAA2B;IACnF,OAAO,IAAA,qBAAU,EACf,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;QACjB,OAAO,aAAa,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IACrC,CAAC,CAAC,CACH,CAAC,SAAS,CAAC,CAAC,OAAiB,EAAE,EAAE;QAChC,MAAM,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;QACjD,OAAO,IAAA,kBAAO,EAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACtC,CAAC,CAAC,CAAC;AACL,CAAC;AATD,gCASC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Result, captureResult, mapResults, succeed } from '@fgv/ts-utils';\nimport Mustache from 'mustache';\n\nMustache.escape = (s: string) => s;\n\n/**\n * Destination format for some formatted string.\n * @beta\n */\nexport type FormatTargets = 'text' | 'markdown' | 'embed';\n\n/**\n * Interface for an object that can be formatted.\n * @beta\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface Formattable {\n /**\n * Formats an object using the supplied mustache template.\n * @param format - A mustache template used to format the object.\n * @returns {@link Success} with the resulting string, or {@link Failure}\n * with an error message if an error occurs.\n */\n format(format: string): Result<string>;\n}\n\n/**\n * Base class which adds common formatting.\n * @beta\n */\nexport class FormattableBase {\n /**\n * Helper enables derived classes to add named details to a formatted presentation.\n * @param details - An array of detail description strings.\n * @param label - Label to use for the new detail.\n * @param value - Value to use for the new detail.\n * @internal\n */\n protected static _tryAddDetail(details: string[], label: string, value: string | undefined): void {\n if (value !== undefined) {\n const padded = ` ${label}:`.padEnd(20, ' ');\n details.push(`${padded} ${value}`);\n }\n }\n\n /**\n * {@inheritdoc Experimental.Formattable.format}\n */\n public format(template: string): Result<string> {\n return captureResult(() => Mustache.render(template, this));\n }\n}\n\n/**\n * Type definition for a formatting function, which takes a `string` and an\n * item and returns {@link Result | Result<string>}.\n * @beta\n */\nexport type Formatter<T> = (format: string, item: T) => Result<string>;\n\n/**\n * A collection of {@link Experimental.Formatter | formatters} indexed by target name, to enable\n * different format methods per output target.\n * @beta\n */\nexport type FormattersByExtendedTarget<TFT extends FormatTargets, T> = Record<TFT, Formatter<T>>;\n/**\n * A collection of {@link Experimental.Formatter | formatters} indexed by the\n * {@link Experimental.FormatTargets | default supported target formats}.\n * @beta\n */\nexport type FormattersByTarget<T> = FormattersByExtendedTarget<FormatTargets, T>;\n\n/**\n * Formats a list of items using the supplied template and formatter, one result\n * per output line.\n * @param format - A mustache template used to format each item.\n * @param items - The items to be formatted.\n * @param itemFormatter - The {@link Experimental.Formatter | Formatter<T>} used to format each item.\n * @returns The resulting string.\n * @beta\n */\nexport function formatList<T>(format: string, items: T[], itemFormatter: Formatter<T>): Result<string> {\n return mapResults(\n items.map((item) => {\n return itemFormatter(format, item);\n })\n ).onSuccess((results: string[]) => {\n const filtered = results.filter((s) => s !== '');\n return succeed(filtered.join('\\n'));\n });\n}\n"]}
@@ -0,0 +1,4 @@
1
+ export * from './extendedArray';
2
+ export * from './formatter';
3
+ export * from './rangeOf';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/packlets/experimental/index.ts"],"names":[],"mappings":"AAsBA,cAAc,iBAAiB,CAAC;AAChC,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC"}
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2023 Erik Fortune
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ * of this software and associated documentation files (the "Software"), to deal
7
+ * in the Software without restriction, including without limitation the rights
8
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ * copies of the Software, and to permit persons to whom the Software is
10
+ * furnished to do so, subject to the following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be included in all
13
+ * copies or substantial portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ * SOFTWARE.
22
+ */
23
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
24
+ if (k2 === undefined) k2 = k;
25
+ var desc = Object.getOwnPropertyDescriptor(m, k);
26
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
27
+ desc = { enumerable: true, get: function() { return m[k]; } };
28
+ }
29
+ Object.defineProperty(o, k2, desc);
30
+ }) : (function(o, m, k, k2) {
31
+ if (k2 === undefined) k2 = k;
32
+ o[k2] = m[k];
33
+ }));
34
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
35
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ __exportStar(require("./extendedArray"), exports);
39
+ __exportStar(require("./formatter"), exports);
40
+ __exportStar(require("./rangeOf"), exports);
41
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/experimental/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;;;;;;;AAEH,kDAAgC;AAChC,8CAA4B;AAC5B,4CAA0B","sourcesContent":["/*\n * Copyright (c) 2023 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nexport * from './extendedArray';\nexport * from './formatter';\nexport * from './rangeOf';\n"]}
@@ -0,0 +1,122 @@
1
+ import { Result } from '@fgv/ts-utils';
2
+ /**
3
+ * Represents a generic range of some comparable type `<T>`.
4
+ * @public
5
+ */
6
+ export interface RangeOfProperties<T> {
7
+ readonly min?: T;
8
+ readonly max?: T;
9
+ }
10
+ /**
11
+ * Format strings (in mustache format) to
12
+ * use for both open-ended and complete
13
+ * {@link Experimental.RangeOf | RangeOf<T>}.
14
+ * @public
15
+ */
16
+ export interface RangeOfFormats {
17
+ minOnly: string;
18
+ maxOnly: string;
19
+ minMax: string;
20
+ }
21
+ /**
22
+ * Default {@link Experimental.RangeOfFormats | formats} to use for both
23
+ * open-ended and complete {@link Experimental.RangeOf | RangeOf<T>}.
24
+ * @public
25
+ */
26
+ export declare const DEFAULT_RANGEOF_FORMATS: RangeOfFormats;
27
+ /**
28
+ * Simple implementation of a possibly open-ended range of some comparable
29
+ * type `<T>` with test and formatting.
30
+ * @public
31
+ */
32
+ export declare class RangeOf<T> implements RangeOfProperties<T> {
33
+ /**
34
+ * Minimum extent of the range.
35
+ */
36
+ readonly min?: T;
37
+ /**
38
+ * Maximum extent of the range.
39
+ */
40
+ readonly max?: T;
41
+ /**
42
+ * Creates a new {@link Experimental.RangeOf | RangeOf<T>}.
43
+ * @param min - Optional minimum extent of the range.
44
+ * @param max - Optional maximum extent of the range.
45
+ */
46
+ constructor(min?: T, max?: T);
47
+ /**
48
+ * Static constructor for a {@link Experimental.RangeOf | RangeOf<T>}.
49
+ * @param init - {@link Experimental.RangeOfProperties | Range initializer}.
50
+ * @returns A new {@link Experimental.RangeOf | RangeOf<T>}.
51
+ */
52
+ static createRange<T>(init?: RangeOfProperties<T>): Result<RangeOf<T>>;
53
+ /**
54
+ * Gets a formatted description of a {@link Experimental.RangeOfProperties | RangeOfProperties<T>} given an
55
+ * optional set of formats and 'empty' value to use.
56
+ * @param range - The {@link Experimental.RangeOfProperties | RangeOfProperties<T>} to be formatted.
57
+ * @param formats - Optional {@link Experimental.RangeOfFormats | formats} to use. Default is
58
+ * {@link Experimental.DEFAULT_RANGEOF_FORMATS | DEFAULT_RANGEOF_FORMATS}.
59
+ * @param emptyValue - Value which represents unbounded minimum or maximum for this range. Default is `undefined`.
60
+ * @returns A string representation of the range.
61
+ */
62
+ static propertiesToString<T>(range: RangeOfProperties<T>, formats?: RangeOfFormats, emptyValue?: T): string | undefined;
63
+ /**
64
+ * Default comparison uses javascript built-in comparison.
65
+ * @param t1 - First value to be compared.
66
+ * @param t2 - Second value to be compared.
67
+ * @returns `'less'` if `t1` is less than `t2`, `'greater'` if `t1` is larger
68
+ * and `'equal'` if `t1` and `t2` are equal.
69
+ * @internal
70
+ */
71
+ protected static _defaultCompare<T>(t1: T, t2: T): 'less' | 'equal' | 'greater';
72
+ /**
73
+ * Checks if a supplied value is within this range.
74
+ * @param t - The value to be tested.
75
+ * @returns `'included'` if `t` falls within the range, `'less'` if `t` falls
76
+ * below the minimum extent of the range and `'greater'` if `t` is above the
77
+ * maximum extent.
78
+ */
79
+ check(t: T): 'less' | 'included' | 'greater';
80
+ /**
81
+ * Determines if a supplied value is within this range.
82
+ * @param t - The value to be tested.
83
+ * @returns Returns `true` if `t` falls within the range, `false` otherwise.
84
+ */
85
+ includes(t: T): boolean;
86
+ /**
87
+ * Finds the transition value that would bring a supplied value `t` into
88
+ * range.
89
+ * @param t - The value to be tested.
90
+ * @returns The minimum extent of the range if `t` is below the range or
91
+ * the maximum extent of the range if `t` is above the range. Returns
92
+ * `undefined` if `t` already falls within the range.
93
+ */
94
+ findTransition(t: T): T | undefined;
95
+ /**
96
+ * Formats the minimum and maximum values of this range.
97
+ * @param format - A format function used to format the values.
98
+ * @returns A {@link Experimental.RangeOfProperties | RangeOfProperties<string>} containing the
99
+ * formatted representation of the {@link Experimental.RangeOf.min | minimum} and
100
+ * {@link Experimental.RangeOf.max | maximum}
101
+ * extent of the range, or `undefined` for an extent that is not present.
102
+ */
103
+ toFormattedProperties(format: (value: T) => string | undefined): RangeOfProperties<string>;
104
+ /**
105
+ * Formats this range using the supplied format function.
106
+ * @param format - Format function used to format minimum and maximum extent values.
107
+ * @param formats - The {@link Experimental.RangeOfFormats | format strings} used to format the range
108
+ * (default {@link Experimental.DEFAULT_RANGEOF_FORMATS}).
109
+ * @returns Returns a formatted representation of this range.
110
+ */
111
+ format(format: (value: T) => string | undefined, formats?: RangeOfFormats): string | undefined;
112
+ /**
113
+ * Inner compare method can be overridden by a derived class.
114
+ * @param t1 - First value to compare.
115
+ * @param t2 - Second value to compare.
116
+ * @returns `'less'` if `t1` is less than `t2`, `'greater'` if `t1` is larger
117
+ * and `'equal'` if `t1` and `t2` are equal.
118
+ * @internal
119
+ */
120
+ protected _compare(t1: T, t2: T): 'less' | 'equal' | 'greater';
121
+ }
122
+ //# sourceMappingURL=rangeOf.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rangeOf.d.ts","sourceRoot":"","sources":["../../../src/packlets/experimental/rangeOf.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,MAAM,EAAiB,MAAM,eAAe,CAAC;AAGtD;;;GAGG;AAEH,MAAM,WAAW,iBAAiB,CAAC,CAAC;IAClC,QAAQ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AAC,GAAG,CAAC,GAAG,SAAS;IAU1C;;;;;;;OAOG;IACI,qBAAqB,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,MAAM,GAAG,SAAS,GAAG,iBAAiB,CAAC,MAAM,CAAC;IAOjG;;;;;;OAMG;IACI,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,MAAM,GAAG,SAAS,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,MAAM,GAAG,SAAS;IAIrG;;;;;;;OAOG;IACH,SAAS,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,MAAM,GAAG,OAAO,GAAG,SAAS;CAG/D"}
@@ -0,0 +1,185 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2020 Erik Fortune
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ * of this software and associated documentation files (the "Software"), to deal
7
+ * in the Software without restriction, including without limitation the rights
8
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ * copies of the Software, and to permit persons to whom the Software is
10
+ * furnished to do so, subject to the following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be included in all
13
+ * copies or substantial portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ * SOFTWARE.
22
+ */
23
+ var __importDefault = (this && this.__importDefault) || function (mod) {
24
+ return (mod && mod.__esModule) ? mod : { "default": mod };
25
+ };
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.RangeOf = exports.DEFAULT_RANGEOF_FORMATS = void 0;
28
+ const ts_utils_1 = require("@fgv/ts-utils");
29
+ const mustache_1 = __importDefault(require("mustache"));
30
+ /**
31
+ * Default {@link Experimental.RangeOfFormats | formats} to use for both
32
+ * open-ended and complete {@link Experimental.RangeOf | RangeOf<T>}.
33
+ * @public
34
+ */
35
+ exports.DEFAULT_RANGEOF_FORMATS = {
36
+ minOnly: '{{min}}-',
37
+ maxOnly: '-{{max}}',
38
+ minMax: '{{min}}-{{max}}'
39
+ };
40
+ /**
41
+ * Simple implementation of a possibly open-ended range of some comparable
42
+ * type `<T>` with test and formatting.
43
+ * @public
44
+ */
45
+ class RangeOf {
46
+ /**
47
+ * Creates a new {@link Experimental.RangeOf | RangeOf<T>}.
48
+ * @param min - Optional minimum extent of the range.
49
+ * @param max - Optional maximum extent of the range.
50
+ */
51
+ constructor(min, max) {
52
+ if (min !== undefined && max !== undefined && this._compare(min, max) === 'greater') {
53
+ throw new Error(`Inverted range - ${JSON.stringify(min)} must be <= ${JSON.stringify(max)}.`);
54
+ }
55
+ this.min = min;
56
+ this.max = max;
57
+ }
58
+ /**
59
+ * Static constructor for a {@link Experimental.RangeOf | RangeOf<T>}.
60
+ * @param init - {@link Experimental.RangeOfProperties | Range initializer}.
61
+ * @returns A new {@link Experimental.RangeOf | RangeOf<T>}.
62
+ */
63
+ static createRange(init) {
64
+ return (0, ts_utils_1.captureResult)(() => new RangeOf(init === null || init === void 0 ? void 0 : init.min, init === null || init === void 0 ? void 0 : init.max));
65
+ }
66
+ /**
67
+ * Gets a formatted description of a {@link Experimental.RangeOfProperties | RangeOfProperties<T>} given an
68
+ * optional set of formats and 'empty' value to use.
69
+ * @param range - The {@link Experimental.RangeOfProperties | RangeOfProperties<T>} to be formatted.
70
+ * @param formats - Optional {@link Experimental.RangeOfFormats | formats} to use. Default is
71
+ * {@link Experimental.DEFAULT_RANGEOF_FORMATS | DEFAULT_RANGEOF_FORMATS}.
72
+ * @param emptyValue - Value which represents unbounded minimum or maximum for this range. Default is `undefined`.
73
+ * @returns A string representation of the range.
74
+ */
75
+ static propertiesToString(range, formats, emptyValue) {
76
+ formats = formats !== null && formats !== void 0 ? formats : exports.DEFAULT_RANGEOF_FORMATS;
77
+ if (range.min !== undefined && range.min !== emptyValue) {
78
+ if (range.max !== undefined && range.max !== emptyValue) {
79
+ return mustache_1.default.render(formats.minMax, range);
80
+ }
81
+ else {
82
+ return mustache_1.default.render(formats.minOnly, range);
83
+ }
84
+ }
85
+ else if (range.max !== undefined && range.max !== emptyValue) {
86
+ return mustache_1.default.render(formats.maxOnly, range);
87
+ }
88
+ return undefined;
89
+ }
90
+ /**
91
+ * Default comparison uses javascript built-in comparison.
92
+ * @param t1 - First value to be compared.
93
+ * @param t2 - Second value to be compared.
94
+ * @returns `'less'` if `t1` is less than `t2`, `'greater'` if `t1` is larger
95
+ * and `'equal'` if `t1` and `t2` are equal.
96
+ * @internal
97
+ */
98
+ static _defaultCompare(t1, t2) {
99
+ if (t1 < t2) {
100
+ return 'less';
101
+ }
102
+ else if (t1 > t2) {
103
+ return 'greater';
104
+ }
105
+ return 'equal';
106
+ }
107
+ /**
108
+ * Checks if a supplied value is within this range.
109
+ * @param t - The value to be tested.
110
+ * @returns `'included'` if `t` falls within the range, `'less'` if `t` falls
111
+ * below the minimum extent of the range and `'greater'` if `t` is above the
112
+ * maximum extent.
113
+ */
114
+ check(t) {
115
+ if (this.min !== undefined && this._compare(t, this.min) === 'less') {
116
+ return 'less';
117
+ }
118
+ if (this.max !== undefined && this._compare(t, this.max) !== 'less') {
119
+ return 'greater';
120
+ }
121
+ return 'included';
122
+ }
123
+ /**
124
+ * Determines if a supplied value is within this range.
125
+ * @param t - The value to be tested.
126
+ * @returns Returns `true` if `t` falls within the range, `false` otherwise.
127
+ */
128
+ includes(t) {
129
+ return this.check(t) === 'included';
130
+ }
131
+ /**
132
+ * Finds the transition value that would bring a supplied value `t` into
133
+ * range.
134
+ * @param t - The value to be tested.
135
+ * @returns The minimum extent of the range if `t` is below the range or
136
+ * the maximum extent of the range if `t` is above the range. Returns
137
+ * `undefined` if `t` already falls within the range.
138
+ */
139
+ findTransition(t) {
140
+ switch (this.check(t)) {
141
+ case 'less':
142
+ return this.min;
143
+ case 'included':
144
+ return this.max;
145
+ }
146
+ return undefined;
147
+ }
148
+ /**
149
+ * Formats the minimum and maximum values of this range.
150
+ * @param format - A format function used to format the values.
151
+ * @returns A {@link Experimental.RangeOfProperties | RangeOfProperties<string>} containing the
152
+ * formatted representation of the {@link Experimental.RangeOf.min | minimum} and
153
+ * {@link Experimental.RangeOf.max | maximum}
154
+ * extent of the range, or `undefined` for an extent that is not present.
155
+ */
156
+ toFormattedProperties(format) {
157
+ return {
158
+ min: this.min !== undefined ? format(this.min) : undefined,
159
+ max: this.max !== undefined ? format(this.max) : undefined
160
+ };
161
+ }
162
+ /**
163
+ * Formats this range using the supplied format function.
164
+ * @param format - Format function used to format minimum and maximum extent values.
165
+ * @param formats - The {@link Experimental.RangeOfFormats | format strings} used to format the range
166
+ * (default {@link Experimental.DEFAULT_RANGEOF_FORMATS}).
167
+ * @returns Returns a formatted representation of this range.
168
+ */
169
+ format(format, formats) {
170
+ return RangeOf.propertiesToString(this.toFormattedProperties(format), formats);
171
+ }
172
+ /**
173
+ * Inner compare method can be overridden by a derived class.
174
+ * @param t1 - First value to compare.
175
+ * @param t2 - Second value to compare.
176
+ * @returns `'less'` if `t1` is less than `t2`, `'greater'` if `t1` is larger
177
+ * and `'equal'` if `t1` and `t2` are equal.
178
+ * @internal
179
+ */
180
+ _compare(t1, t2) {
181
+ return RangeOf._defaultCompare(t1, t2);
182
+ }
183
+ }
184
+ exports.RangeOf = RangeOf;
185
+ //# sourceMappingURL=rangeOf.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rangeOf.js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AAC,CAAC,CAAC,KAAK,UAAU,CAAC;IACtC,CAAC;IAED;;;;;;;OAOG;IACI,cAAc,CAAC,CAAI;QACxB,QAAQ,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;YACtB,KAAK,MAAM;gBACT,OAAO,IAAI,CAAC,GAAG,CAAC;YAClB,KAAK,UAAU;gBACb,OAAO,IAAI,CAAC,GAAG,CAAC;QACpB,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED;;;;;;;OAOG;IACI,qBAAqB,CAAC,MAAwC;QACnE,OAAO;YACL,GAAG,EAAE,IAAI,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS;YAC1D,GAAG,EAAE,IAAI,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS;SAC3D,CAAC;IACJ,CAAC;IAED;;;;;;OAMG;IACI,MAAM,CAAC,MAAwC,EAAE,OAAwB;QAC9E,OAAO,OAAO,CAAC,kBAAkB,CAAC,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC;IACjF,CAAC;IAED;;;;;;;OAOG;IACO,QAAQ,CAAC,EAAK,EAAE,EAAK;QAC7B,OAAO,OAAO,CAAC,eAAe,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IACzC,CAAC;CACF;AA7JD,0BA6JC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Result, captureResult } from '@fgv/ts-utils';\nimport Mustache from 'mustache';\n\n/**\n * Represents a generic range of some comparable type `<T>`.\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface RangeOfProperties<T> {\n readonly min?: T;\n readonly max?: T;\n}\n\n/**\n * Format strings (in mustache format) to\n * use for both open-ended and complete\n * {@link Experimental.RangeOf | RangeOf<T>}.\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface RangeOfFormats {\n minOnly: string;\n maxOnly: string;\n minMax: string;\n}\n\n/**\n * Default {@link Experimental.RangeOfFormats | formats} to use for both\n * open-ended and complete {@link Experimental.RangeOf | RangeOf<T>}.\n * @public\n */\nexport const DEFAULT_RANGEOF_FORMATS: RangeOfFormats = {\n minOnly: '{{min}}-',\n maxOnly: '-{{max}}',\n minMax: '{{min}}-{{max}}'\n};\n\n/**\n * Simple implementation of a possibly open-ended range of some comparable\n * type `<T>` with test and formatting.\n * @public\n */\nexport class RangeOf<T> implements RangeOfProperties<T> {\n /**\n * Minimum extent of the range.\n */\n public readonly min?: T;\n /**\n * Maximum extent of the range.\n */\n public readonly max?: T;\n\n /**\n * Creates a new {@link Experimental.RangeOf | RangeOf<T>}.\n * @param min - Optional minimum extent of the range.\n * @param max - Optional maximum extent of the range.\n */\n public constructor(min?: T, max?: T) {\n if (min !== undefined && max !== undefined && this._compare(min, max) === 'greater') {\n throw new Error(`Inverted range - ${JSON.stringify(min)} must be <= ${JSON.stringify(max)}.`);\n }\n this.min = min;\n this.max = max;\n }\n\n /**\n * Static constructor for a {@link Experimental.RangeOf | RangeOf<T>}.\n * @param init - {@link Experimental.RangeOfProperties | Range initializer}.\n * @returns A new {@link Experimental.RangeOf | RangeOf<T>}.\n */\n public static createRange<T>(init?: RangeOfProperties<T>): Result<RangeOf<T>> {\n return captureResult(() => new RangeOf<T>(init?.min, init?.max));\n }\n\n /**\n * Gets a formatted description of a {@link Experimental.RangeOfProperties | RangeOfProperties<T>} given an\n * optional set of formats and 'empty' value to use.\n * @param range - The {@link Experimental.RangeOfProperties | RangeOfProperties<T>} to be formatted.\n * @param formats - Optional {@link Experimental.RangeOfFormats | formats} to use. Default is\n * {@link Experimental.DEFAULT_RANGEOF_FORMATS | DEFAULT_RANGEOF_FORMATS}.\n * @param emptyValue - Value which represents unbounded minimum or maximum for this range. Default is `undefined`.\n * @returns A string representation of the range.\n */\n public static propertiesToString<T>(\n range: RangeOfProperties<T>,\n formats?: RangeOfFormats,\n emptyValue?: T\n ): string | undefined {\n formats = formats ?? DEFAULT_RANGEOF_FORMATS;\n if (range.min !== undefined && range.min !== emptyValue) {\n if (range.max !== undefined && range.max !== emptyValue) {\n return Mustache.render(formats.minMax, range);\n } else {\n return Mustache.render(formats.minOnly, range);\n }\n } else if (range.max !== undefined && range.max !== emptyValue) {\n return Mustache.render(formats.maxOnly, range);\n }\n return undefined;\n }\n\n /**\n * Default comparison uses javascript built-in comparison.\n * @param t1 - First value to be compared.\n * @param t2 - Second value to be compared.\n * @returns `'less'` if `t1` is less than `t2`, `'greater'` if `t1` is larger\n * and `'equal'` if `t1` and `t2` are equal.\n * @internal\n */\n protected static _defaultCompare<T>(t1: T, t2: T): 'less' | 'equal' | 'greater' {\n if (t1 < t2) {\n return 'less';\n } else if (t1 > t2) {\n return 'greater';\n }\n return 'equal';\n }\n\n /**\n * Checks if a supplied value is within this range.\n * @param t - The value to be tested.\n * @returns `'included'` if `t` falls within the range, `'less'` if `t` falls\n * below the minimum extent of the range and `'greater'` if `t` is above the\n * maximum extent.\n */\n public check(t: T): 'less' | 'included' | 'greater' {\n if (this.min !== undefined && this._compare(t, this.min) === 'less') {\n return 'less';\n }\n if (this.max !== undefined && this._compare(t, this.max) !== 'less') {\n return 'greater';\n }\n return 'included';\n }\n\n /**\n * Determines if a supplied value is within this range.\n * @param t - The value to be tested.\n * @returns Returns `true` if `t` falls within the range, `false` otherwise.\n */\n public includes(t: T): boolean {\n return this.check(t) === 'included';\n }\n\n /**\n * Finds the transition value that would bring a supplied value `t` into\n * range.\n * @param t - The value to be tested.\n * @returns The minimum extent of the range if `t` is below the range or\n * the maximum extent of the range if `t` is above the range. Returns\n * `undefined` if `t` already falls within the range.\n */\n public findTransition(t: T): T | undefined {\n switch (this.check(t)) {\n case 'less':\n return this.min;\n case 'included':\n return this.max;\n }\n return undefined;\n }\n\n /**\n * Formats the minimum and maximum values of this range.\n * @param format - A format function used to format the values.\n * @returns A {@link Experimental.RangeOfProperties | RangeOfProperties<string>} containing the\n * formatted representation of the {@link Experimental.RangeOf.min | minimum} and\n * {@link Experimental.RangeOf.max | maximum}\n * extent of the range, or `undefined` for an extent that is not present.\n */\n public toFormattedProperties(format: (value: T) => string | undefined): RangeOfProperties<string> {\n return {\n min: this.min !== undefined ? format(this.min) : undefined,\n max: this.max !== undefined ? format(this.max) : undefined\n };\n }\n\n /**\n * Formats this range using the supplied format function.\n * @param format - Format function used to format minimum and maximum extent values.\n * @param formats - The {@link Experimental.RangeOfFormats | format strings} used to format the range\n * (default {@link Experimental.DEFAULT_RANGEOF_FORMATS}).\n * @returns Returns a formatted representation of this range.\n */\n public format(format: (value: T) => string | undefined, formats?: RangeOfFormats): string | undefined {\n return RangeOf.propertiesToString(this.toFormattedProperties(format), formats);\n }\n\n /**\n * Inner compare method can be overridden by a derived class.\n * @param t1 - First value to compare.\n * @param t2 - Second value to compare.\n * @returns `'less'` if `t1` is less than `t2`, `'greater'` if `t1` is larger\n * and `'equal'` if `t1` and `t2` are equal.\n * @internal\n */\n protected _compare(t1: T, t2: T): 'less' | 'equal' | 'greater' {\n return RangeOf._defaultCompare(t1, t2);\n }\n}\n"]}
@@ -0,0 +1,51 @@
1
+ import { Result } from '@fgv/ts-utils';
2
+ /**
3
+ * Computes an md5 hash from an array of strings. Not secure and not intended to be secure.
4
+ * @param parts - The strings to be hashed
5
+ * @returns An md5 hash of the parts
6
+ * @public
7
+ */
8
+ export declare function computeHash(parts: string[]): string;
9
+ /**
10
+ * Computes a normalized hash for an arbitrary javascript value.
11
+ * @public
12
+ */
13
+ export declare class Normalizer {
14
+ /**
15
+ * Computes a normalized md5 hash from an arbitrary supplied object. Not secure and not
16
+ * intended to be secure. Also not fast and not intended to be fast.
17
+ *
18
+ * Normalization just sorts Maps, Sets and object keys by hash so that differences in order
19
+ * do not affect the hash.
20
+ *
21
+ * @param from - The arbitrary `unknown` to be hashed.
22
+ * @returns A normalized md5 hash for the supplied value.
23
+ */
24
+ computeHash(from: unknown): Result<string>;
25
+ /**
26
+ * Compares two property names from some object being normalized.
27
+ * @param k1 - First key to be compared.
28
+ * @param k2 - Second key to be compared.
29
+ * @returns `1` if `k1` is greater, `-1` if `k2` is greater and
30
+ * `0` if they are equal.
31
+ * @internal
32
+ */
33
+ protected _compareKeys(k1: unknown, k2: unknown): number;
34
+ /**
35
+ * Normalizes an array of object property entries (e.g. as returned by `Object.entries()`).
36
+ * @remarks
37
+ * Converts property names (entry key) to string and then sorts as string.
38
+ * @param entries - The entries to be normalized.
39
+ * @returns A normalized sorted array of entries.
40
+ * @internal
41
+ */
42
+ protected _normalizeEntries(entries: Iterable<[unknown, unknown]>): [unknown, unknown][];
43
+ /**
44
+ * Constructs a normalized string representation of some literal value.
45
+ * @param from - The literal value to be normalized.
46
+ * @returns A normalized string representation of the literal.
47
+ * @internal
48
+ */
49
+ protected _normalizeLiteral(from: string | number | bigint | boolean | symbol | undefined | Date | RegExp | null): Result<string>;
50
+ }
51
+ //# sourceMappingURL=hash.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash.d.ts","sourceRoot":"","sources":["../../../src/packlets/hash/hash.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,MAAM,EAA4C,MAAM,eAAe,CAAC;AAEjF;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,CAEnD;AAED;;;GAGG;AACH,qBAAa,UAAU;IACrB;;;;;;;;;OASG;IACI,WAAW,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC;IA4BjD;;;;;;;OAOG;IACH,SAAS,CAAC,YAAY,CAAC,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,OAAO,GAAG,MAAM;IAaxD;;;;;;;OAOG;IACH,SAAS,CAAC,iBAAiB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE;IAIxF;;;;;OAKG;IACH,SAAS,CAAC,iBAAiB,CACzB,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,MAAM,GAAG,IAAI,GACnF,MAAM,CAAC,MAAM,CAAC;CAuBlB"}
@@ -0,0 +1,166 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2021 Erik Fortune
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ * of this software and associated documentation files (the "Software"), to deal
7
+ * in the Software without restriction, including without limitation the rights
8
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ * copies of the Software, and to permit persons to whom the Software is
10
+ * furnished to do so, subject to the following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be included in all
13
+ * copies or substantial portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ * SOFTWARE.
22
+ */
23
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
24
+ if (k2 === undefined) k2 = k;
25
+ var desc = Object.getOwnPropertyDescriptor(m, k);
26
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
27
+ desc = { enumerable: true, get: function() { return m[k]; } };
28
+ }
29
+ Object.defineProperty(o, k2, desc);
30
+ }) : (function(o, m, k, k2) {
31
+ if (k2 === undefined) k2 = k;
32
+ o[k2] = m[k];
33
+ }));
34
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
35
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
36
+ }) : function(o, v) {
37
+ o["default"] = v;
38
+ });
39
+ var __importStar = (this && this.__importStar) || function (mod) {
40
+ if (mod && mod.__esModule) return mod;
41
+ var result = {};
42
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
43
+ __setModuleDefault(result, mod);
44
+ return result;
45
+ };
46
+ Object.defineProperty(exports, "__esModule", { value: true });
47
+ exports.Normalizer = exports.computeHash = void 0;
48
+ const crypto = __importStar(require("crypto"));
49
+ const ts_utils_1 = require("@fgv/ts-utils");
50
+ /**
51
+ * Computes an md5 hash from an array of strings. Not secure and not intended to be secure.
52
+ * @param parts - The strings to be hashed
53
+ * @returns An md5 hash of the parts
54
+ * @public
55
+ */
56
+ function computeHash(parts) {
57
+ return crypto.createHash('md5').update(parts.join('|'), 'utf8').digest('hex');
58
+ }
59
+ exports.computeHash = computeHash;
60
+ /**
61
+ * Computes a normalized hash for an arbitrary javascript value.
62
+ * @public
63
+ */
64
+ class Normalizer {
65
+ /**
66
+ * Computes a normalized md5 hash from an arbitrary supplied object. Not secure and not
67
+ * intended to be secure. Also not fast and not intended to be fast.
68
+ *
69
+ * Normalization just sorts Maps, Sets and object keys by hash so that differences in order
70
+ * do not affect the hash.
71
+ *
72
+ * @param from - The arbitrary `unknown` to be hashed.
73
+ * @returns A normalized md5 hash for the supplied value.
74
+ */
75
+ computeHash(from) {
76
+ switch (typeof from) {
77
+ case 'string':
78
+ case 'bigint':
79
+ case 'boolean':
80
+ case 'number':
81
+ case 'symbol':
82
+ case 'undefined':
83
+ return this._normalizeLiteral(from).onSuccess((v) => {
84
+ return (0, ts_utils_1.captureResult)(() => computeHash([v]));
85
+ });
86
+ case 'object':
87
+ if (from === null || from instanceof Date || from instanceof RegExp) {
88
+ return this._normalizeLiteral(from).onSuccess((v) => {
89
+ return (0, ts_utils_1.captureResult)(() => computeHash([v]));
90
+ });
91
+ }
92
+ else if (Array.isArray(from)) {
93
+ return (0, ts_utils_1.mapResults)(from.map((e) => this.computeHash(e))).onSuccess((a) => {
94
+ return (0, ts_utils_1.captureResult)(() => computeHash(a));
95
+ });
96
+ }
97
+ else if (from instanceof Map || from instanceof Set) {
98
+ return this.computeHash(this._normalizeEntries(from.entries()));
99
+ }
100
+ return this.computeHash(this._normalizeEntries(Object.entries(from)));
101
+ }
102
+ return (0, ts_utils_1.fail)(`computeHash: Unexpected type - cannot hash '${typeof from}'`);
103
+ }
104
+ /**
105
+ * Compares two property names from some object being normalized.
106
+ * @param k1 - First key to be compared.
107
+ * @param k2 - Second key to be compared.
108
+ * @returns `1` if `k1` is greater, `-1` if `k2` is greater and
109
+ * `0` if they are equal.
110
+ * @internal
111
+ */
112
+ _compareKeys(k1, k2) {
113
+ const cs1 = String(k1);
114
+ const cs2 = String(k2);
115
+ if (cs1 > cs2) {
116
+ return 1;
117
+ }
118
+ if (cs2 > cs1) {
119
+ return -1;
120
+ }
121
+ /* c8 ignore next 2 */
122
+ return 0;
123
+ }
124
+ /**
125
+ * Normalizes an array of object property entries (e.g. as returned by `Object.entries()`).
126
+ * @remarks
127
+ * Converts property names (entry key) to string and then sorts as string.
128
+ * @param entries - The entries to be normalized.
129
+ * @returns A normalized sorted array of entries.
130
+ * @internal
131
+ */
132
+ _normalizeEntries(entries) {
133
+ return Array.from(entries).sort((e1, e2) => this._compareKeys(e1[0], e2[0]));
134
+ }
135
+ /**
136
+ * Constructs a normalized string representation of some literal value.
137
+ * @param from - The literal value to be normalized.
138
+ * @returns A normalized string representation of the literal.
139
+ * @internal
140
+ */
141
+ _normalizeLiteral(from) {
142
+ switch (typeof from) {
143
+ case 'string':
144
+ return (0, ts_utils_1.succeed)(from);
145
+ case 'bigint':
146
+ case 'boolean':
147
+ case 'number':
148
+ case 'symbol':
149
+ case 'undefined':
150
+ return (0, ts_utils_1.succeed)(`${typeof from}:[[[${String(from)}]]]`);
151
+ }
152
+ if (from === null) {
153
+ return (0, ts_utils_1.succeed)('object:[[[null]]');
154
+ }
155
+ if (from instanceof Date) {
156
+ return (0, ts_utils_1.succeed)(`Date:[[[${String(from.valueOf())}]]]`);
157
+ }
158
+ if (from instanceof RegExp) {
159
+ return (0, ts_utils_1.succeed)(`RegExp:[[[${from.toString()}]]]`);
160
+ }
161
+ /* c8 ignore next 2 */
162
+ return (0, ts_utils_1.fail)(`cannot normalize ${JSON.stringify(from)}`);
163
+ }
164
+ }
165
+ exports.Normalizer = Normalizer;
166
+ //# sourceMappingURL=hash.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash.js","sourceRoot":"","sources":["../../../src/packlets/hash/hash.ts"],"names":[],"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AAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/E,CAAC;IAED;;;;;OAKG;IACO,iBAAiB,CACzB,IAAoF;QAEpF,QAAQ,OAAO,IAAI,EAAE,CAAC;YACpB,KAAK,QAAQ;gBACX,OAAO,IAAA,kBAAO,EAAC,IAAI,CAAC,CAAC;YACvB,KAAK,QAAQ,CAAC;YACd,KAAK,SAAS,CAAC;YACf,KAAK,QAAQ,CAAC;YACd,KAAK,QAAQ,CAAC;YACd,KAAK,WAAW;gBACd,OAAO,IAAA,kBAAO,EAAC,GAAG,OAAO,IAAI,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC3D,CAAC;QACD,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;YAClB,OAAO,IAAA,kBAAO,EAAC,kBAAkB,CAAC,CAAC;QACrC,CAAC;QACD,IAAI,IAAI,YAAY,IAAI,EAAE,CAAC;YACzB,OAAO,IAAA,kBAAO,EAAC,WAAW,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC;QACzD,CAAC;QACD,IAAI,IAAI,YAAY,MAAM,EAAE,CAAC;YAC3B,OAAO,IAAA,kBAAO,EAAC,aAAa,IAAI,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;QACpD,CAAC;QACD,sBAAsB;QACtB,OAAO,IAAA,eAAI,EAAC,oBAAoB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC1D,CAAC;CACF;AAvGD,gCAuGC","sourcesContent":["/*\n * Copyright (c) 2021 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport * as crypto from 'crypto';\nimport { Result, captureResult, fail, mapResults, succeed } from '@fgv/ts-utils';\n\n/**\n * Computes an md5 hash from an array of strings. Not secure and not intended to be secure.\n * @param parts - The strings to be hashed\n * @returns An md5 hash of the parts\n * @public\n */\nexport function computeHash(parts: string[]): string {\n return crypto.createHash('md5').update(parts.join('|'), 'utf8').digest('hex');\n}\n\n/**\n * Computes a normalized hash for an arbitrary javascript value.\n * @public\n */\nexport class Normalizer {\n /**\n * Computes a normalized md5 hash from an arbitrary supplied object. Not secure and not\n * intended to be secure. Also not fast and not intended to be fast.\n *\n * Normalization just sorts Maps, Sets and object keys by hash so that differences in order\n * do not affect the hash.\n *\n * @param from - The arbitrary `unknown` to be hashed.\n * @returns A normalized md5 hash for the supplied value.\n */\n public computeHash(from: unknown): Result<string> {\n switch (typeof from) {\n case 'string':\n case 'bigint':\n case 'boolean':\n case 'number':\n case 'symbol':\n case 'undefined':\n return this._normalizeLiteral(from).onSuccess((v) => {\n return captureResult(() => computeHash([v]));\n });\n case 'object':\n if (from === null || from instanceof Date || from instanceof RegExp) {\n return this._normalizeLiteral(from).onSuccess((v) => {\n return captureResult(() => computeHash([v]));\n });\n } else if (Array.isArray(from)) {\n return mapResults(from.map((e) => this.computeHash(e))).onSuccess((a) => {\n return captureResult(() => computeHash(a));\n });\n } else if (from instanceof Map || from instanceof Set) {\n return this.computeHash(this._normalizeEntries(from.entries()));\n }\n return this.computeHash(this._normalizeEntries(Object.entries(from)));\n }\n return fail(`computeHash: Unexpected type - cannot hash '${typeof from}'`);\n }\n\n /**\n * Compares two property names from some object being normalized.\n * @param k1 - First key to be compared.\n * @param k2 - Second key to be compared.\n * @returns `1` if `k1` is greater, `-1` if `k2` is greater and\n * `0` if they are equal.\n * @internal\n */\n protected _compareKeys(k1: unknown, k2: unknown): number {\n const cs1 = String(k1);\n const cs2 = String(k2);\n if (cs1 > cs2) {\n return 1;\n }\n if (cs2 > cs1) {\n return -1;\n }\n /* c8 ignore next 2 */\n return 0;\n }\n\n /**\n * Normalizes an array of object property entries (e.g. as returned by `Object.entries()`).\n * @remarks\n * Converts property names (entry key) to string and then sorts as string.\n * @param entries - The entries to be normalized.\n * @returns A normalized sorted array of entries.\n * @internal\n */\n protected _normalizeEntries(entries: Iterable<[unknown, unknown]>): [unknown, unknown][] {\n return Array.from(entries).sort((e1, e2) => this._compareKeys(e1[0], e2[0]));\n }\n\n /**\n * Constructs a normalized string representation of some literal value.\n * @param from - The literal value to be normalized.\n * @returns A normalized string representation of the literal.\n * @internal\n */\n protected _normalizeLiteral(\n from: string | number | bigint | boolean | symbol | undefined | Date | RegExp | null\n ): Result<string> {\n switch (typeof from) {\n case 'string':\n return succeed(from);\n case 'bigint':\n case 'boolean':\n case 'number':\n case 'symbol':\n case 'undefined':\n return succeed(`${typeof from}:[[[${String(from)}]]]`);\n }\n if (from === null) {\n return succeed('object:[[[null]]');\n }\n if (from instanceof Date) {\n return succeed(`Date:[[[${String(from.valueOf())}]]]`);\n }\n if (from instanceof RegExp) {\n return succeed(`RegExp:[[[${from.toString()}]]]`);\n }\n /* c8 ignore next 2 */\n return fail(`cannot normalize ${JSON.stringify(from)}`);\n }\n}\n"]}