@koloseum/utils 0.2.28 → 0.3.0

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.
package/dist/utils.d.ts DELETED
@@ -1,394 +0,0 @@
1
- import type { Database } from "@koloseum/types/database";
2
- import type { BrowserInfo, CustomError, Microservice, MicroserviceGroup, MicroserviceObject, UserWithCustomMetadata } from "@koloseum/types/general";
3
- import type { BranchAddressObject, County, IdentityType, PronounsCheckboxes, PronounsItem, Sex, SocialMediaPlatform } from "@koloseum/types/public-auth";
4
- import type { Page } from "@sveltejs/kit";
5
- import type { SupabaseClient, FunctionInvokeOptions, PostgrestError } from "@supabase/supabase-js";
6
- import type { IOptions } from "@suprsend/web-components/dist/types/interface.d.ts";
7
- import type { MobilePhoneLocale } from "validator";
8
- export declare const Data: {
9
- /**
10
- * A generic authenticated user.
11
- * @param {string} id - The user ID; defaults to a random UUID
12
- * @param {Date} date - The date and time; defaults to the current date and time
13
- * @param {string} phone - The phone number; defaults to a generic Kenyan phone number
14
- * @param {string} identityId - A default identity ID; defaults to a random UUID
15
- * @returns A generic authenticated user.
16
- */
17
- authenticatedUser: (id?: string, date?: Date, phone?: string, identityId?: string) => UserWithCustomMetadata;
18
- };
19
- export declare const Status: {
20
- /**
21
- * A generic error message.
22
- */
23
- ERROR: string;
24
- /**
25
- * A generic loading message.
26
- */
27
- LOADING: string;
28
- /**
29
- * A generic password reset request message.
30
- */
31
- PASSWORD_RESET_REQUESTED: string;
32
- };
33
- export declare const Utility: {
34
- /**
35
- * Calls a Supabase Edge function.
36
- * @param {boolean} browser - Whether the function is being called in the browser
37
- * @param {SupabaseClient<Database>} supabase - The Supabase client
38
- * @param {string} path - The path to the Edge function
39
- * @param {FunctionInvokeOptions} [options] - The options to use for the function invocation; defaults to `{ method: "GET" }`
40
- * @returns The response from the Edge function
41
- */
42
- callEdgeFunction: (browser: boolean, supabase: SupabaseClient<Database>, path: string, options?: FunctionInvokeOptions) => Promise<{
43
- code: number;
44
- data?: any;
45
- error?: string;
46
- context?: Record<string, any>;
47
- }>;
48
- /**
49
- * Capitalises a given word.
50
- * @param {string} word - The word to be capitalised
51
- * @returns The capitalised word
52
- */
53
- capitalise: (word: string) => string;
54
- /**
55
- * Cleans a URL by removing the protocol and trailing slashes.
56
- * @param {string} url - The URL to clean
57
- * @returns {string} The cleaned URL
58
- */
59
- cleanUrl: (url: string) => string;
60
- /**
61
- * Returns a custom error object.
62
- * @param {number} code - The error code; defaults to `500` if not provided or invalid
63
- * @param {string} message - The error message
64
- * @returns An object with the error `code` and `message`
65
- */
66
- customError: (code: number | undefined, message: string) => CustomError;
67
- /**
68
- * A regular expression for E.164 phone numbers.
69
- *
70
- * - Source: https://www.twilio.com/docs/glossary/what-e164
71
- */
72
- e164Regex: RegExp;
73
- /**
74
- * Formats a date in the format DD/MM/YYYY (by default) or YYYY-MM-DD (for client).
75
- * @param {string} date - Date to be formatted
76
- * @param {boolean} forClient - Specify whether the data is for displaying on the client; defaults to `false`
77
- * @returns The formatted date string, or `null` if invalid input or in case of an error
78
- */
79
- formatDate: (date: string, forClient?: boolean) => string | null;
80
- /**
81
- * Formats a social media platform for display.
82
- * @param {SocialMediaPlatform} platform - The social media platform to be formatted
83
- * @returns The formatted social media platform string
84
- */
85
- formatSocialMediaPlatform: (platform: SocialMediaPlatform) => string;
86
- /**
87
- * Returns an age in years given a birth date.
88
- * @param {Date | string | number | null} dateOfBirth - The date of birth
89
- * @returns The age in years, or `NaN` if the input is invalid
90
- */
91
- getAge: (dateOfBirth: Date | string | number | null) => number;
92
- /**
93
- * Formats a date as a locale-specific string.
94
- * @param {Date | string | number | null} date - Date to be formatted
95
- * @param {boolean} withTime - Specify whether the date should include time; defaults to `false`
96
- * @param {string} timeZone - The time zone to use for formatting; defaults to `Africa/Nairobi`
97
- * @returns The formatted date string, or an empty string if invalid input
98
- */
99
- getDateString: (date: Date | string | number | null, withTime?: boolean, timeZone?: string) => string;
100
- /**
101
- * Formats an identity type for display.
102
- * @param {IdentityType} identityType - The identity type to be formatted
103
- * @returns The formatted identity type string
104
- */
105
- getIdentityTypeString: (identityType: IdentityType) => string;
106
- /**
107
- * Returns a list of all counties in Kenya.
108
- * @param {"name" | "code"} sortBy - The field to sort the counties by, i.e. `name` or `code`; defaults to `name`
109
- * @returns {Promise<County[]>} A list of objects with the county `name`, `code`, and a list of `subCounties`
110
- */
111
- getKenyaCounties: (sortBy?: "name" | "code") => Promise<County[]>;
112
- /**
113
- * Formats a date to an ISO string in Kenyan time, i.e. `Africa/Nairobi` (UTC+3).
114
- * @param {Date | string | number | null} date - The date to format
115
- * @returns {string} The formatted date in ISO string format, or an empty string if invalid input
116
- */
117
- getKenyanISOString: (date: Date | string | number | null) => string;
118
- /**
119
- * Returns the URL for a menu item based on the slug.
120
- * @param {string} base - The base URL
121
- * @param {string} slug - The slug of the menu item
122
- * @returns {string} The URL for the menu item
123
- */
124
- getMenuItemUrl: (base: string, slug: string | undefined) => string;
125
- /**
126
- * Returns the parent URL for a given base URL.
127
- * @param {string} base - The base URL
128
- * @returns {string} The parent URL
129
- */
130
- getParentUrl: (base: string) => string;
131
- /**
132
- * Returns a pronoun given pronouns and a type.
133
- * @param {PronounsItem | null} pronouns - The pronouns to be formatted
134
- * @param {"subject" | "object" | "possessive" | "reflexive"} type - The type of pronoun to be returned
135
- * @param {Sex} sex - The user's sex; defaults to `undefined`
136
- * @returns The formatted pronoun, or `null` if the input is invalid
137
- */
138
- getPronoun: (pronouns: PronounsItem | null, type: "subject" | "object" | "possessive" | "reflexive", sex?: Sex) => string | null;
139
- /**
140
- * Returns the redirect URL for a given URI.
141
- * @param {string} uri - The URI to get the redirect URL for, i.e. `microserviceGroup:path` (e.g. `players:fgc/tournaments`)
142
- * @param {"development" | "production"} env - The environment to use for the redirect URL; defaults to `production`
143
- * @returns {string} An object with the redirect `url`, or an `error` if any occurs
144
- */
145
- getRedirectUrl: (uri: string, env?: "development" | "production") => {
146
- url?: string;
147
- error?: CustomError;
148
- };
149
- /**
150
- * Generate a SuprSend notification inbox configuration object for a user.
151
- * @param {string} userId - The user ID to generate the configuration for.
152
- * @param {string} publicApiKey - The public API key to use for SuprSend.
153
- * @returns The SuprSend notification inbox configuration object.
154
- */
155
- getSuprSendInboxConfig: (userId: string, publicApiKey: string) => IOptions;
156
- /**
157
- * Handles the click event for pronouns checkboxes.
158
- * @param {MouseEvent} e - The click event
159
- * @param {PronounsCheckboxes} checkboxes - The pronouns checkboxes
160
- */
161
- handlePronounsCheckboxClick: (e: MouseEvent, checkboxes: PronounsCheckboxes) => void;
162
- /**
163
- * Checks if a user is authorised to access a microservice.
164
- * @param {SupabaseClient<Database>} supabase - The Supabase client.
165
- * @param {UserWithCustomMetadata} user - The user to check.
166
- * @param {Object} options - The options for the function.
167
- * @param {MicroserviceGroup} options.microserviceGroup - The microservice group.
168
- * @param {Microservice<MicroserviceGroup> | string} options.microservice - The microservice.
169
- * @param {string} options.playersUrl - The URL to the Players microservice.
170
- * @param {(role: string) => string} options.requestedPermission - A function that returns the requested permission for a given role.
171
- * @returns {Promise<{ isAuthorised?: boolean; redirect?: { code: number; url: string }; error?: CustomError }>} The result of the function.
172
- */
173
- isUserAuthorised: (supabase: SupabaseClient<Database>, user: UserWithCustomMetadata, options: {
174
- microserviceGroup: MicroserviceGroup;
175
- microservice: Microservice<MicroserviceGroup> | string;
176
- playersUrl?: string;
177
- requestedPermission?: (role: string) => string;
178
- }) => Promise<{
179
- isAuthorised?: boolean;
180
- redirect?: {
181
- code: number;
182
- url: string;
183
- };
184
- error?: CustomError;
185
- }>;
186
- /**
187
- * A reference of microservices available on the platform, represented as an object with each user group (i.e. `public`, `players`, `lounges`, and `backroom`) having its own array of microservices. Each microservice in a list is an object with the following properties:
188
- * - `name`: The name of the microservice.
189
- * - `description`: A description of the microservice.
190
- * - `slug`: The slug of the microservice.
191
- * - `features`: An array of features that the microservice has.
192
- * - `roles`: An array of roles attached to the microservice.
193
- */
194
- microservices: { [key in MicroserviceGroup]: MicroserviceObject<key>[]; };
195
- /**
196
- * The minimum birth date (from today's date) for a user who is a minor, i.e. `YYYY-MM-DD`
197
- */
198
- minimumMinorBirthDate: string;
199
- /**
200
- * Check if a page is active based on the slug and microservice.
201
- * @param page - The current page object.
202
- * @param slug - The slug of the page to check.
203
- * @param microservice - The microservice to check against.
204
- * @param base - The base path of the application; defaults to an empty string.
205
- * @returns `true` if the page is active, `false` otherwise.
206
- */
207
- pageIsActive: (page: Page, slug: string | undefined, microservice?: Microservice<MicroserviceGroup>, base?: string) => boolean;
208
- /**
209
- * Paginates an array.
210
- * @template T - The type of array items; defaults to `any`
211
- * @param {T[]} array - The array to paginate
212
- * @param {number} page - The page number
213
- * @param {number} pageSize - The number of items per page; defaults to 10
214
- * @returns {Object} The paginated array and total number of pages
215
- */
216
- paginateArray: <T = any>(array: T[], page: number, pageSize?: number) => {
217
- paginatedItems: T[];
218
- totalPages: number;
219
- };
220
- /**
221
- * Parses a `CustomError` object within a page/layout server load function and returns an error to be thrown.
222
- * @param {CustomError} error - The error object
223
- * @returns A new `Error` object if the error is unexpected, or a Svelte error otherwise
224
- */
225
- parseLoadError: (error: CustomError) => Error | never;
226
- /**
227
- * Parses a Postgres interval string and returns a string in the specified format.
228
- * @param {string} interval - The interval string to parse
229
- * @param {"postgres" | "iso" | "iso-short"} type - The format to return the interval in; defaults to `postgres`
230
- * @returns A string in the specified format
231
- */
232
- parsePostgresInterval: (interval: string, type?: "postgres" | "iso" | "iso-short") => string | null;
233
- /**
234
- * Parses a `PostgrestError` object and returns a custom error object if any has occurred.
235
- * @param {PostgrestError | null} postgrestError - The `PostgrestError` object, or `null` if no error occurred
236
- * @param {boolean} clientSafe - Whether to clamp 5xx errors down to 422 to prevent Sentry from capturing them as unhandled; defaults to `true`
237
- * @returns An object with an `error` if any has occurred
238
- */
239
- parsePostgrestError: (postgrestError: PostgrestError | null, clientSafe?: boolean) => {
240
- error?: CustomError;
241
- };
242
- /**
243
- * A regular expression for user passwords to match during authentication. It covers the following rules:
244
- * - at least 8 characters long
245
- * - at least one digit
246
- * - at least one lowercase letter
247
- * - at least one uppercase letter
248
- * - at least one symbol
249
- */
250
- passwordRegex: RegExp;
251
- /**
252
- * Returns a regular expression for a Koloseum platform ID.
253
- * @param {string} type - The type of platform ID to return
254
- * @returns A regular expression for the platform ID, or `null` if the type is invalid
255
- */
256
- platformIdRegex: (type: "lounge" | "loungeBranch" | "player") => RegExp | null;
257
- /**
258
- * Sanitises any potential HTML injected into user input.
259
- * @param {string} input - The input to be sanitised
260
- * @returns A sanitised string, or an empty string if the input is invalid
261
- */
262
- sanitiseHtml: (input: string) => string;
263
- /**
264
- * Sends a welcome notification to a new user.
265
- * @param {SupabaseClient<Database>} supabase - The Supabase client
266
- * @param {UserWithCustomMetadata} user - The user to send the notification to
267
- * @param {MicroserviceGroup} microserviceGroup - The microservice group the user belongs to
268
- * @returns An object with an `error` if any has occurred
269
- */
270
- sendWelcomeNotification: (supabase: SupabaseClient<Database>, user: UserWithCustomMetadata, microserviceGroup: MicroserviceGroup) => Promise<{
271
- error?: CustomError;
272
- }>;
273
- /**
274
- * A regular expression for social media handles, without a leading slash or @ character.
275
- *
276
- * - Source: https://stackoverflow.com/a/74579651
277
- */
278
- socialMediaHandleRegex: RegExp;
279
- /**
280
- * Validates address data submitted in a form and returns the validated data.
281
- * @param {FormData} formData - The submitted form data
282
- * @returns An object with the validated `address`, or an `error` if any has occurred
283
- */
284
- validateAddress: (formData: FormData) => Promise<{
285
- address?: BranchAddressObject;
286
- error?: CustomError;
287
- }>;
288
- /**
289
- * Validates an E.164 phone number.
290
- * @param {string} phoneNumber - The phone number to be validated
291
- * @param {"any" | MobilePhoneLocale | MobilePhoneLocale[]} [locale="any"] - The locale(s) to validate the phone number against
292
- * @returns `true` if the phone number is valid; `false` otherwise
293
- */
294
- validateE164: (phoneNumber: string, locale?: "any" | MobilePhoneLocale | MobilePhoneLocale[]) => boolean;
295
- /**
296
- * Validates a social media handle.
297
- * @param {string} handle - The social media handle to be validated
298
- * @returns `true` if the handle is valid; `false` otherwise
299
- */
300
- validateSocialMediaHandle: (handle: string) => boolean;
301
- };
302
- export declare const Cache: {
303
- /**
304
- * Delete cached data from Valkey.
305
- * @param valkey - The Valkey client instance
306
- * @param cachePrefix - The cache prefix
307
- * @param key - The cache key
308
- */
309
- deleteData: (valkey: any, cachePrefix: string, key: string) => Promise<void>;
310
- /**
311
- * Generate cache key with consistent formatting
312
- * @param prefix - The key prefix
313
- * @param params - Additional parameters to include in the key
314
- * @returns The formatted cache key
315
- */
316
- generateDataKey: (prefix: string, ...params: (string | number)[]) => string;
317
- /**
318
- * Get cached data from Valkey.
319
- * @param valkey - The Valkey client instance
320
- * @param cachePrefix - The cache prefix
321
- * @param key - The cache key
322
- * @returns The cached data, or `null` if not found
323
- */
324
- getData: <T>(valkey: any, cachePrefix: string, key: string) => Promise<T | null>;
325
- /**
326
- * Invalidate cache by pattern
327
- * @param valkey - The Valkey client instance
328
- * @param cachePrefix - The cache prefix
329
- * @param pattern - The pattern to match keys against (e.g., "app-config*")
330
- */
331
- invalidateDataByPattern: (valkey: any, cachePrefix: string, pattern: string) => Promise<void>;
332
- /**
333
- * Set data in Valkey cache.
334
- * @param valkey - The Valkey client instance
335
- * @param cachePrefix - The cache prefix
336
- * @param key - The cache key
337
- * @param data - The data to cache
338
- * @param ttl - The time to live in seconds; defaults to 1 hour
339
- */
340
- setData: <T>(valkey: any, cachePrefix: string, key: string, data: T, ttl?: number) => Promise<void>;
341
- };
342
- export declare const Browser: {
343
- /**
344
- * Checks if a specific feature is supported by the browser.
345
- * @param feature - The feature to check
346
- * @param browserName - The name of the browser
347
- * @param browserVersion - The version of the browser
348
- * @returns `true` if the feature is supported, `false` otherwise
349
- */
350
- checkFeatureSupport: (feature: string, browserName: string, browserVersion: number) => boolean;
351
- /**
352
- * Gets detailed browser information for debugging.
353
- */
354
- getDetailedInfo: () => {
355
- browser: string;
356
- os: string;
357
- platform: string;
358
- engine: string;
359
- userAgent: string;
360
- };
361
- /**
362
- * Gets comprehensive browser information using Bowser.
363
- */
364
- getInfo: () => BrowserInfo;
365
- /**
366
- * Gets specific browser recommendations based on the detected browser.
367
- */
368
- getRecommendations: () => {
369
- title: string;
370
- message: string;
371
- recommendations: string[];
372
- critical: boolean;
373
- };
374
- /**
375
- * Checks if the current browser is compatible with the application.
376
- */
377
- isBrowserCompatible: () => boolean;
378
- /**
379
- * Checks if the browser is Internet Explorer.
380
- */
381
- isInternetExplorer: () => boolean;
382
- /**
383
- * Checks if the browser is iOS Safari.
384
- */
385
- isIOSSafari: () => boolean;
386
- /**
387
- * Checks if the browser is a legacy version that needs updating.
388
- */
389
- isLegacyBrowser: () => boolean;
390
- /**
391
- * Checks if the browser is an old version of Safari.
392
- */
393
- isOldSafari: () => boolean;
394
- };