@jsb188/app 1.1.5 → 1.1.6

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/utils/object.ts CHANGED
@@ -29,16 +29,17 @@ export function uniq(arr: Array<any>, fn?: (value: any, index: number, self: Arr
29
29
  * Remove undefined (and/or null) values from an object
30
30
  */
31
31
 
32
- export function removeUndefined<T>(obj: T, removeNull?: boolean) {
32
+ export function removeUndefined<T>(obj: T, removeNull?: boolean, removeFalsy?: boolean): T {
33
33
  for (const key in obj) {
34
34
  if (Object.prototype.hasOwnProperty.call(obj, key)) {
35
35
  if (
36
36
  obj[key] === undefined ||
37
- (removeNull && obj[key] === null)
37
+ (removeNull && obj[key] === null) ||
38
+ (removeFalsy && !obj[key])
38
39
  ) {
39
40
  delete obj[key];
40
41
  } else if (obj[key] && typeof obj[key] === 'object') {
41
- removeUndefined(obj[key], removeNull);
42
+ removeUndefined(obj[key], removeNull, removeFalsy);
42
43
  }
43
44
  }
44
45
  }
@@ -78,6 +79,19 @@ export function parseJSON(jsonStr?: string) {
78
79
  return null;
79
80
  }
80
81
 
82
+ /**
83
+ * Stringify JSON objects with BigInt support
84
+ * NOTE: This will work recursively for nested objects as well.
85
+ */
86
+
87
+ export function stringifyJSON(obj: any, convertBigIntToNumber: boolean = false): string {
88
+ if (!convertBigIntToNumber) {
89
+ return JSON.stringify(obj, (_key, value) => typeof value === 'bigint' ? Number(value) : value);
90
+ }
91
+
92
+ return JSON.stringify(obj, (_key, value) => typeof value === 'bigint' ? value.toString() : value);
93
+ }
94
+
81
95
  /**
82
96
  * Merge nested objects together
83
97
  */
@@ -113,9 +127,7 @@ export function areObjectsEqual(
113
127
  if (isNested) {
114
128
  return JSON.stringify(obj1) === JSON.stringify(obj2);
115
129
  } else if (obj1 && obj2) {
116
- return Object.keys(obj1).every((key: string) =>
117
- Object.prototype.hasOwnProperty.call(obj2, key) && obj1[key] === obj2[key]
118
- );
130
+ return Object.keys(obj1).every((key: string) => Object.prototype.hasOwnProperty.call(obj2, key) && obj1[key] === obj2[key]);
119
131
  }
120
132
  return obj1 === obj2;
121
133
  }
@@ -280,22 +292,68 @@ export function intersection(arr1: Array<any>, arr2: Array<any>) {
280
292
  */
281
293
 
282
294
  export function groupCollections(
283
- collections: Array<any>,
295
+ collections_: Array<any>,
284
296
  innerCollectionNames: string[],
285
297
  innerCollectionDefaultValues: Record<string, any> = {},
286
- primaryKeyName = 'id',
298
+ primaryKey: string | ((o: any) => string) = 'id',
299
+ isTest?: boolean,
287
300
  ): any[] {
288
- return collections.reduce((acc, obj) => {
301
+ let hasHash = false;
302
+ let primaryKeyName;
303
+ let collections = collections_;
304
+
305
+ if (typeof primaryKey === 'function') {
306
+ primaryKeyName = '__primaryKey';
307
+ collections = collections_.map((obj) => ({
308
+ ...obj,
309
+ __primaryKey: primaryKey(obj),
310
+ }));
311
+ } else {
312
+ primaryKeyName = primaryKey;
313
+ }
314
+
315
+ const groupedCollections = collections.reduce((acc, obj) => {
289
316
  const primaryKey = obj[primaryKeyName];
290
317
  const i = acc.findIndex((o: any) => o[primaryKeyName] === primaryKey);
291
318
 
292
319
  if (i === -1) {
320
+ // Map everything without hash first (inner array collections)
293
321
  innerCollectionNames.forEach((name: string) => {
294
322
  const defaultValue = innerCollectionDefaultValues[name] || [];
323
+ const [, afterHash] = name.split('.#.');
324
+
325
+ if (afterHash) {
326
+ // This is a merged array collection
327
+ // This mapping is handled separately after first merge
328
+ // const beforeHashObj = getObject(obj, beforeHash);
329
+ // console.log('beforeHashObj:', beforeHash, beforeHashObj);
330
+ // name = `${beforeHash}.1.${afterHash ? `${afterHash}` : ''}`;
331
+ hasHash = true;
332
+ return;
333
+ }
334
+
295
335
  const ref = getObject(obj, name);
296
336
 
337
+ // if (isTest) {
338
+ // console.log('name', name);
339
+ // console.log('ref', ref);
340
+ // console.log('ref', obj);
341
+ // }
342
+
297
343
  if (ref) {
298
- setObject(obj, name, Array.isArray(defaultValue) ? [ref] : ref);
344
+ let isNull = true;
345
+ for (const key in ref) {
346
+ if (!key.startsWith('__') && ref[key] !== null) {
347
+ isNull = false;
348
+ break;
349
+ }
350
+ }
351
+
352
+ if (!isNull) {
353
+ setObject(obj, name, Array.isArray(defaultValue) ? [ref] : ref);
354
+ } else {
355
+ setObject(obj, name, defaultValue);
356
+ }
299
357
  } else {
300
358
  setObject(obj, name, defaultValue);
301
359
  }
@@ -312,12 +370,30 @@ export function groupCollections(
312
370
  } else {
313
371
  innerCollectionNames.forEach((name: string) => {
314
372
  const defaultValue = innerCollectionDefaultValues[name] || [];
373
+ const [, afterHash] = name.split('.#.');
374
+
375
+ if (afterHash) {
376
+ // This is a merged array collection
377
+ // This mapping is handled separately after first merge
378
+ // const beforeHashObj = getObject(obj, beforeHash);
379
+ // console.log('beforeHashObj:', beforeHash, beforeHashObj);
380
+ // name = `${beforeHash}.1.${afterHash ? `${afterHash}` : ''}`;
381
+ hasHash = true;
382
+ return;
383
+ }
384
+
315
385
  const innerObj = getObject(obj, name);
316
386
  const ref = getObject(acc[i], name);
317
387
 
318
388
  if (!ref) {
319
389
  setObject(acc[i], name, innerObj && Array.isArray(innerObj) ? [innerObj] : (innerObj || defaultValue));
320
- } else if (innerObj && !ref.find((o: any) => o.id === innerObj.id)) {
390
+ } else if (
391
+ innerObj &&
392
+ !ref.find((o: any) =>
393
+ (o.id && o.id === innerObj.id) ||
394
+ (!o.id && Object.entries(o).flat().join('|') === Object.entries(innerObj).flat().join('|'))
395
+ )
396
+ ) {
321
397
  setObject(acc[i], name, Array.isArray(ref) ? ref.concat(innerObj) : innerObj);
322
398
  }
323
399
 
@@ -333,6 +409,78 @@ export function groupCollections(
333
409
 
334
410
  return acc;
335
411
  }, []);
412
+
413
+ if (!hasHash) {
414
+ return groupedCollections;
415
+ }
416
+
417
+ innerCollectionNames.forEach((name: string) => {
418
+ const [beforeHash, afterHash] = name.split('.#.');
419
+ if (!afterHash) {
420
+ return;
421
+ }
422
+
423
+ const flatName = name.replace('.#.', '.');
424
+
425
+ collections.forEach((obj) => {
426
+ const innerObj = getObject(obj, flatName);
427
+ const primaryKey = obj[primaryKeyName];
428
+ const i = groupedCollections.findIndex((o: any) => o[primaryKeyName] === primaryKey);
429
+ const innerParent = getObject(obj, beforeHash);
430
+ const innerParentId = innerParent?.[primaryKeyName];
431
+
432
+ if (!innerObj) {
433
+ return;
434
+ }
435
+
436
+ if (innerParentId && i >= 0) {
437
+ const innerArr = getObject(groupedCollections[i], beforeHash) || [];
438
+ const j = innerArr.findIndex((o: any) => o[primaryKeyName] === innerParentId);
439
+
440
+ if (j >= 0) {
441
+ const currentValue = innerArr[j][afterHash];
442
+ const currentValueIsArray = Array.isArray(currentValue);
443
+ const actualPathName = `${beforeHash}.${j}.${afterHash}`;
444
+
445
+ let newValue;
446
+ if (currentValueIsArray) {
447
+ if (!currentValue.find((o) => o.id === innerObj.id)) {
448
+ newValue = currentValue.concat(innerObj);
449
+ }
450
+ } else if (currentValue && currentValue.id !== innerObj.id) {
451
+ newValue = [currentValue].concat(innerObj);
452
+ } else if (!currentValue) {
453
+ newValue = [innerObj];
454
+ } else if (!currentValueIsArray) {
455
+ newValue = [currentValue];
456
+ }
457
+
458
+ if (newValue) {
459
+ setObject(groupedCollections[i], actualPathName, newValue);
460
+ }
461
+ }
462
+ }
463
+ });
464
+
465
+ collections.forEach((obj) => {
466
+ const innerParent = getObject(obj, beforeHash);
467
+
468
+ if (Array.isArray(innerParent)) {
469
+ innerParent.forEach((obj: any) => {
470
+ const innerParentObj = getObject(obj, afterHash);
471
+ if (innerParentObj) {
472
+ if (Array.isArray(innerParentObj)) {
473
+ setObject(obj, afterHash, uniqBy(innerParentObj, primaryKeyName));
474
+ } else {
475
+ setObject(obj, afterHash, [innerParentObj]);
476
+ }
477
+ }
478
+ });
479
+ }
480
+ });
481
+ });
482
+
483
+ return groupedCollections;
336
484
  }
337
485
 
338
486
  /**
package/utils/string.ts CHANGED
@@ -1,7 +1,5 @@
1
- const NOT_ALLOWED_USERNAMES = [
2
- 'ai',
3
- 'kajiwoto',
4
- ];
1
+ import i18n from '@jsb188/app/i18n';
2
+ import type { AddressObj } from '../types/other.d';
5
3
 
6
4
  /**
7
5
  * Combine list of class names
@@ -72,8 +70,8 @@ export function guessFirstName(str: string, len: number = 40): string {
72
70
  export function isEmail(str: string) {
73
71
  // return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str);
74
72
  const emailRegex =
75
- /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
76
- return emailRegex.test(str.trim());
73
+ /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i;
74
+ return !!str && emailRegex.test(str.trim());
77
75
  }
78
76
 
79
77
  /**
@@ -89,7 +87,7 @@ export function convertToInternationalPhone(str: string) {
89
87
  }
90
88
 
91
89
  const digits = str.replace(/[^0-9]/g, '');
92
- if (digits.startsWith('0')) {
90
+ if (!digits || digits.startsWith('0')) {
93
91
  // Invalid
94
92
  return null;
95
93
  } else if (
@@ -120,18 +118,6 @@ export function isPhone(str: string, doNotConvertInternational: boolean = false)
120
118
  return /^\+[0-9]{7,15}$/.test(phoneNumber);
121
119
  }
122
120
 
123
- /**
124
- * Check if valid username
125
- */
126
-
127
- export function isValidUsername(str: string) {
128
- const username = str.replace(/^@/, '').toLowerCase();
129
- return (
130
- /^[a-z0-9_]+$/i.test(username) &&
131
- !NOT_ALLOWED_USERNAMES.includes(username)
132
- );
133
- }
134
-
135
121
  /**
136
122
  * Check if password is secure enough
137
123
  * Rules:
@@ -267,10 +253,25 @@ export function isInvisibleString(str: string) {
267
253
  * NOTE: Userful for building AI prompts
268
254
  */
269
255
 
270
- export function buildSingleText(lines: (string | undefined | false | null)[], delemiter: string = '\n') {
256
+ type AnyLineItem = string | undefined | false | null;
257
+
258
+ export function buildSingleText(
259
+ lines: (AnyLineItem | Record<string, AnyLineItem[]>)[],
260
+ delemiter: string = '\n',
261
+ features: string[] = [],
262
+ ) {
271
263
  return lines
272
264
  .reduce((acc, line_) => {
273
265
  const line = line_ || '';
266
+ if (line && typeof line === 'object') {
267
+ for (const key in line) {
268
+ const lineItem = line[key];
269
+ if (features.includes(key)) {
270
+ acc.push(buildSingleText(lineItem, delemiter, features));
271
+ }
272
+ }
273
+ return acc;
274
+ }
274
275
  if (line || acc[acc.length - 1] !== '') {
275
276
  acc.push(line);
276
277
  }
@@ -295,7 +296,7 @@ export function joinReadable(
295
296
  lastSeparator: string = ' and ',
296
297
  ) {
297
298
  const lastIx = texts.length - 1;
298
- return texts.reduce((acc, text, i) => {
299
+ return texts.filter(Boolean).reduce((acc, text, i) => {
299
300
  return acc + (!acc ? '' : i === lastIx ? lastSeparator : separator) + text;
300
301
  }, '');
301
302
  }
@@ -351,10 +352,10 @@ export function removeGeneratedTextGarbage(str: string) {
351
352
  */
352
353
 
353
354
  export function escapeCSVValue(value: string): string {
354
- if (/[",\n]/.test(value)) {
355
- return `"${value.replace(/"/g, '""')}"`;
356
- }
357
- return value;
355
+ if (/[",\n]/.test(value)) {
356
+ return `"${value.replace(/"/g, '""')}"`;
357
+ }
358
+ return value;
358
359
  }
359
360
 
360
361
  /**
@@ -362,14 +363,144 @@ export function escapeCSVValue(value: string): string {
362
363
  * Example: "+1 (555) 123-4567"
363
364
  */
364
365
 
365
- export function formatPhoneNumber(phone: string): string {
366
- const match = phone.match(/(\d{3})(\d{3})(\d{4})$/);
367
- if (match) {
368
- const [, area, first, second] = match;
369
- const countryCode = phone.substring(0, phone.length - area.length - first.length - second.length);
370
- // NOTE: This does not account for non North American (+1) phone numbers
371
- return `${countryCode} (${area}) ${first}-${second}`;
372
- }
366
+ export function formatPhoneNumber(phone?: string | null) {
367
+ const match = phone?.match(/(\d{3})(\d{3})(\d{4})$/);
368
+ if (match) {
369
+ const [, area, first, second] = match;
370
+ const countryCode = phone!.substring(0, phone.length - area.length - first.length - second.length);
371
+ // NOTE: This does not account for non North American (+1) phone numbers
372
+ return `${countryCode} (${area}) ${first}-${second}`;
373
+ }
374
+
375
+ return phone;
376
+ }
377
+
378
+ /**
379
+ * Split a long text into chunks, making sure each chunk is under the chunk size character limit.
380
+ * @param text - The long text to split.
381
+ * @param chunkSize - The maximum number of characters allowed in each chunk.
382
+ * @param linebreakDistance - The maximum distance from the chunk boundary to look for a line break.
383
+ * @returns An array of text chunks.
384
+ */
385
+
386
+ export function splitTextIntoChunks(text: string, chunkSize: number, linebreakDistance: number = 50): string[] {
387
+ if (!text || chunkSize <= 0 || text.length < chunkSize) {
388
+ return [text || ''];
389
+ }
390
+
391
+ const chunks: string[] = [];
392
+ let start = 0;
393
+
394
+ while (start < text.length) {
395
+ let end = Math.min(start + chunkSize, text.length);
396
+
397
+ if (end < text.length) {
398
+ // Find the nearest line break around the target chunk boundary
399
+ const beforeBreak = text.lastIndexOf('\n', end);
400
+
401
+ let chosenBreak = -1;
402
+ if (beforeBreak !== -1 && end - beforeBreak <= linebreakDistance && beforeBreak > start) {
403
+ chosenBreak = beforeBreak + 1;
404
+ }
405
+
406
+ if (chosenBreak !== -1) {
407
+ end = chosenBreak;
408
+ } else {
409
+ // Fall back to last whitespace near the end
410
+ const lastSpace = text.lastIndexOf(' ', end);
411
+ if (lastSpace > start && end - lastSpace < 100) {
412
+ end = lastSpace;
413
+ }
414
+ }
415
+ }
416
+
417
+ const chunk = text.slice(start, end).trim();
418
+ if (chunk) chunks.push(chunk);
419
+ start = end;
420
+ }
421
+
422
+ return chunks;
423
+ }
424
+
425
+ /**
426
+ * Format reference number
427
+ */
428
+
429
+ export function formatReferenceNumber(idStr: string) {
430
+ if (idStr && /^\d+$/.test(idStr)) {
431
+ return '#' + idStr;
432
+ }
433
+ return idStr;
434
+ }
435
+
436
+ /**
437
+ * Get "nth" string for a number
438
+ * @param num - The number to convert
439
+ * @returns The number with its ordinal suffix (e.g., "1st", "2nd", "3rd", "4th")
440
+ */
441
+
442
+ export function getNthString(num: number): string {
443
+ const mod10 = num % 10;
444
+ const mod100 = num % 100;
445
+
446
+ if (mod10 === 1 && mod100 !== 11) {
447
+ return `${num}st`;
448
+ } else if (mod10 === 2 && mod100 !== 12) {
449
+ return `${num}nd`;
450
+ } else if (mod10 === 3 && mod100 !== 13) {
451
+ return `${num}rd`;
452
+ } else {
453
+ return `${num}th`;
454
+ }
455
+ }
456
+
457
+ /**
458
+ * Make address text
459
+ * @param address - Address object
460
+ * @param useFullCountryName - Whether to use full country name instead of code
461
+ * @param regionOnly - Whether to return only region (city, state, country)
462
+ * @returns Formatted address string
463
+ */
464
+
465
+ export function makeAddressText(
466
+ address: Partial<AddressObj>,
467
+ format: 'REGION_ONLY' | 'SINGLE_LINE' | 'NORMAL' = 'NORMAL',
468
+ useFullCountryName: boolean = false,
469
+ delimiter: string = ', ',
470
+ ) {
471
+ if (!address) {
472
+ return null;
473
+ }
474
+
475
+ const countryName = useFullCountryName && i18n.has(`country.from_code.${address.country}`)
476
+ ? i18n.t(`country.from_code.${address.country}`)
477
+ : address.country;
478
+
479
+ if (format === 'REGION_ONLY') {
480
+ return [
481
+ address.city,
482
+ address.state,
483
+ countryName,
484
+ ].filter(Boolean).join(delimiter);
485
+ } else if (format === 'SINGLE_LINE') {
486
+ return [
487
+ address.line1,
488
+ address.line2,
489
+ address.city,
490
+ address.state,
491
+ address.postalCode,
492
+ countryName,
493
+ ].filter(Boolean).join(delimiter);
494
+ }
373
495
 
374
- return phone;
496
+ // NORMAL format
497
+ return [
498
+ address.line1,
499
+ address.line2,
500
+ [
501
+ [address.city, address.state].filter(Boolean).join(', '),
502
+ address.postalCode,
503
+ ].filter(Boolean).join(' '),
504
+ countryName,
505
+ ].filter(Boolean).join('\n');
375
506
  }
package/utils/timeZone.ts CHANGED
@@ -2353,14 +2353,14 @@ export function parseDateInTimezone(
2353
2353
  input: Date | string,
2354
2354
  tz?: string | null,
2355
2355
  addDay?: number, // Use this for start/end of day
2356
- isISODate?: boolean, // If true, input is assumed to be ISO Date without any checks
2356
+ isISODate?: boolean, // If true, input is assumed to be ISO Date without any checks
2357
2357
  ): Date {
2358
2358
  const timeZone = tz || DEFAULT_TIMEZONE;
2359
2359
 
2360
2360
  let dt: DateTime;
2361
2361
 
2362
2362
  // If input is a string in "YYYY-MM-DD" format
2363
- if (typeof input === 'string' && (isISODate || /^\d{4}-\d{2}-\d{2}$/.test(input))) {
2363
+ if (typeof input === 'string' && (isISODate || /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{2}-\d{2}T\d{2}:\d{2})$/.test(input))) {
2364
2364
  dt = DateTime.fromISO(input, { zone: timeZone });
2365
2365
  } else if (typeof input === 'string') {
2366
2366
  dt = DateTime.fromJSDate(new Date(input), { zone: timeZone });
@@ -2376,6 +2376,42 @@ export function parseDateInTimezone(
2376
2376
  return dt.toJSDate();
2377
2377
  }
2378
2378
 
2379
+ /**
2380
+ * Parse date to start or end of day in time zone
2381
+ * @param input - Date object or string in "YYYY-MM-DD" format
2382
+ * @param tz - Timezone string (IANA format), defaults to DEFAULT_TIMEZONE
2383
+ * @param toEndOfDay - If true, set time to end of day (23:59:59.999), otherwise start of day (00:00:00.000)
2384
+ * @returns {Date} - Date object adjusted to the start or end of the day in the specified timezone
2385
+ */
2386
+
2387
+ export function parseBoundaryDateInTimezone(
2388
+ input: Date | string, // "YYYY-MM-DD" or "YYYY-MM-DDTHH:MM" format
2389
+ tz?: string | null,
2390
+ toEndOfDay?: boolean,
2391
+ ): Date {
2392
+ const timeZone = tz || DEFAULT_TIMEZONE;
2393
+
2394
+ let dt: DateTime;
2395
+
2396
+ // If input is a string in "YYYY-MM-DD" format
2397
+ if (typeof input === 'string' && /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{2}-\d{2}T\d{2}:\d{2})$/.test(input)) {
2398
+ dt = DateTime.fromISO(input, { zone: timeZone });
2399
+ } else if (typeof input === 'string') {
2400
+ dt = DateTime.fromJSDate(new Date(input), { zone: timeZone });
2401
+ } else {
2402
+ dt = DateTime.fromJSDate(input, { zone: timeZone });
2403
+ }
2404
+
2405
+ // Set time to start or end of day
2406
+ if (toEndOfDay) {
2407
+ dt = dt.endOf('day');
2408
+ } else {
2409
+ dt = dt.startOf('day');
2410
+ }
2411
+
2412
+ return dt.toJSDate();
2413
+ }
2414
+
2379
2415
  /**
2380
2416
  * Get the index of timzeone from TIMEZONES_LIST
2381
2417
  * @param tz - Timezone string (IANA format)
@@ -2418,15 +2454,134 @@ export function indexToTimeZone(index?: number | string | null): string | null {
2418
2454
  */
2419
2455
 
2420
2456
  export function getTimeZoneCode(tz?: string | null, useSystem?: boolean): string | null {
2421
- try {
2422
- if (tz) {
2423
- return DateTime.now().setZone(tz).toFormat('ZZZZ');
2424
- } else if (useSystem) {
2425
- // IMPORTANT: If you do this in server, this will always return UTC
2426
- return DateTime.now().toFormat('ZZZZ');
2427
- }
2428
- } catch (e) {
2429
- console.warn('Invalid timezone:', tz, e);
2430
- }
2431
- return null;
2457
+ try {
2458
+ if (tz) {
2459
+ return DateTime.now().setZone(tz).toFormat('ZZZZ');
2460
+ } else if (useSystem) {
2461
+ // IMPORTANT: If you do this in server, this will always return UTC
2462
+ return DateTime.now().toFormat('ZZZZ');
2463
+ }
2464
+ } catch (e) {
2465
+ console.warn('Invalid timezone:', tz, e);
2466
+ }
2467
+ return null;
2432
2468
  }
2469
+
2470
+ /**
2471
+ * Check if time zone is currently in daylight saving time, and get the time difference
2472
+ * @param tz - Timezone string (IANA format)
2473
+ * @param d - DateTime object representing the current time in the specified timezone
2474
+ * @returns { timeZone: string, isDST: boolean; offset: number, shiftHours: number } | null
2475
+ */
2476
+
2477
+ export function getDayLightSavingsInfo(tz: string, d?: Date) {
2478
+ let now;
2479
+ if (d) {
2480
+ now = DateTime.fromJSDate(d).setZone(tz);
2481
+ } else {
2482
+ now = DateTime.now().setZone(tz);
2483
+ }
2484
+
2485
+ const jan = DateTime.fromObject({ year: now.year, month: 1, day: 1 }).setZone(tz);
2486
+ const offsetShift = (jan.offset - now.offset) / 60;
2487
+
2488
+ return {
2489
+ timeZone: tz,
2490
+ isDST: now.isInDST, // true if currently observing DST
2491
+ offset: now.offset / 60, // offset from UTC in hours
2492
+ offsetShift, // hours
2493
+ };
2494
+ }
2495
+
2496
+ /**
2497
+ * Get time in time zone
2498
+ * @param hhmmStr - Time string in "HHMM" format
2499
+ * @param date - Date object or date string to extract time from if hhmmStr is not provided
2500
+ * @param addAMPM - If true, return time in "HH:MM AM/PM" format, otherwise "HH:MM" format
2501
+ * @param timeZone - Timezone string (IANA format), defaults to DEFAULT_TIMEZONE
2502
+ * @returns {string} - Formatted time string
2503
+ */
2504
+
2505
+ export function hhmmFromDateOrTime(
2506
+ hhmmStr: string | number | null,
2507
+ dVal: Date | string | null,
2508
+ addAMPM: boolean,
2509
+ timeZone?: string | null,
2510
+ ): string {
2511
+ let hhmm: string = '';
2512
+ if (hhmmStr && /^[0-9]{3,4}$/.test(String(hhmmStr))) {
2513
+ hhmm = String(hhmmStr);
2514
+ } else if (dVal) {
2515
+ let date;
2516
+ if (typeof dVal === 'string') {
2517
+ date = new Date(dVal);
2518
+ } else {
2519
+ date = dVal;
2520
+ }
2521
+
2522
+ const luxonDate = DateTime.fromJSDate(date).setZone(timeZone || DEFAULT_TIMEZONE);
2523
+ hhmm = String(luxonDate.hour * 100 + luxonDate.minute).padStart(4, '0');
2524
+ }
2525
+
2526
+ let hh, mm;
2527
+ if (hhmm.length === 4) {
2528
+ hh = hhmm.slice(0, 2);
2529
+ mm = hhmm.slice(2, 4);
2530
+ } else if (hhmm.length === 3) {
2531
+ hh = hhmm.slice(0, 1);
2532
+ mm = hhmm.slice(1, 3);
2533
+ }
2534
+
2535
+ if (hh) {
2536
+ if (addAMPM) {
2537
+ const hourNum = parseInt(hh, 10);
2538
+ const ampm = hourNum >= 12 ? 'PM' : 'AM';
2539
+ const hour12 = hourNum % 12 === 0 ? 12 : hourNum % 12;
2540
+ return `${hour12}:${mm} ${ampm}`;
2541
+ }
2542
+ return `${hh}:${mm}`;
2543
+ }
2544
+
2545
+ return '';
2546
+ }
2547
+
2548
+ /**
2549
+ * Get date in time zone
2550
+ */
2551
+
2552
+ export function formatCalDateInTimeZone(date: Date, timeZone: string | null): string {
2553
+ const formatter = new Intl.DateTimeFormat('en-CA', {
2554
+ timeZone: timeZone ?? 'UTC',
2555
+ year: 'numeric',
2556
+ month: '2-digit',
2557
+ day: '2-digit',
2558
+ });
2559
+
2560
+ return formatter.format(date); // YYYY-MM-DD
2561
+ }
2562
+
2563
+ /**
2564
+ * Get day of week in time zone
2565
+ * @param date
2566
+ * @param timeZone
2567
+ * @returns
2568
+ */
2569
+
2570
+ export function getDayOfWeekInTimeZone(date: Date, timeZone: string | null): number {
2571
+ const formatter = new Intl.DateTimeFormat('en-US', {
2572
+ timeZone: timeZone ?? 'UTC',
2573
+ weekday: 'short',
2574
+ });
2575
+
2576
+ const day = formatter.format(date);
2577
+
2578
+ return {
2579
+ Sun: 0,
2580
+ Mon: 1,
2581
+ Tue: 2,
2582
+ Wed: 3,
2583
+ Thu: 4,
2584
+ Fri: 5,
2585
+ Sat: 6,
2586
+ }[day as 'Sun'];
2587
+ }
@@ -34,7 +34,7 @@ export function makeUploadsUrl(
34
34
  // Do size paths here
35
35
  }
36
36
 
37
- return 'https://assets.chiefhappiness.co/' + prefix + urlPath;
37
+ return 'https://assets.chiefhappiness.co/marketday/' + prefix + urlPath;
38
38
  }
39
39
 
40
40
  /**