zilla-util 1.2.27

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/LICENSE.txt +202 -0
  2. package/lib/esm/array.d.ts +30 -0
  3. package/lib/esm/array.js +111 -0
  4. package/lib/esm/array.js.map +1 -0
  5. package/lib/esm/base64.d.ts +2 -0
  6. package/lib/esm/base64.js +51 -0
  7. package/lib/esm/base64.js.map +1 -0
  8. package/lib/esm/crypto.d.ts +16 -0
  9. package/lib/esm/crypto.js +182 -0
  10. package/lib/esm/crypto.js.map +1 -0
  11. package/lib/esm/date.d.ts +2 -0
  12. package/lib/esm/date.js +47 -0
  13. package/lib/esm/date.js.map +1 -0
  14. package/lib/esm/deep.d.ts +24 -0
  15. package/lib/esm/deep.js +318 -0
  16. package/lib/esm/deep.js.map +1 -0
  17. package/lib/esm/error.d.ts +1 -0
  18. package/lib/esm/error.js +9 -0
  19. package/lib/esm/error.js.map +1 -0
  20. package/lib/esm/hash.d.ts +4 -0
  21. package/lib/esm/hash.js +18 -0
  22. package/lib/esm/hash.js.map +1 -0
  23. package/lib/esm/index.d.ts +17 -0
  24. package/lib/esm/index.js +18 -0
  25. package/lib/esm/index.js.map +1 -0
  26. package/lib/esm/logger.d.ts +18 -0
  27. package/lib/esm/logger.js +18 -0
  28. package/lib/esm/logger.js.map +1 -0
  29. package/lib/esm/lru.d.ts +25 -0
  30. package/lib/esm/lru.js +137 -0
  31. package/lib/esm/lru.js.map +1 -0
  32. package/lib/esm/msg.d.ts +29 -0
  33. package/lib/esm/msg.js +7 -0
  34. package/lib/esm/msg.js.map +1 -0
  35. package/lib/esm/object.d.ts +8 -0
  36. package/lib/esm/object.js +31 -0
  37. package/lib/esm/object.js.map +1 -0
  38. package/lib/esm/package.d.ts +2 -0
  39. package/lib/esm/package.js +38 -0
  40. package/lib/esm/package.js.map +1 -0
  41. package/lib/esm/regex.d.ts +1 -0
  42. package/lib/esm/regex.js +22 -0
  43. package/lib/esm/regex.js.map +1 -0
  44. package/lib/esm/retry.d.ts +13 -0
  45. package/lib/esm/retry.js +57 -0
  46. package/lib/esm/retry.js.map +1 -0
  47. package/lib/esm/sha256.d.ts +50 -0
  48. package/lib/esm/sha256.js +181 -0
  49. package/lib/esm/sha256.js.map +1 -0
  50. package/lib/esm/string.d.ts +106 -0
  51. package/lib/esm/string.js +257 -0
  52. package/lib/esm/string.js.map +1 -0
  53. package/lib/esm/subst.d.ts +6 -0
  54. package/lib/esm/subst.js +37 -0
  55. package/lib/esm/subst.js.map +1 -0
  56. package/lib/esm/time.d.ts +27 -0
  57. package/lib/esm/time.js +84 -0
  58. package/lib/esm/time.js.map +1 -0
  59. package/lib/esm/url.d.ts +9 -0
  60. package/lib/esm/url.js +80 -0
  61. package/lib/esm/url.js.map +1 -0
  62. package/package.json +72 -0
  63. package/src/array.ts +134 -0
  64. package/src/base64.ts +53 -0
  65. package/src/crypto.ts +281 -0
  66. package/src/date.ts +48 -0
  67. package/src/deep.ts +348 -0
  68. package/src/error.ts +7 -0
  69. package/src/hash.ts +20 -0
  70. package/src/index.ts +17 -0
  71. package/src/logger.ts +35 -0
  72. package/src/lru.ts +187 -0
  73. package/src/msg.ts +33 -0
  74. package/src/object.ts +43 -0
  75. package/src/package.ts +39 -0
  76. package/src/retry.ts +71 -0
  77. package/src/string.ts +338 -0
  78. package/src/subst.ts +41 -0
  79. package/src/time.ts +105 -0
  80. package/src/url.ts +92 -0
package/lib/esm/lru.js ADDED
@@ -0,0 +1,137 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { DEFAULT_CLOCK } from "zilla-util";
3
+ import { safeStringify } from "./string.js";
4
+ export class LRUCache {
5
+ maxSize;
6
+ maxAge;
7
+ cache;
8
+ clock;
9
+ touchOnGet;
10
+ logger;
11
+ constructor({ maxSize = 100, maxAge, clock = DEFAULT_CLOCK, touchOnGet = true, logger } = {}) {
12
+ if (maxSize <= 0)
13
+ throw new Error("maxSize must be positive");
14
+ this.maxSize = maxSize;
15
+ this.maxAge = maxAge;
16
+ this.cache = new Map();
17
+ this.clock = clock;
18
+ this.touchOnGet = touchOnGet;
19
+ this.logger = logger;
20
+ if (this.logger && this.logger.isTraceEnabled()) {
21
+ if (clock.constructor) {
22
+ this.logger.trace(`LRUCache.constructor now=${this.clock.now()} using clock=${clock.constructor}`);
23
+ }
24
+ else {
25
+ this.logger.trace(`LRUCache.constructor now=${this.clock.now()} using clock=${clock === DEFAULT_CLOCK ? "DEFAULT_CLOCK" : "custom-clock"}`);
26
+ }
27
+ }
28
+ }
29
+ get(key) {
30
+ if (this.logger && this.logger.isTraceEnabled()) {
31
+ this.logger.trace(`LRUCache.get(${key}) now=${this.clock.now()} starting`);
32
+ }
33
+ const entry = this.cache.get(key);
34
+ if (this.logger && this.logger.isTraceEnabled()) {
35
+ this.logger.trace(`LRUCache.get(${key}) now=${this.clock.now()} entry=${entry ? safeStringify(entry) : "undefined"}`);
36
+ }
37
+ if (!entry) {
38
+ return undefined;
39
+ }
40
+ if (this.maxAge !== undefined && this.clock.now() - entry.timestamp > this.maxAge) {
41
+ if (this.logger && this.logger.isTraceEnabled()) {
42
+ this.logger.trace(`LRUCache.get(${key}) now=${this.clock.now()} EXPIRED entry=${entry ? safeStringify(entry) : "undefined"}`);
43
+ }
44
+ this.cache.delete(key);
45
+ return undefined;
46
+ }
47
+ if (this.touchOnGet) {
48
+ if (this.logger && this.logger.isTraceEnabled()) {
49
+ this.logger.trace(`LRUCache.get(${key}) now=${this.clock.now()} TOUCH-ON-GET entry=${entry ? safeStringify(entry) : "undefined"}`);
50
+ }
51
+ this.cache.delete(key);
52
+ this.cache.set(key, { ...entry, timestamp: this.clock.now() });
53
+ }
54
+ if (this.logger && this.logger.isTraceEnabled()) {
55
+ this.logger.trace(`LRUCache.get(${key}) now=${this.clock.now()} RETURNING entry.value=${entry.value}`);
56
+ }
57
+ return entry.value;
58
+ }
59
+ set(key, value) {
60
+ if (this.logger && this.logger.isTraceEnabled()) {
61
+ this.logger.trace(`LRUCache.set(${key}) now=${this.clock.now()} starting`);
62
+ }
63
+ if (this.cache.has(key)) {
64
+ if (this.logger && this.logger.isTraceEnabled()) {
65
+ this.logger.trace(`LRUCache.set(${key}) now=${this.clock.now()} KEY FOUND DELETING`);
66
+ }
67
+ this.cache.delete(key);
68
+ }
69
+ else if (this.cache.size >= this.maxSize) {
70
+ if (this.logger && this.logger.isTraceEnabled()) {
71
+ this.logger.trace(`LRUCache.set(${key}) now=${this.clock.now()} this.cache.size=${this.cache.size} >= this.maxSize=${this.maxSize} EVICTING`);
72
+ }
73
+ this.evict();
74
+ }
75
+ if (this.logger && this.logger.isTraceEnabled()) {
76
+ this.logger.trace(`LRUCache.set(${key}) now=${this.clock.now()} SETTING value=${safeStringify(value)}`);
77
+ }
78
+ this.cache.set(key, { value, timestamp: this.clock.now() });
79
+ }
80
+ evict() {
81
+ if (this.logger && this.logger.isTraceEnabled()) {
82
+ this.logger.trace(`LRUCache.evict now=${this.clock.now()} starting`);
83
+ }
84
+ const oldestKey = this.cache.keys().next().value;
85
+ if (oldestKey !== undefined) {
86
+ if (this.logger && this.logger.isTraceEnabled()) {
87
+ this.logger.trace(`LRUCache.evict now=${this.clock.now()} DELETING oldestKey=${oldestKey}`);
88
+ }
89
+ this.cache.delete(oldestKey);
90
+ }
91
+ else {
92
+ if (this.logger && this.logger.isTraceEnabled()) {
93
+ this.logger.trace(`LRUCache.evict now=${this.clock.now()} NOTHING TO DELETE oldestKey=undefined`);
94
+ }
95
+ }
96
+ }
97
+ delete(key) {
98
+ if (this.logger && this.logger.isTraceEnabled()) {
99
+ this.logger.trace(`LRUCache.delete(${key}) now=${this.clock.now()} starting`);
100
+ }
101
+ this.cache.delete(key);
102
+ if (this.logger && this.logger.isTraceEnabled()) {
103
+ this.logger.trace(`LRUCache.delete(${key}) now=${this.clock.now()} finished`);
104
+ }
105
+ }
106
+ clear() {
107
+ if (this.logger && this.logger.isTraceEnabled()) {
108
+ this.logger.trace(`LRUCache.clear now=${this.clock.now()} starting`);
109
+ }
110
+ this.cache.clear();
111
+ if (this.logger && this.logger.isTraceEnabled()) {
112
+ this.logger.trace(`LRUCache.clear now=${this.clock.now()} finished`);
113
+ }
114
+ }
115
+ }
116
+ export function withLRUCache(fn, cacheOrConfig, keyFn) {
117
+ const cache = cacheOrConfig instanceof LRUCache ? cacheOrConfig : new LRUCache(cacheOrConfig);
118
+ const defaultKeyFn = (...args) => JSON.stringify(args, (key, value) => (typeof value === "function" ? value.toString() : value));
119
+ return (...args) => {
120
+ const key = (keyFn ?? defaultKeyFn)(...args);
121
+ const cachedValue = cache.get(key);
122
+ if (cachedValue !== undefined)
123
+ return cachedValue;
124
+ const result = fn(...args);
125
+ if (result instanceof Promise) {
126
+ return result.then((resolvedResult) => {
127
+ cache.set(key, resolvedResult);
128
+ return resolvedResult;
129
+ });
130
+ }
131
+ else {
132
+ cache.set(key, result);
133
+ return result;
134
+ }
135
+ };
136
+ }
137
+ //# sourceMappingURL=lru.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lru.js","sourceRoot":"","sources":["../../src/lru.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,OAAO,EAAc,aAAa,EAAE,MAAM,YAAY,CAAC;AAEvD,OAAO,EAAC,aAAa,EAAC,MAAM,aAAa,CAAC;AAU1C,MAAM,OAAO,QAAQ;IACA,OAAO,CAAS;IAChB,MAAM,CAAU;IACzB,KAAK,CAA0C;IAC/C,KAAK,CAAa;IAClB,UAAU,CAAW;IACrB,MAAM,CAAiB;IAE/B,YAAY,EAAE,OAAO,GAAG,GAAG,EAAE,MAAM,EAAE,KAAK,GAAG,aAAa,EAAE,UAAU,GAAG,IAAI,EAAE,MAAM,KAAqB,EAAE;QACxG,IAAI,OAAO,IAAI,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;QAC9D,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,MAAM,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,CAAC,IAAI,QAAQ,CAAY,aAAa,CAAC,CAAC;IAEzG,MAAM,YAAY,GAAG,CAAC,GAAG,IAAW,EAAU,EAAE,CAC5C,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;IAEnG,OAAO,CAAC,GAAG,IAAW,EAAkB,EAAE;QACtC,MAAM,GAAG,GAAG,CAAC,KAAK,IAAI,YAAY,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;QAC7C,MAAM,WAAW,GAAG,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACnC,IAAI,WAAW,KAAK,SAAS;YAAE,OAAO,WAAW,CAAC;QAElD,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;QAC3B,IAAI,MAAM,YAAY,OAAO,EAAE,CAAC;YAC5B,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,cAAc,EAAE,EAAE;gBAClC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;gBAC/B,OAAO,cAAc,CAAC;YAC1B,CAAC,CAAC,CAAC;QACP,CAAC;aAAM,CAAC;YACJ,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;YACvB,OAAO,MAAM,CAAC;QAClB,CAAC;IACL,CAAC,CAAC;AACN,CAAC"}
@@ -0,0 +1,29 @@
1
+ export declare enum ZillaMsgTransportType {
2
+ email = "email",
3
+ sms = "sms"
4
+ }
5
+ export declare const MESSAGE_TYPE_VALUES: ZillaMsgTransportType[];
6
+ export type ZillaMsgRecipient = {
7
+ name?: string;
8
+ destination: string;
9
+ };
10
+ export type ZillaMessage = {
11
+ transport: string;
12
+ type: ZillaMsgTransportType;
13
+ via: string;
14
+ template: string;
15
+ locale: string;
16
+ from: string;
17
+ to: string;
18
+ messages: Record<string, string>;
19
+ ctime: number;
20
+ };
21
+ export type ZillaMsgTransport = {
22
+ name: string;
23
+ type: ZillaMsgTransportType;
24
+ sender: string;
25
+ via: () => string;
26
+ templates: string[];
27
+ formatTo: (recipient: ZillaMsgRecipient) => string;
28
+ send: (recipient: ZillaMsgRecipient, rendered: Record<string, string>) => Promise<unknown>;
29
+ };
package/lib/esm/msg.js ADDED
@@ -0,0 +1,7 @@
1
+ export var ZillaMsgTransportType;
2
+ (function (ZillaMsgTransportType) {
3
+ ZillaMsgTransportType["email"] = "email";
4
+ ZillaMsgTransportType["sms"] = "sms";
5
+ })(ZillaMsgTransportType || (ZillaMsgTransportType = {}));
6
+ export const MESSAGE_TYPE_VALUES = Object.values(ZillaMsgTransportType);
7
+ //# sourceMappingURL=msg.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"msg.js","sourceRoot":"","sources":["../../src/msg.ts"],"names":[],"mappings":"AAAA,MAAM,CAAN,IAAY,qBAGX;AAHD,WAAY,qBAAqB;IAC7B,wCAAe,CAAA;IACf,oCAAW,CAAA;AACf,CAAC,EAHW,qBAAqB,KAArB,qBAAqB,QAGhC;AAED,MAAM,CAAC,MAAM,mBAAmB,GAA4B,MAAM,CAAC,MAAM,CAAC,qBAAqB,CAAC,CAAC"}
@@ -0,0 +1,8 @@
1
+ import { SortedSet } from "./array.js";
2
+ export type EmptyObjectType = Record<string, never>;
3
+ export declare const keysByValue: <K extends string, V>(obj: Record<K, V>, val: V) => K[];
4
+ export declare const firstKeyByValue: <K extends string, V>(obj: Record<K, V>, val: V) => K | undefined;
5
+ export declare const enumRecord: <E extends string | number | symbol, V>(e: Record<string, E>, init: V | ((e?: E) => V)) => Record<E, V>;
6
+ export declare const setsToArrays: <K extends string, V>(input: Record<K, SortedSet<V>>) => Record<K, V[]>;
7
+ export declare const findDuplicates: <T>(items: T[], field: keyof T) => string[];
8
+ export declare const reverseEnum: <E extends Record<string, string>>(enumObj: E) => Record<string, string>;
@@ -0,0 +1,31 @@
1
+ export const keysByValue = (obj, val) => {
2
+ return Object.keys(obj).filter((k) => obj[k] === val);
3
+ };
4
+ export const firstKeyByValue = (obj, val) => {
5
+ return Object.keys(obj).find((k) => obj[k] === val);
6
+ };
7
+ export const enumRecord = (e, init) => {
8
+ const o = {};
9
+ for (const k of Object.values(e)) {
10
+ o[k] = typeof init === "function" ? init(k) : init;
11
+ }
12
+ return o;
13
+ };
14
+ export const setsToArrays = (input) => Object.fromEntries(Object.entries(input).map(([k, set]) => [k, set.toArray()]));
15
+ export const findDuplicates = (items, field) => {
16
+ const counts = new Map();
17
+ for (const item of items) {
18
+ const key = String(item[field]);
19
+ counts.set(key, (counts.get(key) ?? 0) + 1);
20
+ }
21
+ return [...counts].filter(([, n]) => n > 1).map(([k]) => k);
22
+ };
23
+ export const reverseEnum = (enumObj) => {
24
+ const rev = {};
25
+ Object.keys(enumObj).forEach((key) => {
26
+ const value = enumObj[key];
27
+ rev[value] = key;
28
+ });
29
+ return rev;
30
+ };
31
+ //# sourceMappingURL=object.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"object.js","sourceRoot":"","sources":["../../src/object.ts"],"names":[],"mappings":"AAIA,MAAM,CAAC,MAAM,WAAW,GAAG,CAAsB,GAAiB,EAAE,GAAM,EAAO,EAAE;IAC/E,OAAQ,MAAM,CAAC,IAAI,CAAC,GAAG,CAAS,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC;AACnE,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,eAAe,GAAG,CAAsB,GAAiB,EAAE,GAAM,EAAiB,EAAE;IAC7F,OAAQ,MAAM,CAAC,IAAI,CAAC,GAAG,CAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC;AACj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,CAAC,CAAC;AAChE,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,WAAW,GAAG,CAAmC,OAAU,EAA0B,EAAE;IAChG,MAAM,GAAG,GAA2B,EAAE,CAAC;IACtC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAoB,CAAC,OAAO,CAAC,CAAC,GAAY,EAAQ,EAAE;QACpE,MAAM,KAAK,GAAW,OAAO,CAAC,GAAG,CAAC,CAAC;QACnC,GAAG,CAAC,KAAK,CAAC,GAAG,GAAa,CAAC;IAC/B,CAAC,CAAC,CAAC;IACH,OAAO,GAAG,CAAC;AACf,CAAC,CAAC"}
@@ -0,0 +1,2 @@
1
+ import { GenericLogger } from "./logger.js";
2
+ export declare const packageVersion: (importMetaUrl?: string, logger?: GenericLogger) => Promise<string | undefined>;
@@ -0,0 +1,38 @@
1
+ const packageJsonUrl = async (startUrl) => {
2
+ let currentUrl = new URL(startUrl);
3
+ while (true) {
4
+ const packageUrl = new URL("package.json", currentUrl);
5
+ try {
6
+ const packageJson = await import(packageUrl.toString(), { assert: { type: "json" } });
7
+ if (packageJson)
8
+ return packageUrl; // Found package.json
9
+ }
10
+ catch {
11
+ const parentUrl = new URL("..", currentUrl);
12
+ if (parentUrl.toString() === currentUrl.toString())
13
+ break; // Stop if we reach the root
14
+ currentUrl = parentUrl; // Move up one level
15
+ }
16
+ }
17
+ return null; // Not found
18
+ };
19
+ export const packageVersion = async (importMetaUrl = import.meta.url, logger) => {
20
+ try {
21
+ const packageUrl = await packageJsonUrl(new URL(importMetaUrl));
22
+ if (!packageUrl)
23
+ throw new Error("package.json not found");
24
+ const packageJson = await import(packageUrl.toString(), { assert: { type: "json" } });
25
+ return packageJson.version;
26
+ }
27
+ catch (e) {
28
+ const msg = `packageVersion importMetaUrl=${importMetaUrl} error determining package version: error=${e}`;
29
+ if (logger) {
30
+ logger.error(msg, e);
31
+ }
32
+ else {
33
+ console.error(msg);
34
+ }
35
+ return undefined;
36
+ }
37
+ };
38
+ //# sourceMappingUR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AAI,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC;QACtF,OAAO,WAAW,CAAC,OAAO,CAAC;IAC/B,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACT,MAAM,GAAG,GAAG,gCAAgC,aAAa,6CAA6C,CAAC,EAAE,CAAC;QAC1G,IAAI,MAAM,EAAE,CAAC;YACT,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;QACzB,CAAC;aAAM,CAAC;YACJ,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACvB,CAAC;QACD,OAAO,SAAS,CAAC;IACrB,CAAC;AACL,CAAC,CAAC"}
@@ -0,0 +1 @@
1
+ export declare const shortStringMatch: (regex: RegExp) => string;
@@ -0,0 +1,22 @@
1
+ export const shortStringMatch = (regex) => {
2
+ if (regex.test(""))
3
+ return "";
4
+ const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
5
+ for (let length = 1; length <= 3; length++) {
6
+ const stack = [{ text: "", index: 0 }];
7
+ while (stack.length) {
8
+ const { text, index } = stack.pop();
9
+ if (index === length) {
10
+ if (regex.test(text))
11
+ return text;
12
+ }
13
+ else {
14
+ for (const c of chars) {
15
+ stack.push({ text: text + c, index: index + 1 });
16
+ }
17
+ }
18
+ }
19
+ }
20
+ throw new Error("No short match found up to length 3");
21
+ };
22
+ //# sourceMappingURL=regex.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"regex.js","sourceRoot":"","sources":["../../src/regex.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,KAAa,EAAU,EAAE;IACtD,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;QAAE,OAAO,EAAE,CAAC;IAC9B,MAAM,KAAK,GAAG,gEAAgE,CAAC;IAC/E,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC;QACzC,MAAM,KAAK,GAAsC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;QAC1E,OAAO,KAAK,CAAC,MAAM,EAAE,CAAC;YAClB,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,KAAK,CAAC,GAAG,EAAqC,CAAC;YACvE,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;gBACnB,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;oBAAE,OAAO,IAAI,CAAC;YACtC,CAAC;iBAAM,CAAC;gBACJ,KAAK,MAAM,CAAC,IAAI,KAAK,EAAE,CAAC;oBACpB,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,GAAG,CAAC,EAAE,KAAK,EAAE,KAAK,GAAG,CAAC,EAAE,CAAC,CAAC;gBACrD,CAAC;YACL,CAAC;QACL,CAAC;IACL,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;AAC3D,CAAC,CAAC"}
@@ -0,0 +1,13 @@
1
+ import { GenericLogger } from "./logger.js";
2
+ export type RetryOptions = {
3
+ maxAttempts?: number;
4
+ backoffBaseMillis?: number;
5
+ backoffMultiplier?: number;
6
+ canRetry?: (e: Error) => Promise<boolean> | boolean;
7
+ };
8
+ export declare const DEFAULT_RETRY_MAX_ATTEMPTS = 3;
9
+ export declare const DEFAULT_RETRY_BACKOFF_BASE_MILLIS = 250;
10
+ export declare const DEFAULT_RETRY_BACKOFF_MULTIPLIER = 3;
11
+ export declare const DEFAULT_RETRY_CAN_RETRY_FUNC: () => boolean;
12
+ export declare const DEFAULT_RETRY_OPTS: RetryOptions;
13
+ export declare const retry: <T>(fn: () => Promise<T>, opts?: RetryOptions, logger?: GenericLogger, action?: string) => Promise<T>;
@@ -0,0 +1,57 @@
1
+ import { sleep } from "./time.js";
2
+ import { safeStringify } from "./string.js";
3
+ export const DEFAULT_RETRY_MAX_ATTEMPTS = 3;
4
+ export const DEFAULT_RETRY_BACKOFF_BASE_MILLIS = 250;
5
+ export const DEFAULT_RETRY_BACKOFF_MULTIPLIER = 3;
6
+ export const DEFAULT_RETRY_CAN_RETRY_FUNC = () => true;
7
+ export const DEFAULT_RETRY_OPTS = {
8
+ maxAttempts: DEFAULT_RETRY_MAX_ATTEMPTS,
9
+ backoffBaseMillis: DEFAULT_RETRY_BACKOFF_BASE_MILLIS,
10
+ backoffMultiplier: DEFAULT_RETRY_BACKOFF_MULTIPLIER,
11
+ canRetry: DEFAULT_RETRY_CAN_RETRY_FUNC,
12
+ };
13
+ export const retry = async (fn, opts, logger, action) => {
14
+ const maxAttempts = opts?.maxAttempts || DEFAULT_RETRY_MAX_ATTEMPTS;
15
+ const backoffBaseMillis = opts?.backoffBaseMillis || DEFAULT_RETRY_BACKOFF_BASE_MILLIS;
16
+ const backoffMultiplier = opts?.backoffMultiplier || DEFAULT_RETRY_BACKOFF_MULTIPLIER;
17
+ const canRetry = opts?.canRetry || DEFAULT_RETRY_CAN_RETRY_FUNC;
18
+ const prefix = logger ? (action ? `@@@ retry[${action}]:` : "retry:") : "";
19
+ let backoffTime = backoffBaseMillis;
20
+ let error;
21
+ if (logger && logger.isDebugEnabled()) {
22
+ logger.debug(`${prefix} starting with opts=${opts ? safeStringify(opts) : "undefined"}`);
23
+ }
24
+ for (let i = 0; i < maxAttempts; i++) {
25
+ const iPrefix = `${prefix} [${i + 1}/${maxAttempts}]:`;
26
+ if (i > 0) {
27
+ if (logger && logger.isDebugEnabled()) {
28
+ logger.debug(`${iPrefix} waiting for ${backoffTime} before retrying`);
29
+ }
30
+ await sleep(backoffTime);
31
+ backoffTime = Math.floor(backoffTime * backoffMultiplier);
32
+ }
33
+ try {
34
+ if (logger && logger.isDebugEnabled()) {
35
+ logger.debug(`${iPrefix} calling function`);
36
+ }
37
+ return await fn();
38
+ }
39
+ catch (e) {
40
+ error = e;
41
+ if (!(await canRetry(e))) {
42
+ if (logger && logger.isDebugEnabled()) {
43
+ logger.debug(`${iPrefix} function threw error and canRetry=false, throwing e=${e}`, e);
44
+ }
45
+ throw e;
46
+ }
47
+ if (logger && logger.isDebugEnabled()) {
48
+ logger.debug(`${iPrefix} function threw error=${e} and canRetry=true, continuing`, e);
49
+ }
50
+ }
51
+ }
52
+ if (logger && logger.isDebugEnabled()) {
53
+ logger.debug(`${prefix} maxAttempts exceeded, throwing most recent error=${error}`, error);
54
+ }
55
+ throw error;
56
+ };
57
+ //# sourceMappingURL=retry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/retry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAElC,OAAO,EAAC,aAAa,EAAC,MAAM,aAAa,CAAC;AAS1C,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AAC5C,MAAM,CAAC,MAAM,iCAAiC,GAAG,GAAG,CAAC;AACrD,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAClD,MAAM,CAAC,MAAM,4BAA4B,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC;AAEvD,MAAM,CAAC,MAAM,kBAAkB,GAAiB;IAC5C,WAAW,EAAE,0BAA0B;IACvC,iBAAiB,EAAE,iCAAiC;IACpD,iBAAiB,EAAE,gCAAgC;IACnD,QAAQ,EAAE,4BAA4B;CACzC,CAAC;AAEF,MAAM,CAAC,MAAM,KAAK,GAAG,KAAK,EACtB,EAAoB,EACpB,IAAmB,EACnB,MAAsB,EACtB,MAAe,EACL,EAAE;IACZ,MAAM,WAAW,GAAG,IAAI,EAAE,WAAW,IAAI,0BAA0B,CAAC;IACpE,MAAM,iBAAiB,GAAG,IAAI,EAAE,iBAAiB,IAAI,iCAAiC,CAAC;IACvF,MAAM,iBAAiB,GAAG,IAAI,EAAE,iBAAiB,IAAI,gCAAgC,CAAC;IACtF,MAAM,QAAQ,GAAG,IAAI,EAAE,QAAQ,I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M,QAAQ,CAAC,CAAU,CAAC,CAAC,EAAE,CAAC;gBAChC,IAAI,MAAM,IAAI,MAAM,CAAC,cAAc,EAAE,EAAE,CAAC;oBACpC,MAAM,CAAC,KAAK,CAAC,GAAG,OAAO,wDAAwD,CAAC,EAAE,EAAE,CAAU,CAAC,CAAC;gBACpG,CAAC;gBACD,MAAM,CAAC,CAAC;YACZ,CAAC;YACD,IAAI,MAAM,IAAI,MAAM,CAAC,cAAc,EAAE,EAAE,CAAC;gBACpC,MAAM,CAAC,KAAK,CAAC,GAAG,OAAO,yBAAyB,CAAC,gCAAgC,EAAE,CAAU,CAAC,CAAC;YACnG,CAAC;QACL,CAAC;IACL,CAAC;IACD,IAAI,MAAM,IAAI,MAAM,CAAC,cAAc,EAAE,EAAE,CAAC;QACpC,MAAM,CAAC,KAAK,CAAC,GAAG,MAAM,qDAAqD,KAAK,EAAE,EAAE,KAAc,CAAC,CAAC;IACxG,CAAC;IACD,MAAM,KAAK,CAAC;AAChB,CAAC,CAAC"}
@@ -0,0 +1,50 @@
1
+ export default Sha256;
2
+ /**
3
+ * SHA-256 hash function reference implementation.
4
+ *
5
+ * This is an annotated direct implementation of FIPS 180-4, without any optimisations. It is
6
+ * intended to aid understanding of the algorithm rather than for production use.
7
+ *
8
+ * While it could be used where performance is not critical, I would recommend using the ‘Web
9
+ * Cryptography API’ (developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest) for the browser,
10
+ * or the ‘crypto’ library (nodejs.org/api/crypto.html#crypto_class_hash) in Node.js.
11
+ *
12
+ * See csrc.nist.gov/groups/ST/toolkit/secure_hashing.html
13
+ * csrc.nist.gov/groups/ST/toolkit/examples.html
14
+ */
15
+ declare class Sha256 {
16
+ /**
17
+ * Generates SHA-256 hash of string.
18
+ *
19
+ * @param {string} msg - (Unicode) string to be hashed.
20
+ * @param {Object} [options]
21
+ * @param {string} [options.msgFormat=string] - Message format: 'string' for JavaScript string
22
+ * (gets converted to UTF-8 for hashing); 'hex-bytes' for string of hex bytes ('616263' ≡ 'abc') .
23
+ * @param {string} [options.outFormat=hex] - Output format: 'hex' for string of contiguous
24
+ * hex bytes; 'hex-w' for grouping hex bytes into groups of (4 byte / 8 character) words.
25
+ * @returns {string} Hash of msg as hex character string.
26
+ *
27
+ * @example
28
+ * import Sha256 from './sha256.js';
29
+ * const hash = Sha256.hash('abc'); // 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'
30
+ */
31
+ static hash(msg: string, options?: {
32
+ msgFormat?: string | undefined;
33
+ outFormat?: string | undefined;
34
+ }): string;
35
+ /**
36
+ * Rotates right (circular right shift) value x by n positions [§3.2.4].
37
+ * @private
38
+ */
39
+ private static ROTR;
40
+ /**
41
+ * Logical functions [§4.1.2].
42
+ * @private
43
+ */
44
+ private static Σ0;
45
+ static Σ1(x: any): number;
46
+ static σ0(x: any): number;
47
+ static σ1(x: any): number;
48
+ static Ch(x: any, y: any, z: any): number;
49
+ static Maj(x: any, y: any, z: any): number;
50
+ }
@@ -0,0 +1,181 @@
1
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
2
+ /* SHA-256 (FIPS 180-4) implementation in JavaScript (c) Chris Veness 2002-2019 */
3
+ /* MIT Licence */
4
+ /* www.movable-type.co.uk/scripts/sha256.html */
5
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
6
+ /**
7
+ * SHA-256 hash function reference implementation.
8
+ *
9
+ * This is an annotated direct implementation of FIPS 180-4, without any optimisations. It is
10
+ * intended to aid understanding of the algorithm rather than for production use.
11
+ *
12
+ * While it could be used where performance is not critical, I would recommend using the ‘Web
13
+ * Cryptography API’ (developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest) for the browser,
14
+ * or the ‘crypto’ library (nodejs.org/api/crypto.html#crypto_class_hash) in Node.js.
15
+ *
16
+ * See csrc.nist.gov/groups/ST/toolkit/secure_hashing.html
17
+ * csrc.nist.gov/groups/ST/toolkit/examples.html
18
+ */
19
+ class Sha256 {
20
+ /**
21
+ * Generates SHA-256 hash of string.
22
+ *
23
+ * @param {string} msg - (Unicode) string to be hashed.
24
+ * @param {Object} [options]
25
+ * @param {string} [options.msgFormat=string] - Message format: 'string' for JavaScript string
26
+ * (gets converted to UTF-8 for hashing); 'hex-bytes' for string of hex bytes ('616263' ≡ 'abc') .
27
+ * @param {string} [options.outFormat=hex] - Output format: 'hex' for string of contiguous
28
+ * hex bytes; 'hex-w' for grouping hex bytes into groups of (4 byte / 8 character) words.
29
+ * @returns {string} Hash of msg as hex character string.
30
+ *
31
+ * @example
32
+ * import Sha256 from './sha256.js';
33
+ * const hash = Sha256.hash('abc'); // 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'
34
+ */
35
+ static hash(msg, options) {
36
+ const defaults = { msgFormat: "string", outFormat: "hex" };
37
+ const opt = Object.assign(defaults, options);
38
+ // note use throughout this routine of 'n >>> 0' to coerce Number 'n' to unsigned 32-bit integer
39
+ switch (opt.msgFormat) {
40
+ default: // default is to convert string to UTF-8, as SHA only deals with byte-streams
41
+ case "string":
42
+ msg = utf8Encode(msg);
43
+ break;
44
+ case "hex-bytes":
45
+ msg = hexBytesToString(msg);
46
+ break; // mostly for running tests
47
+ }
48
+ // constants [§4.2.2]
49
+ const K = [
50
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98,
51
+ 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
52
+ 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8,
53
+ 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
54
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
55
+ 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
56
+ 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
57
+ 0xc67178f2,
58
+ ];
59
+ // initial hash value [§5.3.3]
60
+ const H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
61
+ // PREPROCESSING [§6.2.1]
62
+ msg += String.fromCharCode(0x80); // add trailing '1' bit (+ 0's padding) to string [§5.1.1]
63
+ // convert string msg into 512-bit blocks (array of 16 32-bit integers) [§5.2.1]
64
+ const l = msg.length / 4 + 2; // length (in 32-bit integers) of msg + ‘1’ + appended length
65
+ const N = Math.ceil(l / 16); // number of 16-integer (512-bit) blocks required to hold 'l' ints
66
+ const M = new Array(N); // message M is N×16 array of 32-bit integers
67
+ for (let i = 0; i < N; i++) {
68
+ M[i] = new Array(16);
69
+ for (let j = 0; j < 16; j++) {
70
+ // encode 4 chars per integer (64 per block), big-endian encoding
71
+ M[i][j] =
72
+ (msg.charCodeAt(i * 64 + j * 4 + 0) << 24) |
73
+ (msg.charCodeAt(i * 64 + j * 4 + 1) << 16) |
74
+ (msg.charCodeAt(i * 64 + j * 4 + 2) << 8) |
75
+ (msg.charCodeAt(i * 64 + j * 4 + 3) << 0);
76
+ } // note running off the end of msg is ok 'cos bitwise ops on NaN return 0
77
+ }
78
+ // add length (in bits) into final pair of 32-bit integers (big-endian) [§5.1.1]
79
+ // note: most significant word would be (len-1)*8 >>> 32, but since JS converts
80
+ // bitwise-op args to 32 bits, we need to simulate this by arithmetic operators
81
+ const lenHi = ((msg.length - 1) * 8) / Math.pow(2, 32);
82
+ const lenLo = ((msg.length - 1) * 8) >>> 0;
83
+ M[N - 1][14] = Math.floor(lenHi);
84
+ M[N - 1][15] = lenLo;
85
+ // HASH COMPUTATION [§6.2.2]
86
+ for (let i = 0; i < N; i++) {
87
+ const W = new Array(64);
88
+ // 1 - prepare message schedule 'W'
89
+ for (let t = 0; t < 16; t++)
90
+ W[t] = M[i][t];
91
+ for (let t = 16; t < 64; t++) {
92
+ W[t] = (Sha256.σ1(W[t - 2]) + W[t - 7] + Sha256.σ0(W[t - 15]) + W[t - 16]) >>> 0;
93
+ }
94
+ // 2 - initialise working variables a, b, c, d, e, f, g, h with previous hash value
95
+ let a = H[0], b = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];
96
+ // 3 - main loop (note '>>> 0' for 'addition modulo 2^32')
97
+ for (let t = 0; t < 64; t++) {
98
+ const T1 = h + Sha256.Σ1(e) + Sha256.Ch(e, f, g) + K[t] + W[t];
99
+ const T2 = Sha256.Σ0(a) + Sha256.Maj(a, b, c);
100
+ h = g;
101
+ g = f;
102
+ f = e;
103
+ e = (d + T1) >>> 0;
104
+ d = c;
105
+ c = b;
106
+ b = a;
107
+ a = (T1 + T2) >>> 0;
108
+ }
109
+ // 4 - compute the new intermediate hash value (note '>>> 0' for 'addition modulo 2^32')
110
+ H[0] = (H[0] + a) >>> 0;
111
+ H[1] = (H[1] + b) >>> 0;
112
+ H[2] = (H[2] + c) >>> 0;
113
+ H[3] = (H[3] + d) >>> 0;
114
+ H[4] = (H[4] + e) >>> 0;
115
+ H[5] = (H[5] + f) >>> 0;
116
+ H[6] = (H[6] + g) >>> 0;
117
+ H[7] = (H[7] + h) >>> 0;
118
+ }
119
+ // convert H0..H7 to hex strings (with leading zeros)
120
+ for (let h = 0; h < H.length; h++)
121
+ H[h] = ("00000000" + H[h].toString(16)).slice(-8);
122
+ // concatenate H0..H7, with separator if required
123
+ const separator = opt.outFormat == "hex-w" ? " " : "";
124
+ return H.join(separator);
125
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
126
+ function utf8Encode(str) {
127
+ try {
128
+ return new TextEncoder()
129
+ .encode(str, "utf-8")
130
+ .reduce((prev, curr) => prev + String.fromCharCode(curr), "");
131
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
132
+ }
133
+ catch (e) {
134
+ // no TextEncoder available?
135
+ return unescape(encodeURIComponent(str)); // monsur.hossa.in/2012/07/20/utf-8-in-javascript.html
136
+ }
137
+ }
138
+ function hexBytesToString(hexStr) {
139
+ // convert string of hex numbers to a string of chars (eg '616263' -> 'abc').
140
+ const str = hexStr.replace(" ", ""); // allow space-separated groups
141
+ return str == ""
142
+ ? ""
143
+ : str
144
+ .match(/.{2}/g)
145
+ .map((byte) => String.fromCharCode(parseInt(byte, 16)))
146
+ .join("");
147
+ }
148
+ }
149
+ /**
150
+ * Rotates right (circular right shift) value x by n positions [§3.2.4].
151
+ * @private
152
+ */
153
+ static ROTR(n, x) {
154
+ return (x >>> n) | (x << (32 - n));
155
+ }
156
+ /**
157
+ * Logical functions [§4.1.2].
158
+ * @private
159
+ */
160
+ static Σ0(x) {
161
+ return Sha256.ROTR(2, x) ^ Sha256.ROTR(13, x) ^ Sha256.ROTR(22, x);
162
+ }
163
+ static Σ1(x) {
164
+ return Sha256.ROTR(6, x) ^ Sha256.ROTR(11, x) ^ Sha256.ROTR(25, x);
165
+ }
166
+ static σ0(x) {
167
+ return Sha256.ROTR(7, x) ^ Sha256.ROTR(18, x) ^ (x >>> 3);
168
+ }
169
+ static σ1(x) {
170
+ return Sha256.ROTR(17, x) ^ Sha256.ROTR(19, x) ^ (x >>> 10);
171
+ }
172
+ static Ch(x, y, z) {
173
+ return (x & y) ^ (~x & z);
174
+ } // 'choice'
175
+ static Maj(x, y, z) {
176
+ return (x & y) ^ (x & z) ^ (y & z);
177
+ } // 'majority'
178
+ }
179
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
180
+ export default Sha256;
181
+ //# sourceMappingURL=sha256.js.map