@cripty2001/utils 0.0.36 → 0.0.38

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.
@@ -8,6 +8,9 @@ declare class AppserverError extends Error {
8
8
  status: number;
9
9
  constructor(code: string, message: string, payload?: AppserverData, status?: number);
10
10
  }
11
+ export declare class AppserverAuthError extends AppserverError {
12
+ constructor();
13
+ }
11
14
  export declare class AppserverHandledError extends AppserverError {
12
15
  constructor(code: string, message: string, payload?: AppserverData);
13
16
  }
@@ -16,6 +19,6 @@ export declare class Appserver<U extends AppserverData> {
16
19
  private parseUser;
17
20
  constructor(port: number, parseUser: AppserverUsergetter<U>);
18
21
  private parseInput;
19
- register<ISchema extends TSchema, O extends AppserverData, I extends Static<ISchema> & AppserverData = Static<ISchema> & AppserverData>(action: string, inputSchema: ISchema, handler: AppserverHandler<I, U, O>): void;
22
+ register<ISchema extends TSchema, O extends AppserverData, I extends Static<ISchema> & AppserverData = Static<ISchema> & AppserverData>(action: string, inputSchema: ISchema, auth: boolean, handler: AppserverHandler<I, U, O>): void;
20
23
  }
21
24
  export {};
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.Appserver = exports.AppserverHandledError = void 0;
6
+ exports.Appserver = exports.AppserverHandledError = exports.AppserverAuthError = void 0;
7
7
  const express_1 = __importDefault(require("express"));
8
8
  const value_1 = require("@sinclair/typebox/value");
9
9
  const msgpack_1 = require("@msgpack/msgpack");
@@ -19,6 +19,12 @@ class AppserverError extends Error {
19
19
  this.status = status;
20
20
  }
21
21
  }
22
+ class AppserverAuthError extends AppserverError {
23
+ constructor() {
24
+ super("PERMISSION_DENIED", "You have no right to access this page", {}, 403);
25
+ }
26
+ }
27
+ exports.AppserverAuthError = AppserverAuthError;
22
28
  class AppserverHandledError extends AppserverError {
23
29
  constructor(code, message, payload = {}) {
24
30
  super(code, message, payload);
@@ -51,11 +57,16 @@ class Appserver {
51
57
  user: token ? await this.parseUser(token) : null
52
58
  };
53
59
  }
54
- register(action, inputSchema, handler) {
60
+ register(action, inputSchema, auth, handler) {
55
61
  this.app.post(`/exec/${action}`, async (req, res) => {
56
62
  const { status, data } = await (async () => {
57
63
  try {
58
64
  const { data: unsafeData, user } = await this.parseInput(req);
65
+ if (auth && user === null)
66
+ return {
67
+ status: 401,
68
+ data: { error: 'Authentication required', code: 'AUTHENTICATION_REQUIRED' }
69
+ };
59
70
  if (!value_1.Value.Check(inputSchema, unsafeData))
60
71
  return {
61
72
  status: 422,
package/dist/index.d.ts CHANGED
@@ -10,23 +10,75 @@ export type ExactlyOne<T> = {
10
10
  [K in keyof T]: Pick<T, K> & Partial<Record<Exclude<keyof T, K>, never>>;
11
11
  }[keyof T];
12
12
  export type AllRequired<T> = T extends ExactlyOne<infer U> ? ExactlyOne<Required<U>> : never;
13
+ /**
14
+ * Generate a random string from the given alphabeth.
15
+ * @param _alphabeth The alphabeth to draw characters from
16
+ * @param length The length of the string to generate
17
+ * @returns The generated string
18
+ */
13
19
  export declare function getRandom(_alphabeth: string, length: number): string;
20
+ /**
21
+ * Generate a random, url safe, id string, with 3 bits of entropy per character.
22
+ * @param length The length of the id to generate
23
+ * @returns The generated id
24
+ */
14
25
  export declare function getRandomId(length?: number): string;
26
+ /**
27
+ * Generate a random one time password (OTP).
28
+ * @param length The length of the OTP to generate
29
+ * @param char Allow for characters to be inserted in the otp
30
+ * @returns The generated otp
31
+ */
15
32
  export declare function getRandomOtp(length?: number, char?: boolean): string;
33
+ /**
34
+ * Pause the execution for the given number of milliseconds.
35
+ * @param ms The number of milliseconds to sleep
36
+ */
16
37
  export declare function sleep(ms: number): Promise<void>;
17
38
  export declare function parseHash(fields: string[]): URLSearchParams;
18
- export declare function loop(cb: () => Promise<void>, interval: number, onError?: (e: any) => Promise<void>): Promise<void>;
39
+ /**
40
+ * Start an infinite loop executing an async callback spaced by at least the given interval.
41
+ * The loop ignores errors (the next execution is not affected), but an optional error callback can be provided to handle them.
42
+ * The error callback can return true to stop the loop. An error in the error callback will be logged, but the loop will continue.
43
+ *
44
+ * @param cb The (async) callback to execute
45
+ * @param interval The minimum interval between two executions, in milliseconds. The execution may be scheduled later, but not earlier.
46
+ * @param onError The error callback. Return true to stop the loop.
47
+ */
48
+ export declare function loop(cb: () => Promise<void>, interval: number, onError?: (e: any) => Promise<boolean>): Promise<void>;
19
49
  /**
20
50
  * Float aware deep equality check between two values.
21
51
  */
22
52
  export declare function isEqual(a: any, b: any): boolean;
23
53
  export declare function arrayStep(from: number, to: number, step: number): number[];
54
+ /**
55
+ * Copy the given text to clipboard.
56
+ * @param text The text to copy to clipboard
57
+ */
24
58
  export declare function copyToClipboard(text: string): void;
59
+ /**
60
+ * Download data as a file.
61
+ * @param data The data to download
62
+ * @param filename The filename to use
63
+ * @param mimeType The mime type of the data
64
+ */
25
65
  export declare function download(data: string | Blob, filename: string, mimeType?: string): void;
26
66
  export declare function stableLog(obj: any, message?: string): void;
27
67
  export declare function parseQuery(query: string | Record<string, any> | URLSearchParams, fields: string[]): {
28
68
  extracted: URLSearchParams;
29
69
  left: URLSearchParams;
30
70
  };
71
+ /**
72
+ * Generate a random int between min and max, inclusive.
73
+ * @param min The minimum allowed number
74
+ * @param max The maximum allowed number
75
+ * @returns The generated random int
76
+ */
31
77
  export declare function randBetween(min: number, max: number): number;
78
+ /**
79
+ * Get an environment variable, throwing if it is not defined and no default value is provided.
80
+ * @param key The environment variable key
81
+ * @param defaultValue The default value to use if the environment variable is not defined
82
+ * @returns The environment variable value, or the default value if provided
83
+ */
32
84
  export declare function getEnv(key: string, defaultValue?: string): string;
package/dist/index.js CHANGED
@@ -15,6 +15,12 @@ exports.parseQuery = parseQuery;
15
15
  exports.randBetween = randBetween;
16
16
  exports.getEnv = getEnv;
17
17
  const lodash_1 = require("lodash");
18
+ /**
19
+ * Generate a random string from the given alphabeth.
20
+ * @param _alphabeth The alphabeth to draw characters from
21
+ * @param length The length of the string to generate
22
+ * @returns The generated string
23
+ */
18
24
  function getRandom(_alphabeth, length) {
19
25
  const alphabeth = _alphabeth.split("");
20
26
  const toReturn = [];
@@ -23,14 +29,29 @@ function getRandom(_alphabeth, length) {
23
29
  }
24
30
  return toReturn.join("");
25
31
  }
32
+ /**
33
+ * Generate a random, url safe, id string, with 3 bits of entropy per character.
34
+ * @param length The length of the id to generate
35
+ * @returns The generated id
36
+ */
26
37
  function getRandomId(length = 20) {
27
38
  const ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
28
39
  return getRandom(ALPHABET, length);
29
40
  }
41
+ /**
42
+ * Generate a random one time password (OTP).
43
+ * @param length The length of the OTP to generate
44
+ * @param char Allow for characters to be inserted in the otp
45
+ * @returns The generated otp
46
+ */
30
47
  function getRandomOtp(length = 6, char = false) {
31
48
  const ALPHABET = "0123456789" + (char ? "ABCDEFGHIJKLMNOPQRSTUVWXYZ" : "");
32
49
  return getRandom(ALPHABET, length);
33
50
  }
51
+ /**
52
+ * Pause the execution for the given number of milliseconds.
53
+ * @param ms The number of milliseconds to sleep
54
+ */
34
55
  function sleep(ms) {
35
56
  return new Promise((resolve) => setTimeout(resolve, ms));
36
57
  }
@@ -53,13 +74,28 @@ function parseHash(fields) {
53
74
  // Returning extracted fields
54
75
  return toReturn;
55
76
  }
56
- async function loop(cb, interval, onError = async (e) => { console.error(e); }) {
77
+ /**
78
+ * Start an infinite loop executing an async callback spaced by at least the given interval.
79
+ * The loop ignores errors (the next execution is not affected), but an optional error callback can be provided to handle them.
80
+ * The error callback can return true to stop the loop. An error in the error callback will be logged, but the loop will continue.
81
+ *
82
+ * @param cb The (async) callback to execute
83
+ * @param interval The minimum interval between two executions, in milliseconds. The execution may be scheduled later, but not earlier.
84
+ * @param onError The error callback. Return true to stop the loop.
85
+ */
86
+ async function loop(cb, interval, onError = async (e) => { console.error(e); return false; }) {
57
87
  while (true) {
58
88
  try {
59
89
  await cb();
60
90
  }
61
91
  catch (e) {
62
- await onError(e);
92
+ const stop = await onError(e)
93
+ .catch((e) => {
94
+ console.error("Error in loop error handler:", e);
95
+ return false;
96
+ });
97
+ if (stop)
98
+ break;
63
99
  }
64
100
  finally {
65
101
  await sleep(interval);
@@ -85,9 +121,19 @@ function arrayStep(from, to, step) {
85
121
  }
86
122
  return result;
87
123
  }
124
+ /**
125
+ * Copy the given text to clipboard.
126
+ * @param text The text to copy to clipboard
127
+ */
88
128
  function copyToClipboard(text) {
89
129
  navigator.clipboard.writeText(text);
90
130
  }
131
+ /**
132
+ * Download data as a file.
133
+ * @param data The data to download
134
+ * @param filename The filename to use
135
+ * @param mimeType The mime type of the data
136
+ */
91
137
  function download(data, filename, mimeType = 'application/octet-stream') {
92
138
  const blob = data instanceof Blob ? data : new Blob([data], { type: mimeType });
93
139
  const url = URL.createObjectURL(blob);
@@ -132,9 +178,21 @@ function parseQuery(query, fields) {
132
178
  left: data
133
179
  };
134
180
  }
181
+ /**
182
+ * Generate a random int between min and max, inclusive.
183
+ * @param min The minimum allowed number
184
+ * @param max The maximum allowed number
185
+ * @returns The generated random int
186
+ */
135
187
  function randBetween(min, max) {
136
188
  return Math.floor(Math.random() * (max - min + 1)) + min;
137
189
  }
190
+ /**
191
+ * Get an environment variable, throwing if it is not defined and no default value is provided.
192
+ * @param key The environment variable key
193
+ * @param defaultValue The default value to use if the environment variable is not defined
194
+ * @returns The environment variable value, or the default value if provided
195
+ */
138
196
  function getEnv(key, defaultValue) {
139
197
  const value = process.env[key] ?? defaultValue;
140
198
  if (value === undefined)
@@ -31,7 +31,17 @@ export declare function useWhispr<T>(data: T | Whispr<T>): Whispr<T>;
31
31
  * @param cb The callback to call on value change
32
32
  */
33
33
  export declare function useOnWhispr<T>(w: Whispr<T>, cb: (value: T) => void): void;
34
+ /**
35
+ * Return a reactive current timestamp (ms), updated at the given interval.
36
+ * @param refresh The refresh interval
37
+ * @returns The current timestamp
38
+ */
34
39
  export declare function useCurrentTimestamp(refresh?: number): number;
40
+ /**
41
+ * Debounce a reactive value, deep checking for equality, and stopping updates until the value changes.
42
+ * @param value The value to debounce
43
+ * @returns The debounced value
44
+ */
35
45
  export declare function useDebounced<T>(value: T): T;
36
46
  /**
37
47
  *
@@ -66,6 +66,11 @@ function useOnWhispr(w, cb) {
66
66
  return () => unsub();
67
67
  }, [w, cb]);
68
68
  }
69
+ /**
70
+ * Return a reactive current timestamp (ms), updated at the given interval.
71
+ * @param refresh The refresh interval
72
+ * @returns The current timestamp
73
+ */
69
74
  function useCurrentTimestamp(refresh = 1000) {
70
75
  const [currTs, setCurrTs] = (0, react_1.useState)(Date.now());
71
76
  (0, react_1.useEffect)(() => {
@@ -74,6 +79,11 @@ function useCurrentTimestamp(refresh = 1000) {
74
79
  }, [setCurrTs]);
75
80
  return currTs;
76
81
  }
82
+ /**
83
+ * Debounce a reactive value, deep checking for equality, and stopping updates until the value changes.
84
+ * @param value The value to debounce
85
+ * @returns The debounced value
86
+ */
77
87
  function useDebounced(value) {
78
88
  const lastEmitted = (0, react_1.useRef)(value);
79
89
  const [debounced, setDebounced] = (0, react_1.useState)(value);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cripty2001/utils",
3
- "version": "0.0.36",
3
+ "version": "0.0.38",
4
4
  "description": "Internal Set of utils. If you need them use them, otherwise go to the next package ;)",
5
5
  "homepage": "https://github.com/cripty2001/utils#readme",
6
6
  "bugs": {