@adviser/cement 0.2.5 → 0.2.7

Sign up to get free protection for your applications and to get access to all the features.
package/index.d.ts CHANGED
@@ -32,6 +32,46 @@ declare class ResultError<T extends Error> extends Result<never, T> {
32
32
  }
33
33
  type WithoutResult<T> = T extends Result<infer U> ? U : T;
34
34
 
35
+ type NullOrUndef = null | undefined;
36
+ declare class BuildURI {
37
+ private _url;
38
+ constructor(url: URL);
39
+ hostname(h: string): this;
40
+ password(p: string): this;
41
+ port(p: string): this;
42
+ username(u: string): this;
43
+ search(s: string): this;
44
+ protocol(p: string): this;
45
+ pathname(p: string): this;
46
+ hash(h: string): this;
47
+ host(h: string): this;
48
+ delParam(key: string): this;
49
+ setParam(key: string, str: string): this;
50
+ toString(): string;
51
+ build(): URI;
52
+ }
53
+ type CoerceURI = string | URL | URI | NullOrUndef;
54
+ declare class URI {
55
+ static from(strURLUri: CoerceURI, defaultProtocol?: string): URI;
56
+ readonly _url: URL;
57
+ private constructor();
58
+ build(): BuildURI;
59
+ get hostname(): string;
60
+ get password(): string;
61
+ get port(): string;
62
+ get username(): string;
63
+ get search(): string;
64
+ get protocol(): string;
65
+ get pathname(): string;
66
+ get hash(): string;
67
+ get host(): string;
68
+ hasParam(key: string): boolean;
69
+ getParam(key: string): string | undefined;
70
+ clone(): URI;
71
+ asURL(): URL;
72
+ toString(): string;
73
+ }
74
+
35
75
  declare enum Level {
36
76
  WARN = "warn",
37
77
  DEBUG = "debug",
@@ -46,9 +86,17 @@ declare class LogValue {
46
86
  value(): Serialized;
47
87
  toJSON(): Serialized;
48
88
  }
49
- type LogSerializable = Record<string, LogValue>;
89
+ type LogSerializable = Record<string, LogValue | Promise<LogValue>>;
50
90
  declare function removeSelfRef(): (key: unknown, val: unknown) => unknown;
91
+ declare function asyncLogValue(val: () => Promise<Serialized>): Promise<LogValue>;
51
92
  declare function logValue(val: Serialized | FnSerialized | LogSerializable | undefined | null): LogValue;
93
+ interface Sized {
94
+ size: number;
95
+ }
96
+ interface Lengthed {
97
+ length: number;
98
+ }
99
+ type SizeOrLength = Sized | Lengthed;
52
100
  interface LoggerInterface<R> {
53
101
  Module(key: string): R;
54
102
  EnableLevel(level: Level, ...modules: string[]): R;
@@ -58,10 +106,9 @@ interface LoggerInterface<R> {
58
106
  toString: () => string;
59
107
  } | FnSerialized): R;
60
108
  Result<T>(key: string, res: Result<T>): R;
61
- Url(url: URL, key?: string): R;
62
- Len(value: object | {
63
- length: number;
64
- } | string | undefined | null, key?: string): R;
109
+ Url(url: URL | URI | string, key?: string): R;
110
+ Len(value: unknown, key?: string): R;
111
+ Hash(value: unknown, key?: string): R;
65
112
  Str(key: string, value?: string): R;
66
113
  Error(): R;
67
114
  Warn(): R;
@@ -146,7 +193,8 @@ declare class LoggerImpl implements Logger {
146
193
  Bool(key: string, value: unknown): Logger;
147
194
  Result<T>(key: string, res: Result<T, Error>): Logger;
148
195
  Len(value: unknown, key?: string): Logger;
149
- Url(url: URL, key?: string): Logger;
196
+ Hash(value: unknown, key?: string): Logger;
197
+ Url(url: URL | URI | string, key?: string): Logger;
150
198
  Str(key: string, value?: string): Logger;
151
199
  Any(key: string, value?: string | number | boolean | LogSerializable): Logger;
152
200
  Dur(key: string, nsec: number): Logger;
@@ -266,4 +314,86 @@ declare class KeyedResolvSeq<T, K = string> extends Keyed<ResolveSeq<T, K>, K> {
266
314
  constructor();
267
315
  }
268
316
 
269
- export { type AsError, type FnSerialized, Future, IsLogger, Keyed, KeyedResolvOnce, KeyedResolvSeq, Level, type LevelHandler, LevelHandlerImpl, LogCollector, type LogSerializable, LogValue, LogWriter$1 as LogWriter, type Logger, LoggerImpl, type LoggerImplParams, type LoggerInterface, MockLogger, type MockLoggerReturn, None, Option, ResolveOnce, ResolveSeq, Result, ResultError, ResultOK, type Serialized, Some, SysAbstraction, type WithLogger, type WithoutOption, type WithoutResult, logValue, removeSelfRef };
317
+ interface Runtime {
318
+ isNodeIsh: boolean;
319
+ isBrowser: boolean;
320
+ isDeno: boolean;
321
+ isReactNative: boolean;
322
+ }
323
+ declare function runtimeFn(): Runtime;
324
+
325
+ interface CTJsonWebKey {
326
+ alg?: string;
327
+ crv?: string;
328
+ d?: string;
329
+ dp?: string;
330
+ dq?: string;
331
+ e?: string;
332
+ ext?: boolean;
333
+ k?: string;
334
+ key_ops?: string[];
335
+ kty?: string;
336
+ n?: string;
337
+ oth?: RsaOtherPrimesInfo[];
338
+ p?: string;
339
+ q?: string;
340
+ qi?: string;
341
+ use?: string;
342
+ x?: string;
343
+ y?: string;
344
+ }
345
+ type CTKeyFormat = "jwk" | "pkcs8" | "raw" | "spki";
346
+ type CTKeyUsage = "decrypt" | "deriveBits" | "deriveKey" | "encrypt" | "sign" | "unwrapKey" | "verify" | "wrapKey";
347
+ interface CTAlgorithm {
348
+ name: string;
349
+ }
350
+ type CTAlgorithmIdentifier = CTAlgorithm | string;
351
+ interface CTRsaHashedImportParams extends CTAlgorithm {
352
+ hash: CTAlgorithmIdentifier;
353
+ }
354
+ type CTNamedCurve = string;
355
+ interface CTEcKeyImportParams extends CTAlgorithm {
356
+ namedCurve: CTNamedCurve;
357
+ }
358
+ interface CTHmacImportParams extends CTAlgorithm {
359
+ hash: CTAlgorithmIdentifier;
360
+ length?: number;
361
+ }
362
+ interface CTAesKeyAlgorithm extends CTAlgorithm {
363
+ length: number;
364
+ }
365
+ type CTKeyType = "private" | "public" | "secret";
366
+ interface CTCryptoKey {
367
+ readonly algorithm: CTAlgorithm;
368
+ readonly extractable: boolean;
369
+ readonly type: CTKeyType;
370
+ readonly usages: CTKeyUsage[];
371
+ }
372
+ interface CTArrayBufferTypes {
373
+ ArrayBuffer: ArrayBuffer;
374
+ }
375
+ type CTArrayBufferLike = CTArrayBufferTypes[keyof CTArrayBufferTypes];
376
+ interface CTArrayBufferView {
377
+ buffer: CTArrayBufferLike;
378
+ byteLength: number;
379
+ byteOffset: number;
380
+ }
381
+ type CTBufferSource = CTArrayBufferView | ArrayBuffer;
382
+ interface CryptoRuntime {
383
+ importKey(format: CTKeyFormat, keyData: CTJsonWebKey | CTBufferSource, algorithm: CTAlgorithmIdentifier | CTRsaHashedImportParams | CTEcKeyImportParams | CTHmacImportParams | CTAesKeyAlgorithm, extractable: boolean, keyUsages: CTKeyUsage[]): Promise<CTCryptoKey>;
384
+ decrypt(algo: {
385
+ name: string;
386
+ iv: Uint8Array;
387
+ tagLength: number;
388
+ }, key: CTCryptoKey, data: Uint8Array): Promise<ArrayBuffer>;
389
+ encrypt(algo: {
390
+ name: string;
391
+ iv: Uint8Array;
392
+ tagLength: number;
393
+ }, key: CTCryptoKey, data: Uint8Array): Promise<ArrayBuffer>;
394
+ digestSHA256(data: Uint8Array): Promise<ArrayBuffer>;
395
+ randomBytes(size: number): Uint8Array;
396
+ }
397
+ declare function toCryptoRuntime(cryptoOpts?: Partial<CryptoRuntime>): CryptoRuntime;
398
+
399
+ export { type AsError, BuildURI, type CTAesKeyAlgorithm, type CTAlgorithm, type CTAlgorithmIdentifier, type CTArrayBufferView, type CTBufferSource, type CTCryptoKey, type CTEcKeyImportParams, type CTHmacImportParams, type CTJsonWebKey, type CTKeyFormat, type CTKeyType, type CTKeyUsage, type CTNamedCurve, type CTRsaHashedImportParams, type CoerceURI, type CryptoRuntime, type FnSerialized, Future, IsLogger, Keyed, KeyedResolvOnce, KeyedResolvSeq, type Lengthed, Level, type LevelHandler, LevelHandlerImpl, LogCollector, type LogSerializable, LogValue, LogWriter$1 as LogWriter, type Logger, LoggerImpl, type LoggerImplParams, type LoggerInterface, MockLogger, type MockLoggerReturn, None, Option, ResolveOnce, ResolveSeq, Result, ResultError, ResultOK, type Runtime, type Serialized, type SizeOrLength, type Sized, Some, SysAbstraction, URI, type WithLogger, type WithoutOption, type WithoutResult, asyncLogValue, logValue, removeSelfRef, runtimeFn, toCryptoRuntime };
package/index.js CHANGED
@@ -52,6 +52,9 @@ function removeSelfRef() {
52
52
  return value;
53
53
  };
54
54
  }
55
+ function asyncLogValue(val) {
56
+ throw new Error("Not implemented");
57
+ }
55
58
  function logValue(val) {
56
59
  switch (typeof val) {
57
60
  case "function":
@@ -208,6 +211,30 @@ var LogWriter = class {
208
211
  });
209
212
  }
210
213
  };
214
+ function getLen(value) {
215
+ if (Array.isArray(value)) {
216
+ return logValue(() => value.length);
217
+ } else if (typeof value === "string") {
218
+ return logValue(() => value.length);
219
+ } else if (typeof value === "object" && value !== null) {
220
+ if (typeof value.size === "number") {
221
+ return logValue(() => value.size);
222
+ } else if (typeof value.length === "number") {
223
+ return logValue(() => value.length);
224
+ }
225
+ return logValue(() => Object.keys(value).length);
226
+ }
227
+ return logValue(() => -1);
228
+ }
229
+ function hash(value) {
230
+ return "not implemented";
231
+ }
232
+ function toLogValue(lop) {
233
+ if (lop && typeof lop.then === "function") {
234
+ throw new Error("async logValue Not implemented");
235
+ }
236
+ return lop;
237
+ }
211
238
  var LoggerImpl = class _LoggerImpl {
212
239
  // readonly _id: string = "logger-" + Math.random().toString(36)
213
240
  constructor(params) {
@@ -317,15 +344,11 @@ var LoggerImpl = class _LoggerImpl {
317
344
  return this;
318
345
  }
319
346
  Len(value, key = "len") {
320
- if (Array.isArray(value)) {
321
- this._attributes[key] = logValue(() => value.length);
322
- } else if (typeof value === "string") {
323
- this._attributes[key] = logValue(() => value.length);
324
- } else if (typeof value === "object" && value !== null) {
325
- this._attributes[key] = logValue(() => Object.keys(value).length);
326
- } else {
327
- this.Int(key, -1);
328
- }
347
+ this._attributes[key] = getLen(value);
348
+ return this;
349
+ }
350
+ Hash(value, key = "hash") {
351
+ this._attributes[key] = asyncLogValue(async () => `${getLen(value).value()}:${await hash(value)}`);
329
352
  return this;
330
353
  }
331
354
  Url(url, key = "url") {
@@ -383,7 +406,7 @@ var LoggerImpl = class _LoggerImpl {
383
406
  if (typeof msg === "string" && !msg.trim().length) {
384
407
  delete attr["msg"];
385
408
  }
386
- if (((_a = attr["ts"]) == null ? void 0 : _a.value()) === "ETERNITY") {
409
+ if (((_a = toLogValue(attr["ts"])) == null ? void 0 : _a.value()) === "ETERNITY") {
387
410
  this.Timestamp.call({
388
411
  _sys: this._sys,
389
412
  _attributes: attr
@@ -394,7 +417,10 @@ var LoggerImpl = class _LoggerImpl {
394
417
  Msg(...args) {
395
418
  const fnError = this._resetAttributes(() => {
396
419
  var _a, _b;
397
- const doWrite = this._levelHandler.isEnabled((_a = this._attributes["level"]) == null ? void 0 : _a.value(), (_b = this._attributes["module"]) == null ? void 0 : _b.value());
420
+ const doWrite = this._levelHandler.isEnabled(
421
+ (_a = toLogValue(this._attributes["level"])) == null ? void 0 : _a.value(),
422
+ (_b = toLogValue(this._attributes["module"])) == null ? void 0 : _b.value()
423
+ );
398
424
  let fnRet = () => this._produceError(__spreadValues({}, this._attributes), ...args);
399
425
  if (doWrite) {
400
426
  const str = fnRet();
@@ -441,6 +467,10 @@ var WithLoggerBuilder = class {
441
467
  this._li.Len(value, key);
442
468
  return this;
443
469
  }
470
+ Hash(value, key) {
471
+ this._li.Hash(value, key);
472
+ return this;
473
+ }
444
474
  Ref(key, action) {
445
475
  this._li.Ref(key, action);
446
476
  return this;
@@ -530,7 +560,9 @@ var LogWriter2 = class {
530
560
  releaseLock() {
531
561
  }
532
562
  write(chunk) {
533
- chunk && this._bufferArr.push(chunk);
563
+ if (chunk) {
564
+ this._bufferArr.push(chunk);
565
+ }
534
566
  return Promise.resolve(void 0);
535
567
  }
536
568
  };
@@ -591,7 +623,9 @@ function MockLogger(params) {
591
623
  sys: params == null ? void 0 : params.sys,
592
624
  levelHandler: new LevelHandlerImpl()
593
625
  }).With().Module(modNames[0]).Logger();
594
- !(params == null ? void 0 : params.disableDebug) && logger.SetDebug(...modNames);
626
+ if (!(params == null ? void 0 : params.disableDebug)) {
627
+ logger.SetDebug(...modNames);
628
+ }
595
629
  return {
596
630
  logCollector: lc,
597
631
  logger
@@ -719,8 +753,197 @@ var None = class extends Option {
719
753
  throw new Error("None.unwrap");
720
754
  }
721
755
  };
756
+
757
+ // src/runtime.ts
758
+ function isSet(value, ref = globalThis) {
759
+ const [head, ...tail] = value.split(".");
760
+ if (["object", "function"].includes(typeof ref) && ref && ["object", "function"].includes(typeof ref[head]) && ref[head]) {
761
+ if (tail.length <= 1) {
762
+ return true;
763
+ }
764
+ return isSet(tail.join("."), ref[head]);
765
+ }
766
+ return false;
767
+ }
768
+ function runtimeFn() {
769
+ const isNodeIsh = isSet("process.versions.node");
770
+ const isDeno = isSet("Deno");
771
+ return {
772
+ isNodeIsh,
773
+ isBrowser: !(isNodeIsh || isDeno),
774
+ isDeno,
775
+ isReactNative: false
776
+ };
777
+ }
778
+
779
+ // src/uri.ts
780
+ function falsy2undef(value) {
781
+ return value === void 0 || value === null ? void 0 : value;
782
+ }
783
+ function ensureURLWithDefaultProto(url, defaultProtocol) {
784
+ if (!url) {
785
+ return new URL(`${defaultProtocol}//`);
786
+ }
787
+ if (typeof url === "string") {
788
+ try {
789
+ return new URL(url);
790
+ } catch (e) {
791
+ return new URL(`${defaultProtocol}//${url}`);
792
+ }
793
+ } else {
794
+ return url;
795
+ }
796
+ }
797
+ var BuildURI = class {
798
+ constructor(url) {
799
+ this._url = url;
800
+ }
801
+ hostname(h) {
802
+ this._url.hostname = h;
803
+ return this;
804
+ }
805
+ password(p) {
806
+ this._url.password = p;
807
+ return this;
808
+ }
809
+ port(p) {
810
+ this._url.port = p;
811
+ return this;
812
+ }
813
+ username(u) {
814
+ this._url.username = u;
815
+ return this;
816
+ }
817
+ search(s) {
818
+ this._url.search = s;
819
+ return this;
820
+ }
821
+ protocol(p) {
822
+ this._url.protocol = p;
823
+ return this;
824
+ }
825
+ pathname(p) {
826
+ this._url.pathname = p;
827
+ return this;
828
+ }
829
+ hash(h) {
830
+ this._url.hash = h;
831
+ return this;
832
+ }
833
+ host(h) {
834
+ this._url.host = h;
835
+ return this;
836
+ }
837
+ delParam(key) {
838
+ this._url.searchParams.delete(key);
839
+ return this;
840
+ }
841
+ setParam(key, str) {
842
+ this._url.searchParams.set(key, str);
843
+ return this;
844
+ }
845
+ toString() {
846
+ return this._url.toString();
847
+ }
848
+ build() {
849
+ return URI.from(this._url);
850
+ }
851
+ };
852
+ var URI = class _URI {
853
+ // if no protocol is provided, default to file:
854
+ static from(strURLUri, defaultProtocol = "file:") {
855
+ switch (typeof falsy2undef(strURLUri)) {
856
+ case "undefined":
857
+ return new _URI(new URL(`${defaultProtocol}//`));
858
+ case "string":
859
+ return new _URI(ensureURLWithDefaultProto(strURLUri, defaultProtocol));
860
+ case "object":
861
+ if (strURLUri instanceof _URI) {
862
+ return new _URI(new URL(strURLUri._url.toString()));
863
+ } else if (strURLUri instanceof URL) {
864
+ return new _URI(new URL(strURLUri.toString()));
865
+ }
866
+ throw new Error(`unknown object type: ${strURLUri}`);
867
+ default:
868
+ throw new Error(`Invalid argument: ${typeof strURLUri}`);
869
+ }
870
+ }
871
+ constructor(url) {
872
+ this._url = url;
873
+ }
874
+ build() {
875
+ return new BuildURI(this.asURL());
876
+ }
877
+ get hostname() {
878
+ return this._url.hostname;
879
+ }
880
+ get password() {
881
+ return this._url.password;
882
+ }
883
+ get port() {
884
+ return this._url.port;
885
+ }
886
+ get username() {
887
+ return this._url.username;
888
+ }
889
+ get search() {
890
+ return this._url.search;
891
+ }
892
+ get protocol() {
893
+ return this._url.protocol;
894
+ }
895
+ get pathname() {
896
+ return this._url.toString().replace(/^.*:\/\//, "").replace(/\?.*$/, "");
897
+ }
898
+ get hash() {
899
+ return this._url.hash;
900
+ }
901
+ get host() {
902
+ return this._url.host;
903
+ }
904
+ hasParam(key) {
905
+ return this._url.searchParams.has(key);
906
+ }
907
+ getParam(key) {
908
+ return falsy2undef(this._url.searchParams.get(key));
909
+ }
910
+ clone() {
911
+ return new _URI(this.asURL());
912
+ }
913
+ asURL() {
914
+ const url = new URL(this._url.toString());
915
+ url.searchParams.sort();
916
+ return url;
917
+ }
918
+ toString() {
919
+ return this._url.toString();
920
+ }
921
+ };
922
+
923
+ // src/crypto.ts
924
+ function randomBytes(size) {
925
+ const bytes = new Uint8Array(size);
926
+ if (size > 0) {
927
+ crypto.getRandomValues(bytes);
928
+ }
929
+ return bytes;
930
+ }
931
+ function digestSHA256(data) {
932
+ return Promise.resolve(crypto.subtle.digest("SHA-256", data));
933
+ }
934
+ function toCryptoRuntime(cryptoOpts = {}) {
935
+ const runtime = {
936
+ importKey: cryptoOpts.importKey || crypto.subtle.importKey.bind(crypto.subtle),
937
+ encrypt: cryptoOpts.encrypt || crypto.subtle.encrypt.bind(crypto.subtle),
938
+ decrypt: cryptoOpts.decrypt || crypto.subtle.decrypt.bind(crypto.subtle),
939
+ randomBytes: cryptoOpts.randomBytes || randomBytes,
940
+ digestSHA256: cryptoOpts.digestSHA256 || digestSHA256
941
+ };
942
+ return runtime;
943
+ }
722
944
  export {
723
945
  BrowserEnvActions,
946
+ BuildURI,
724
947
  EnvImpl,
725
948
  Future,
726
949
  IDMode,
@@ -748,8 +971,12 @@ export {
748
971
  Time,
749
972
  TimeMode,
750
973
  TimeUnits,
974
+ URI,
975
+ asyncLogValue,
751
976
  envFactory,
752
977
  logValue,
753
- removeSelfRef
978
+ removeSelfRef,
979
+ runtimeFn,
980
+ toCryptoRuntime
754
981
  };
755
982
  //# sourceMappingURL=index.js.map