@magmacomputing/tempo 1.0.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.
Files changed (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +61 -0
  3. package/dist/array.library.d.ts +25 -0
  4. package/dist/array.library.js +78 -0
  5. package/dist/buffer.library.d.ts +6 -0
  6. package/dist/buffer.library.js +192 -0
  7. package/dist/cipher.class.d.ts +18 -0
  8. package/dist/cipher.class.js +65 -0
  9. package/dist/class.library.d.ts +10 -0
  10. package/dist/class.library.js +57 -0
  11. package/dist/coercion.library.d.ts +14 -0
  12. package/dist/coercion.library.js +71 -0
  13. package/dist/enumerate.library.d.ts +64 -0
  14. package/dist/enumerate.library.js +54 -0
  15. package/dist/function.library.d.ts +9 -0
  16. package/dist/function.library.js +49 -0
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.js +3 -0
  19. package/dist/logify.class.d.ts +33 -0
  20. package/dist/logify.class.js +53 -0
  21. package/dist/number.library.d.ts +16 -0
  22. package/dist/number.library.js +36 -0
  23. package/dist/object.library.d.ts +37 -0
  24. package/dist/object.library.js +94 -0
  25. package/dist/pledge.class.d.ts +54 -0
  26. package/dist/pledge.class.js +131 -0
  27. package/dist/prototype.library.d.ts +33 -0
  28. package/dist/prototype.library.js +51 -0
  29. package/dist/reflection.library.d.ts +74 -0
  30. package/dist/reflection.library.js +97 -0
  31. package/dist/serialize.library.d.ts +25 -0
  32. package/dist/serialize.library.js +266 -0
  33. package/dist/storage.library.d.ts +8 -0
  34. package/dist/storage.library.js +57 -0
  35. package/dist/string.library.d.ts +37 -0
  36. package/dist/string.library.js +93 -0
  37. package/dist/tempo.class.d.ts +556 -0
  38. package/dist/tempo.class.js +1412 -0
  39. package/dist/tempo.config/plugins/term.import.d.ts +42 -0
  40. package/dist/tempo.config/plugins/term.import.js +44 -0
  41. package/dist/tempo.config/plugins/term.quarter.d.ts +7 -0
  42. package/dist/tempo.config/plugins/term.quarter.js +28 -0
  43. package/dist/tempo.config/plugins/term.season.d.ts +7 -0
  44. package/dist/tempo.config/plugins/term.season.js +36 -0
  45. package/dist/tempo.config/plugins/term.timeline.d.ts +7 -0
  46. package/dist/tempo.config/plugins/term.timeline.js +19 -0
  47. package/dist/tempo.config/plugins/term.utils.d.ts +17 -0
  48. package/dist/tempo.config/plugins/term.utils.js +38 -0
  49. package/dist/tempo.config/plugins/term.zodiac.d.ts +7 -0
  50. package/dist/tempo.config/plugins/term.zodiac.js +62 -0
  51. package/dist/tempo.config/tempo.default.d.ts +169 -0
  52. package/dist/tempo.config/tempo.default.js +158 -0
  53. package/dist/tempo.config/tempo.enum.d.ts +99 -0
  54. package/dist/tempo.config/tempo.enum.js +78 -0
  55. package/dist/temporal.polyfill.d.ts +9 -0
  56. package/dist/temporal.polyfill.js +18 -0
  57. package/dist/type.library.d.ts +296 -0
  58. package/dist/type.library.js +80 -0
  59. package/dist/utility.library.d.ts +32 -0
  60. package/dist/utility.library.js +54 -0
  61. package/package.json +54 -0
@@ -0,0 +1,296 @@
1
+ import { Tempo } from './tempo.class.js';
2
+ import { Pledge } from './pledge.class.js';
3
+ import type { Enum } from './enumerate.library.js';
4
+ /**
5
+ * return an object's type as a ProperCase string.
6
+ * if instance, return Class name
7
+ */
8
+ export declare const getType: (obj?: any, ...instances: Instance[]) => Type;
9
+ /** return TypeValue<T> object */
10
+ export declare const asType: <T>(value?: T, ...instances: Instance[]) => TypeValue<T>;
11
+ /** assert value is one of a list of Types */
12
+ export declare const isType: <T>(obj: unknown, ...types: Type[]) => obj is T;
13
+ /** Type-Guards: assert \<obj> is of \<type> */
14
+ export declare const isPrimitive: (obj?: unknown) => obj is Primitive;
15
+ export declare const isReference: (obj?: unknown) => obj is Object;
16
+ export declare const isIterable: <T>(obj: unknown) => obj is Iterable<T>;
17
+ export declare const isString: <T>(obj?: T) => obj is Extract<T, string>;
18
+ export declare const isNumber: <T>(obj?: T) => obj is Extract<T, number>;
19
+ export declare const isInteger: <T>(obj?: T) => obj is Extract<T, bigint>;
20
+ export declare const isIntegerLike: <T>(obj?: T) => obj is Extract<T, string>;
21
+ export declare const isDigit: <T>(obj?: T) => obj is Extract<T, number | bigint>;
22
+ export declare const isBoolean: <T>(obj?: T) => obj is Extract<T, boolean>;
23
+ export declare const isArray: <T>(obj: unknown) => obj is T[];
24
+ export declare const isArrayLike: <T>(obj: any) => obj is ArrayLike<T>;
25
+ export declare const isObject: <T>(obj?: T) => obj is Extract<T, object>;
26
+ export declare const isDate: <T>(obj?: T) => obj is Extract<T, Date>;
27
+ export declare const isRegExp: <T>(obj?: T) => obj is Extract<T, RegExp>;
28
+ export declare const isRegExpLike: <T>(obj?: T) => obj is Extract<T, string>;
29
+ export declare const isSymbol: <T>(obj?: T) => obj is Extract<T, symbol>;
30
+ export declare const isSymbolFor: <T>(obj?: T) => obj is Extract<T, symbol>;
31
+ export declare const isPropertyKey: (obj?: unknown) => obj is PropertyKey;
32
+ export declare const isNull: <T>(obj?: T) => obj is Extract<T, null>;
33
+ export declare const isNullish: <T>(obj: T) => obj is Extract<T, Nullish>;
34
+ export declare const isUndefined: <T>(obj?: T) => obj is undefined;
35
+ export declare const isDefined: <T>(obj: T) => obj is NonNullable<T>;
36
+ export declare const isClass: <T>(obj?: T) => obj is Extract<T, Function>;
37
+ export declare const isFunction: (obj?: any) => obj is Function;
38
+ export declare const isPromise: <T>(obj?: T) => obj is Extract<T, Promise<any>>;
39
+ export declare const isMap: <K, V>(obj?: unknown) => obj is Map<K, V>;
40
+ export declare const isSet: <K>(obj?: unknown) => obj is Set<K>;
41
+ export declare const isError: (err: unknown) => err is Error;
42
+ export declare const isTemporal: <T>(obj: T) => obj is Extract<T, Temporals>;
43
+ export declare const isTempo: (obj: unknown) => obj is Tempo;
44
+ export declare const isEnum: <E extends Property<any>>(obj: unknown) => obj is Enum.props<E>;
45
+ export declare const isPledge: <P>(obj: unknown) => obj is Pledge<P>;
46
+ export declare const nullToZero: <T>(obj: T) => 0 | NonNullable<T>;
47
+ export declare const nullToEmpty: <T>(obj: T) => "" | NonNullable<T>;
48
+ export declare const nullToValue: <T, R>(obj: T, value: R) => R | NonNullable<T>;
49
+ /** object has no values */
50
+ export declare const isEmpty: <T>(obj?: T) => boolean;
51
+ export declare function assertCondition(condition: boolean, message?: string): asserts condition;
52
+ export declare function assertString(str: unknown): asserts str is string;
53
+ export declare function assertNever(val: never): asserts val is never;
54
+ /** infer T of a <T | T[]> */ export type TValue<T> = T extends Array<infer A> ? A : NonNullable<T>;
55
+ /** cast <T | undefined> as <T | T[]> */ export type TValues<T> = TValue<T> | Array<TValue<T>> | Extract<T, undefined>;
56
+ /** cast <T | T[]> as T[] */ export type TArray<T> = Array<TValue<T>>;
57
+ /** bottom value */ export type Nullish = null | undefined | void;
58
+ /** Generic Record */ export type Property<T> = Record<PropertyKey, T>;
59
+ /** Generic Record or Array */ export type Obj = Property<any> | Array<any>;
60
+ export type WellKnownSymbols = {
61
+ [K in keyof SymbolConstructor]: SymbolConstructor[K] extends symbol ? SymbolConstructor[K] : never;
62
+ }[keyof SymbolConstructor];
63
+ type SafeCount<T, Acc extends any[] = [], Last = LastInUnion<T>> = Acc['length'] extends 1000 ? number : 0 extends (1 & T) ? number : [
64
+ T
65
+ ] extends [never] ? Acc['length'] : SafeCount<Exclude<T, Last>, [...Acc, any]>;
66
+ /** Own properties of an Array, Object, Map or Enum */
67
+ type IgnoreOf = WellKnownSymbols | Enum.methods;
68
+ export type CountOf<T> = SafeCount<T>;
69
+ export type OwnOf<T extends Obj> = T extends Array<any> ? {
70
+ [K in number]: T[number];
71
+ } : Omit<T, IgnoreOf>;
72
+ export type KeyOf<T extends Obj> = T extends Array<any> ? number : Exclude<Extract<keyof T, PropertyKey>, IgnoreOf>;
73
+ export type ValueOf<T extends Obj> = T extends Array<any> ? T[number] : T[KeyOf<T>];
74
+ export type EntryOf<T extends Obj> = [KeyOf<T>, ValueOf<T>];
75
+ /** extracts only the Literal string keys (not index signatures) from an object/interface */
76
+ export type LiteralKey<T> = {
77
+ [K in keyof T]: string extends K ? never : K;
78
+ }[keyof T] & string;
79
+ /** mark some fields as Optional */
80
+ export type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
81
+ /** Remove 'optional' on keys as well as 'undefined' on values */
82
+ export type NonOptional<T> = {
83
+ [K in keyof T]-?: Exclude<T[K], undefined>;
84
+ };
85
+ /** Record with only one-key */
86
+ export type OneKey<K extends keyof any, V, KK extends keyof any = K> = {
87
+ [P in K]: {
88
+ [Q in P]: V;
89
+ } & {
90
+ [Q in Exclude<KK, P>]?: undefined;
91
+ } extends infer O ? {
92
+ [Q in keyof O]: O[Q];
93
+ } : never;
94
+ }[K];
95
+ export type Prettify<T> = {
96
+ [K in keyof T]: T[K];
97
+ } & {};
98
+ export type ParseInt<T> = T extends `${infer N extends number}` ? N : never;
99
+ export type TPlural<T extends string> = `${T}s`;
100
+ type toName<T extends Primitive> = T extends string ? "String" : T extends number ? "Number" : T extends bigint ? "BigInt" : T extends boolean ? "Boolean" : T extends symbol ? "Symbol" : T extends void ? "Void" : T extends undefined ? "Undefined" : T extends null ? "Null" : never;
101
+ type Primitive = string | number | bigint | boolean | symbol | void | undefined | null;
102
+ export type Primitives = toName<Primitive>;
103
+ /** Generic constructor type */
104
+ export type Constructor<T = any> = new (...args: any[]) => T;
105
+ type Instance = {
106
+ type: string;
107
+ class: Function;
108
+ };
109
+ declare const Temporal: any;
110
+ export type Temporals = typeof Temporal extends {
111
+ Now: any;
112
+ } ? Exclude<keyof typeof Temporal, 'Now'> : never;
113
+ export type Type = 'String' | 'Number' | 'BigInt' | 'Boolean' | 'Object' | 'Array' | 'ArrayLike' | 'Null' | 'Undefined' | 'Void' | 'Empty' | 'Date' | 'Function' | 'AsyncFunction' | 'Class' | 'Promise' | 'RegExp' | 'Blob' | 'Map' | 'Set' | 'WeakMap' | 'WeakSet' | 'WeakRef' | 'Symbol' | 'Error' | 'Temporal' | 'Temporal.Instant' | 'Temporal.ZonedDateTime' | 'Temporal.PlainDateTime' | 'Temporal.PlainDate' | 'Temporal.PlainTime' | 'Temporal.PlainYearMonth' | 'Temporal.PlainMonthDay' | 'Enumify' | 'Tempo' | 'Pledge';
114
+ export type TypeValue<T> = {
115
+ type: 'String';
116
+ value: string;
117
+ } | {
118
+ type: 'Number';
119
+ value: number;
120
+ } | {
121
+ type: 'BigInt';
122
+ value: bigint;
123
+ } | {
124
+ type: 'Boolean';
125
+ value: boolean;
126
+ } | {
127
+ type: 'Object';
128
+ value: Extract<T, Property<unknown>>;
129
+ } | {
130
+ type: 'Array';
131
+ value: Array<T>;
132
+ } | {
133
+ type: 'ArrayLike';
134
+ value: ArrayLike<T>;
135
+ } | {
136
+ type: 'Undefined';
137
+ value: undefined;
138
+ } | {
139
+ type: 'Null';
140
+ value: null;
141
+ } | {
142
+ type: 'Void';
143
+ value: void;
144
+ } | {
145
+ type: 'Empty';
146
+ value: unknown;
147
+ } | {
148
+ type: 'Date';
149
+ value: Date;
150
+ } | {
151
+ type: 'Function';
152
+ value: Function;
153
+ } | {
154
+ type: 'Class';
155
+ value: T;
156
+ } | {
157
+ type: 'Promise';
158
+ value: Promise<T>;
159
+ } | {
160
+ type: 'RegExp';
161
+ value: RegExp;
162
+ } | {
163
+ type: 'Blob';
164
+ value: Blob;
165
+ } | {
166
+ type: 'Map';
167
+ value: Map<any, T>;
168
+ } | {
169
+ type: 'Set';
170
+ value: Set<T>;
171
+ } | {
172
+ type: 'WeakSet';
173
+ value: WeakSet<Property<unknown>>;
174
+ } | {
175
+ type: 'WeakMap';
176
+ value: WeakMap<Property<unknown>, T>;
177
+ } | {
178
+ type: 'Symbol';
179
+ value: symbol;
180
+ } | {
181
+ type: 'Error';
182
+ value: Error;
183
+ } | {
184
+ type: 'Temporal';
185
+ value: Temporals;
186
+ } | {
187
+ type: 'Temporal.Instant';
188
+ value: Temporal.Instant;
189
+ } | {
190
+ type: 'Temporal.ZonedDateTime';
191
+ value: Temporal.ZonedDateTime;
192
+ } | {
193
+ type: 'Temporal.PlainDateTime';
194
+ value: Temporal.PlainDateTime;
195
+ } | {
196
+ type: 'Temporal.PlainDate';
197
+ value: Temporal.PlainDate;
198
+ } | {
199
+ type: 'Temporal.PlainTime';
200
+ value: Temporal.PlainTime;
201
+ } | {
202
+ type: 'Temporal.PlainYearMonth';
203
+ value: Temporal.PlainYearMonth;
204
+ } | {
205
+ type: 'Temporal.PlainMonthDay';
206
+ value: Temporal.PlainMonthDay;
207
+ } | {
208
+ type: 'Tempo';
209
+ value: Tempo;
210
+ } | {
211
+ type: 'Pledge';
212
+ value: Pledge<T>;
213
+ } | {
214
+ type: 'Enumify';
215
+ value: Enum.wrap<Property<any>>;
216
+ };
217
+ type TupleEntry<T extends readonly unknown[], I extends unknown[] = [], R = never> = T extends readonly [infer Head, ...infer Tail] ? TupleEntry<Tail, [...I, unknown], R | [`${I["length"]}`, Head]> : R;
218
+ type ObjectEntry<T extends Property<any>> = T extends object ? {
219
+ [K in keyof T]: [T[K]] extends [never] ? never : [K, Required<T>[K]];
220
+ }[keyof T] extends infer E ? E extends [infer K extends string | number, infer V] ? [`${K}`, V] : E extends [infer K extends symbol, infer V] ? [K, V] : never : never : never;
221
+ /** if T extends readonly[] => [number, T], if T extends {} => [key:string, T] */
222
+ export type Entry<T extends Property<any>> = T extends readonly [unknown, ...unknown[]] ? TupleEntry<T> : T extends ReadonlyArray<infer U> ? [`${number}`, U] : ObjectEntry<T>;
223
+ /** Object.entries<T> as [number,T][] */
224
+ export type Entries<T extends Property<T>> = ReadonlyArray<Entry<T>>;
225
+ /** invert key-value object */
226
+ export type Inverse<T> = {
227
+ [K in keyof T as (T[K] & PropertyKey)]: K;
228
+ };
229
+ /** assign array indexes as values in an object */
230
+ export type Index<T extends readonly any[]> = {
231
+ [K in Entry<T> as `${K[1]}`]: ParseInt<K[0]>;
232
+ };
233
+ /** reverse a Tuple */
234
+ export type Reverse<T extends any[], R extends any[] = []> = ReturnType<T extends [infer F, ...infer L] ? () => Reverse<L, [F, ...R]> : () => R>;
235
+ /** reverse a Record */
236
+ export type Invert<T extends Record<keyof T, keyof any>> = {
237
+ [K in keyof T as T[K]]: K;
238
+ };
239
+ type EnumerateMin<N extends number, Acc extends number[] = []> = Acc["length"] extends N ? Acc[number] : EnumerateMin<N, [...Acc, Acc["length"]]>;
240
+ type EnumerateMax<N extends number, Acc extends number[] = []> = Acc["length"] extends N ? ([...Acc, Acc["length"]])[number] : EnumerateMax<N, [...Acc, Acc["length"]]>;
241
+ /** declare expected range of values */
242
+ export type IntRange<Lower extends number, Upper extends number> = Exclude<EnumerateMax<Upper>, EnumerateMin<Lower>>;
243
+ declare const __brand: unique symbol;
244
+ type Brand<B> = {
245
+ [__brand]: B;
246
+ };
247
+ export type Branded<T, B> = T & Brand<B>;
248
+ export type EmptyObject = {
249
+ [__brand]?: never;
250
+ };
251
+ type Length<T extends string, Count extends number[] = []> = T extends `${string}${infer Tail}` ? Length<Tail, [...Count, 0]> : Count["length"];
252
+ type Compare<First extends number, Second extends number, Count extends number[] = []> = First extends Second ? 0 : Count["length"] extends First ? -1 : Count["length"] extends Second ? 1 : Compare<First, Second, [...Count, 0]>;
253
+ export type MaxLength<T extends string, Max extends number> = Compare<Length<T>, Max> extends -1 | 0 ? T : never;
254
+ export type MinLength<T extends string, Min extends number> = Compare<Min, Length<T>> extends -1 | 0 ? T : never;
255
+ export type InRange<T extends string, Min extends number, Max extends number> = MinLength<T, Min> & MaxLength<T, Max>;
256
+ /**
257
+ * return a substring of a string-type
258
+ * eg: Substr<Monday|Tuesday|Wednesday, 3> returns Mon|Tue|Wed
259
+ * U is the original string union
260
+ * Max is the number of chars to return
261
+ * Start is the offset (starting from '1')
262
+ */
263
+ export type Substring<U extends string, Max extends number, Start extends number = 1> = Substr<U, Max, Start>;
264
+ /**
265
+ * internal Type for Substring<> to recurse
266
+ * Str is the string to build and return
267
+ * Offset is an internal array used to assist with determining start-point of T
268
+ */
269
+ type Substr<U, Max, Start, Str extends string = '', Offset extends number[] = [0]> = U extends `${infer NextChar}${infer Rest}` ? Offset["length"] extends Start ? Length<Str> extends Max ? Str : Substr<Rest, Start, Max, `${Str}${NextChar}`, Offset> : Substr<Rest, Start, Max, Str, [...Offset, 0]> : Str;
270
+ type UnionToIntersection<U> = (U extends unknown ? (arg: U) => 0 : never) extends (arg: infer I) => 0 ? I : never;
271
+ type LastInUnion<U> = UnionToIntersection<U extends unknown ? (x: U) => 0 : never> extends (x: infer L) => 0 ? L : never;
272
+ /**
273
+ * convert a Union to a Tuple.
274
+ * usage: UnionToTuple<A | B> = [A, B]
275
+ */
276
+ export type UnionToTuple<T, Acc extends any[] = [], Last = LastInUnion<T>> = Acc['length'] extends 1000 ? T[] : [
277
+ T
278
+ ] extends [never] ? Acc : UnionToTuple<Exclude<T, Last>, [Last, ...Acc]>;
279
+ /** Deep Readonly object for type safety */
280
+ export type Secure<T> = T extends (infer R)[] ? SecureArray<R> : T extends Function ? T : T extends object ? SecureObject<T> : T;
281
+ export interface SecureArray<T> extends ReadonlyArray<Secure<T>> {
282
+ }
283
+ export type SecureObject<T> = {
284
+ readonly [K in keyof T]: Secure<T[K]>;
285
+ };
286
+ type LooseString = (string & {});
287
+ type LooseProperty = (PropertyKey & {});
288
+ /** Loose union */
289
+ export type LooseUnion<T extends string> = T | LooseString;
290
+ /** Loose property key */
291
+ export type LooseKey<K extends PropertyKey = string> = K | LooseProperty;
292
+ /** Extend an object with a generic-signature */
293
+ export type Extend<T, K extends PropertyKey = string, V = any> = T & {
294
+ [P in K]: V;
295
+ };
296
+ export {};
@@ -0,0 +1,80 @@
1
+ /** the primitive type reported by toStringTag() */
2
+ const protoType = (obj) => Object.prototype.toString.call(obj).slice(8, -1);
3
+ /**
4
+ * return an object's type as a ProperCase string.
5
+ * if instance, return Class name
6
+ */
7
+ export const getType = (obj, ...instances) => {
8
+ const type = protoType(obj);
9
+ switch (true) {
10
+ case type === 'Object':
11
+ const name = isArrayLike(obj)
12
+ ? 'ArrayLike' // special case Object: ArrayLike
13
+ : obj.constructor?.name ?? 'Object'; // some Objects do not have a constructor method
14
+ return (instances
15
+ .find(inst => obj instanceof inst.class)?.type // allow for 'real' name of Instance, after minification
16
+ ?? name); // return Object name
17
+ case type === 'Function' && obj.valueOf().toString().startsWith('class '):
18
+ return 'Class';
19
+ default:
20
+ return type;
21
+ }
22
+ };
23
+ /** return TypeValue<T> object */
24
+ export const asType = (value, ...instances) => ({ type: getType(value, ...instances), value });
25
+ /** assert value is one of a list of Types */
26
+ export const isType = (obj, ...types) => types.includes(getType(obj));
27
+ /** Type-Guards: assert \<obj> is of \<type> */
28
+ export const isPrimitive = (obj) => isType(obj, 'String', 'Number', 'BigInt', 'Boolean', 'Symbol', 'Undefined', 'Void', 'Null', 'Empty');
29
+ export const isReference = (obj) => !isPrimitive(obj);
30
+ export const isIterable = (obj) => Symbol.iterator in Object(obj) && !isString(obj);
31
+ export const isString = (obj) => isType(obj, 'String');
32
+ export const isNumber = (obj) => isType(obj, 'Number');
33
+ export const isInteger = (obj) => isType(obj, 'BigInt');
34
+ export const isIntegerLike = (obj) => isType(obj, 'String') && /^-?[0-9]+n$/.test(obj);
35
+ export const isDigit = (obj) => isType(obj, 'Number', 'BigInt');
36
+ export const isBoolean = (obj) => isType(obj, 'Boolean');
37
+ export const isArray = (obj) => isType(obj, 'Array');
38
+ export const isArrayLike = (obj) => protoType(obj) === 'Object' && 'length' in obj && Object.keys(obj).every(key => key === 'length' || !isNaN(Number(key)));
39
+ export const isObject = (obj) => isType(obj, 'Object');
40
+ export const isDate = (obj) => isType(obj, 'Date');
41
+ export const isRegExp = (obj) => isType(obj, 'RegExp');
42
+ export const isRegExpLike = (obj) => isType(obj, 'String') && /^\/.*\/$/.test(obj);
43
+ export const isSymbol = (obj) => isType(obj, 'Symbol');
44
+ export const isSymbolFor = (obj) => isType(obj, 'Symbol') && Symbol.keyFor(obj) !== void 0;
45
+ export const isPropertyKey = (obj) => isType(obj, 'String', 'Number', 'Symbol');
46
+ export const isNull = (obj) => isType(obj, 'Null');
47
+ export const isNullish = (obj) => isType(obj, 'Null', 'Undefined', 'Void', 'Empty');
48
+ export const isUndefined = (obj) => isType(obj, 'Undefined', 'Void', 'Empty');
49
+ export const isDefined = (obj) => !isNullish(obj);
50
+ export const isClass = (obj) => isType(obj, 'Class');
51
+ export const isFunction = (obj) => isType(obj, 'Function', 'AsyncFunction');
52
+ export const isPromise = (obj) => isType(obj, 'Promise');
53
+ export const isMap = (obj) => isType(obj, 'Map');
54
+ export const isSet = (obj) => isType(obj, 'Set');
55
+ export const isError = (err) => isType(err, 'Error');
56
+ export const isTemporal = (obj) => protoType(obj).startsWith('Temporal.');
57
+ // non-standard Objects
58
+ export const isTempo = (obj) => isType(obj, 'Tempo');
59
+ export const isEnum = (obj) => isType(obj, 'Enumify');
60
+ export const isPledge = (obj) => isType(obj, 'Pledge');
61
+ export const nullToZero = (obj) => obj ?? 0;
62
+ export const nullToEmpty = (obj) => obj ?? '';
63
+ export const nullToValue = (obj, value) => obj ?? value;
64
+ /** object has no values */
65
+ export const isEmpty = (obj) => false
66
+ || isNullish(obj)
67
+ || (isObject(obj) && (Reflect.ownKeys(obj).length === 0))
68
+ || (isString(obj) && (obj.trim().length === 0))
69
+ || (isNumber(obj) && (isNaN(obj) === true))
70
+ || (isArray(obj) && (obj.length === 0))
71
+ || (isSet(obj) && (obj.size === 0))
72
+ || (isMap(obj) && (obj.size === 0));
73
+ export function assertCondition(condition, message) {
74
+ if (!condition)
75
+ throw new Error(message);
76
+ }
77
+ export function assertString(str) { assertCondition(isString(str), `Invalid string: ${str}`); }
78
+ ;
79
+ export function assertNever(val) { throw new Error(`Unexpected object: ${val}`); }
80
+ ;
@@ -0,0 +1,32 @@
1
+ import type { Secure, ValueOf } from './type.library.js';
2
+ /** General utility functions */
3
+ /** analyze the Call Stack to determine calling Function's name */
4
+ export declare const getCaller: () => string;
5
+ /** analyze the Call Stack to determine calling Function's name */
6
+ export declare const getScript: (nbr?: number) => string;
7
+ /**
8
+ * introduce a wait-timer that will Error() on timeOut.
9
+ * best used with Promise.race([xxx(), sleep()]
10
+ * @param msg string to display on a timeout
11
+ * @param timeOut how many milliseconds to sleep (default 2-seconds)
12
+ * @returns Promise\<void>
13
+ */
14
+ export declare const sleep: (msg?: string, timeOut?: number) => Promise<Error>;
15
+ /** Javascript Runtimes */
16
+ export declare const CONTEXT: {
17
+ readonly Unknown: "unknown";
18
+ readonly Browser: "browser";
19
+ readonly NodeJS: "nodejs";
20
+ readonly Deno: "deno";
21
+ readonly GoogleAppsScript: "google-apps-script";
22
+ };
23
+ export type CONTEXT = ValueOf<typeof CONTEXT>;
24
+ type Context = {
25
+ global: any;
26
+ type: CONTEXT;
27
+ };
28
+ /** determine JavaScript environment context */
29
+ export declare const getContext: () => Context;
30
+ /** deep-freeze an Array | Object to make it immutable */
31
+ export declare function secure<const T>(obj: T): Secure<T>;
32
+ export {};
@@ -0,0 +1,54 @@
1
+ import { ownValues } from './reflection.library.js';
2
+ import { isDefined, isReference } from './type.library.js';
3
+ /** General utility functions */
4
+ /** analyze the Call Stack to determine calling Function's name */
5
+ export const getCaller = () => {
6
+ const stackTrace = new Error().stack // only tested in latest FF and Chrome
7
+ ?.split('\n')
8
+ ?.map(itm => itm.trim())
9
+ ?.filter(itm => !itm.startsWith('Error'))
10
+ ?? [];
11
+ const callerName = stackTrace[2].split(' ');
12
+ return (callerName[1] === 'new') ? callerName[2] : callerName[1].split('.')[0];
13
+ };
14
+ /** analyze the Call Stack to determine calling Function's name */
15
+ export const getScript = (nbr = 1) => {
16
+ const stackTrace = new Error().stack
17
+ ?.match(/([^ \n\(@])*([a-z]*:\/\/\/?)*?[a-z0-9\/\\]*\.js/ig)?.[nbr];
18
+ return decodeURI(stackTrace ?? ''); // decodeURI is needed to handle spaces in file-names
19
+ };
20
+ /**
21
+ * introduce a wait-timer that will Error() on timeOut.
22
+ * best used with Promise.race([xxx(), sleep()]
23
+ * @param msg string to display on a timeout
24
+ * @param timeOut how many milliseconds to sleep (default 2-seconds)
25
+ * @returns Promise\<void>
26
+ */
27
+ export const sleep = (msg = 'sleep: timed out', timeOut = 2000) => new Promise((_, reject) => setTimeout(() => reject(new Error(msg)), timeOut));
28
+ /** Javascript Runtimes */
29
+ export const CONTEXT = {
30
+ 'Unknown': 'unknown',
31
+ 'Browser': 'browser',
32
+ 'NodeJS': 'nodejs',
33
+ 'Deno': 'deno',
34
+ 'GoogleAppsScript': 'google-apps-script',
35
+ };
36
+ /** determine JavaScript environment context */
37
+ export const getContext = () => {
38
+ const global = globalThis;
39
+ if (isDefined(global.SpreadsheetApp))
40
+ return { global, type: CONTEXT.GoogleAppsScript };
41
+ if (isDefined(global.window?.document))
42
+ return { global, type: CONTEXT.Browser };
43
+ if (isDefined(global.process?.versions?.node))
44
+ return { global, type: CONTEXT.NodeJS };
45
+ return { global, type: CONTEXT.Unknown };
46
+ };
47
+ // useful for those times when a full Enumify object is not needed, but still lock the Object from mutations
48
+ /** deep-freeze an Array | Object to make it immutable */
49
+ export function secure(obj) {
50
+ if (isReference(obj)) // skip primitive values
51
+ ownValues(obj) // retrieve the properties on obj
52
+ .forEach(val => Object.isFrozen(val) || secure(val)); // secure each value, if not already Frozen
53
+ return Object.freeze(obj); // freeze the object itself
54
+ }
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@magmacomputing/tempo",
3
+ "version": "1.0.0",
4
+ "description": "A premium, high-performance wrapper around the JavaScript Temporal API.",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./dist/index.js",
10
+ "types": "./dist/index.d.ts"
11
+ }
12
+ },
13
+ "directories": {
14
+ "lib": "lib"
15
+ },
16
+ "scripts": {
17
+ "test": "vitest run",
18
+ "build": "tsc && tsc-alias",
19
+ "repl": "tsx -i --import ./repl.ts"
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/magmacomputing/tempo.git"
27
+ },
28
+ "keywords": [
29
+ "Temporal",
30
+ "Date",
31
+ "Time",
32
+ "Parsing",
33
+ "Formatting",
34
+ "Fluent API"
35
+ ],
36
+ "author": "Michael <hello@magmacomputing.com.au>",
37
+ "license": "MIT",
38
+ "type": "module",
39
+ "bugs": {
40
+ "url": "https://github.com/magmacomputing/tempo/issues"
41
+ },
42
+ "homepage": "https://github.com/magmacomputing/tempo#readme",
43
+ "dependencies": {
44
+ "@js-temporal/polyfill": "^0.5.1"
45
+ },
46
+ "devDependencies": {
47
+ "@types/jest": "^30.0.0",
48
+ "@vitest/ui": "^4.0.18",
49
+ "tsc-alias": "^1.8.16",
50
+ "tsx": "^4.21.0",
51
+ "vite-tsconfig-paths": "^6.1.1",
52
+ "vitest": "^4.0.18"
53
+ }
54
+ }