saasco-sdk 0.1.0 → 0.1.3

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/index.esm.js ADDED
@@ -0,0 +1,965 @@
1
+ import { v4 } from '@lukeed/uuid';
2
+ import { z } from 'zod';
3
+
4
+ const timezones = {
5
+ 'Asia/Barnaul': 'RU',
6
+ 'Africa/Nouakchott': 'MR',
7
+ 'Africa/Lusaka': 'ZM',
8
+ 'Asia/Pyongyang': 'KP',
9
+ 'Europe/Bratislava': 'SK',
10
+ 'America/Belize': 'BZ',
11
+ 'America/Maceio': 'BR',
12
+ 'Pacific/Chuuk': 'FM',
13
+ 'Indian/Comoro': 'KM',
14
+ 'Pacific/Palau': 'PW',
15
+ 'Asia/Jakarta': 'ID',
16
+ 'Africa/Windhoek': 'NA',
17
+ 'America/Chihuahua': 'MX',
18
+ 'America/Nome': 'US',
19
+ 'Africa/Mbabane': 'SZ',
20
+ 'Africa/Porto-Novo': 'BJ',
21
+ 'Europe/San_Marino': 'SM',
22
+ 'Pacific/Fakaofo': 'TK',
23
+ 'America/Denver': 'US',
24
+ 'Europe/Belgrade': 'RS',
25
+ 'America/Indiana/Tell_City': 'US',
26
+ 'America/Fortaleza': 'BR',
27
+ 'America/Halifax': 'CA',
28
+ 'Europe/Bucharest': 'RO',
29
+ 'America/Indiana/Petersburg': 'US',
30
+ 'Europe/Kirov': 'RU',
31
+ 'Europe/Athens': 'GR',
32
+ 'America/Argentina/Ushuaia': 'AR',
33
+ 'Europe/Monaco': 'MC',
34
+ 'Europe/Vilnius': 'LT',
35
+ 'Europe/Copenhagen': 'DK',
36
+ 'Pacific/Kanton': 'KI',
37
+ 'America/Caracas': 'VE',
38
+ 'Asia/Almaty': 'KZ',
39
+ 'Europe/Paris': 'FR',
40
+ 'Africa/Blantyre': 'MW',
41
+ 'Asia/Muscat': 'OM',
42
+ 'America/North_Dakota/Beulah': 'US',
43
+ 'America/Matamoros': 'MX',
44
+ 'Asia/Irkutsk': 'RU',
45
+ 'America/Costa_Rica': 'CR',
46
+ 'America/Araguaina': 'BR',
47
+ 'Atlantic/Canary': 'ES',
48
+ 'America/Santo_Domingo': 'DO',
49
+ 'America/Vancouver': 'CA',
50
+ 'Africa/Addis_Ababa': 'ET',
51
+ 'Africa/Accra': 'GH',
52
+ 'Pacific/Kwajalein': 'MH',
53
+ 'Asia/Baghdad': 'IQ',
54
+ 'Australia/Adelaide': 'AU',
55
+ 'Australia/Hobart': 'AU',
56
+ 'America/Guayaquil': 'EC',
57
+ 'America/Argentina/Tucuman': 'AR',
58
+ 'Australia/Lindeman': 'AU',
59
+ 'America/New_York': 'US',
60
+ 'Pacific/Fiji': 'FJ',
61
+ 'America/Antigua': 'AG',
62
+ 'Africa/Casablanca': 'MA',
63
+ 'America/Paramaribo': 'SR',
64
+ 'Africa/Cairo': 'EG',
65
+ 'America/Cayenne': 'GF',
66
+ 'America/Detroit': 'US',
67
+ 'Antarctica/Syowa': 'AQ',
68
+ 'Africa/Douala': 'CM',
69
+ 'America/Argentina/La_Rioja': 'AR',
70
+ 'Africa/Lagos': 'NG',
71
+ 'America/St_Barthelemy': 'BL',
72
+ 'Asia/Nicosia': 'CY',
73
+ 'Asia/Macau': 'MO',
74
+ 'Europe/Riga': 'LV',
75
+ 'Asia/Ashgabat': 'TM',
76
+ 'Indian/Antananarivo': 'MG',
77
+ 'America/Argentina/San_Juan': 'AR',
78
+ 'Asia/Aden': 'YE',
79
+ 'Asia/Tomsk': 'RU',
80
+ 'America/Asuncion': 'PY',
81
+ 'Pacific/Bougainville': 'PG',
82
+ 'Asia/Vientiane': 'LA',
83
+ 'America/Mazatlan': 'MX',
84
+ 'Africa/Luanda': 'AO',
85
+ 'Europe/Oslo': 'NO',
86
+ 'Africa/Kinshasa': 'CD',
87
+ 'Europe/Warsaw': 'PL',
88
+ 'America/Grand_Turk': 'TC',
89
+ 'Asia/Seoul': 'KR',
90
+ 'Africa/Tripoli': 'LY',
91
+ 'America/St_Thomas': 'VI',
92
+ 'Asia/Kathmandu': 'NP',
93
+ 'Pacific/Pitcairn': 'PN',
94
+ 'Pacific/Nauru': 'NR',
95
+ 'America/Curacao': 'CW',
96
+ 'Asia/Kabul': 'AF',
97
+ 'Pacific/Tongatapu': 'TO',
98
+ 'Europe/Simferopol': 'UA',
99
+ 'Asia/Ust-Nera': 'RU',
100
+ 'Africa/Mogadishu': 'SO',
101
+ 'Indian/Mayotte': 'YT',
102
+ 'Pacific/Niue': 'NU',
103
+ 'America/Thunder_Bay': 'CA',
104
+ 'Atlantic/Azores': 'PT',
105
+ 'Pacific/Gambier': 'PF',
106
+ 'Europe/Stockholm': 'SE',
107
+ 'Africa/Libreville': 'GA',
108
+ 'America/Punta_Arenas': 'CL',
109
+ 'America/Guatemala': 'GT',
110
+ 'America/Noronha': 'BR',
111
+ 'Europe/Helsinki': 'FI',
112
+ 'Asia/Gaza': 'PS',
113
+ 'Pacific/Kosrae': 'FM',
114
+ 'America/Aruba': 'AW',
115
+ 'America/Nassau': 'BS',
116
+ 'Asia/Choibalsan': 'MN',
117
+ 'America/Winnipeg': 'CA',
118
+ 'America/Anguilla': 'AI',
119
+ 'Asia/Thimphu': 'BT',
120
+ 'Asia/Beirut': 'LB',
121
+ 'Atlantic/Faroe': 'FO',
122
+ 'Europe/Berlin': 'DE',
123
+ 'Europe/Amsterdam': 'NL',
124
+ 'Pacific/Honolulu': 'US',
125
+ 'America/Regina': 'CA',
126
+ 'America/Scoresbysund': 'GL',
127
+ 'Europe/Vienna': 'AT',
128
+ 'Europe/Tirane': 'AL',
129
+ 'Africa/El_Aaiun': 'EH',
130
+ 'America/Creston': 'CA',
131
+ 'Asia/Qostanay': 'KZ',
132
+ 'Asia/Ho_Chi_Minh': 'VN',
133
+ 'Europe/Samara': 'RU',
134
+ 'Europe/Rome': 'IT',
135
+ 'Australia/Eucla': 'AU',
136
+ 'America/El_Salvador': 'SV',
137
+ 'America/Chicago': 'US',
138
+ 'Africa/Abidjan': 'CI',
139
+ 'Asia/Kamchatka': 'RU',
140
+ 'Pacific/Tarawa': 'KI',
141
+ 'America/Santiago': 'CL',
142
+ 'America/Bahia': 'BR',
143
+ 'Indian/Christmas': 'CX',
144
+ 'Asia/Atyrau': 'KZ',
145
+ 'Asia/Dushanbe': 'TJ',
146
+ 'Europe/Ulyanovsk': 'RU',
147
+ 'America/Yellowknife': 'CA',
148
+ 'America/Recife': 'BR',
149
+ 'Australia/Sydney': 'AU',
150
+ 'America/Fort_Nelson': 'CA',
151
+ 'Pacific/Efate': 'VU',
152
+ 'Europe/Saratov': 'RU',
153
+ 'Africa/Banjul': 'GM',
154
+ 'Asia/Omsk': 'RU',
155
+ 'Europe/Ljubljana': 'SI',
156
+ 'Europe/Budapest': 'HU',
157
+ 'Europe/Astrakhan': 'RU',
158
+ 'America/Argentina/Buenos_Aires': 'AR',
159
+ 'Pacific/Chatham': 'NZ',
160
+ 'America/Argentina/Salta': 'AR',
161
+ 'Africa/Niamey': 'NE',
162
+ 'Asia/Pontianak': 'ID',
163
+ 'Indian/Reunion': 'RE',
164
+ 'Asia/Hong_Kong': 'HK',
165
+ 'Antarctica/McMurdo': 'AQ',
166
+ 'Africa/Malabo': 'GQ',
167
+ 'America/Los_Angeles': 'US',
168
+ 'America/Argentina/Cordoba': 'AR',
169
+ 'Pacific/Pohnpei': 'FM',
170
+ 'America/Tijuana': 'MX',
171
+ 'America/Campo_Grande': 'BR',
172
+ 'America/Dawson_Creek': 'CA',
173
+ 'Asia/Novosibirsk': 'RU',
174
+ 'Pacific/Pago_Pago': 'AS',
175
+ 'Asia/Jerusalem': 'IL',
176
+ 'Europe/Sarajevo': 'BA',
177
+ 'Africa/Freetown': 'SL',
178
+ 'Asia/Yekaterinburg': 'RU',
179
+ 'America/Juneau': 'US',
180
+ 'Africa/Ouagadougou': 'BF',
181
+ 'Africa/Monrovia': 'LR',
182
+ 'Europe/Kiev': 'UA',
183
+ 'America/Argentina/San_Luis': 'AR',
184
+ 'Asia/Tokyo': 'JP',
185
+ 'Asia/Qatar': 'QA',
186
+ 'America/La_Paz': 'BO',
187
+ 'America/Bogota': 'CO',
188
+ 'America/Thule': 'GL',
189
+ 'Asia/Manila': 'PH',
190
+ 'Asia/Hovd': 'MN',
191
+ 'Asia/Tehran': 'IR',
192
+ 'Atlantic/Madeira': 'PT',
193
+ 'America/Metlakatla': 'US',
194
+ 'Europe/Vatican': 'VA',
195
+ 'Asia/Bishkek': 'KG',
196
+ 'Asia/Dili': 'TL',
197
+ 'Antarctica/Palmer': 'AQ',
198
+ 'Atlantic/Cape_Verde': 'CV',
199
+ 'Indian/Chagos': 'IO',
200
+ 'America/Kentucky/Monticello': 'US',
201
+ 'Africa/Algiers': 'DZ',
202
+ 'Africa/Maseru': 'LS',
203
+ 'Asia/Kuala_Lumpur': 'MY',
204
+ 'Africa/Khartoum': 'SD',
205
+ 'America/Argentina/Rio_Gallegos': 'AR',
206
+ 'America/Blanc-Sablon': 'CA',
207
+ 'Africa/Maputo': 'MZ',
208
+ 'America/Tortola': 'VG',
209
+ 'Atlantic/Bermuda': 'BM',
210
+ 'America/Argentina/Catamarca': 'AR',
211
+ 'America/Cayman': 'KY',
212
+ 'America/Puerto_Rico': 'PR',
213
+ 'Pacific/Majuro': 'MH',
214
+ 'Europe/Busingen': 'DE',
215
+ 'Pacific/Midway': 'UM',
216
+ 'Indian/Cocos': 'CC',
217
+ 'Asia/Singapore': 'SG',
218
+ 'America/Boise': 'US',
219
+ 'America/Nuuk': 'GL',
220
+ 'America/Goose_Bay': 'CA',
221
+ 'Australia/Broken_Hill': 'AU',
222
+ 'Africa/Dar_es_Salaam': 'TZ',
223
+ 'Africa/Asmara': 'ER',
224
+ 'Asia/Samarkand': 'UZ',
225
+ 'Asia/Tbilisi': 'GE',
226
+ 'America/Argentina/Jujuy': 'AR',
227
+ 'America/Indiana/Winamac': 'US',
228
+ 'America/Porto_Velho': 'BR',
229
+ 'Asia/Magadan': 'RU',
230
+ 'Europe/Zaporozhye': 'UA',
231
+ 'Antarctica/Casey': 'AQ',
232
+ 'Asia/Shanghai': 'CN',
233
+ 'Pacific/Norfolk': 'NF',
234
+ 'Europe/Guernsey': 'GG',
235
+ 'Australia/Brisbane': 'AU',
236
+ 'Antarctica/DumontDUrville': 'AQ',
237
+ 'America/Havana': 'CU',
238
+ 'America/Atikokan': 'CA',
239
+ 'America/Mexico_City': 'MX',
240
+ 'America/Rankin_Inlet': 'CA',
241
+ 'America/Cuiaba': 'BR',
242
+ 'America/Resolute': 'CA',
243
+ 'Africa/Ceuta': 'ES',
244
+ 'Arctic/Longyearbyen': 'SJ',
245
+ 'Pacific/Guam': 'GU',
246
+ 'Asia/Damascus': 'SY',
247
+ 'Asia/Colombo': 'LK',
248
+ 'Asia/Yerevan': 'AM',
249
+ 'America/Montserrat': 'MS',
250
+ 'America/Belem': 'BR',
251
+ 'Europe/Kaliningrad': 'RU',
252
+ 'Atlantic/South_Georgia': 'GS',
253
+ 'Asia/Tashkent': 'UZ',
254
+ 'Asia/Kolkata': 'IN',
255
+ 'America/St_Johns': 'CA',
256
+ 'Asia/Srednekolymsk': 'RU',
257
+ 'Asia/Yakutsk': 'RU',
258
+ 'Europe/Prague': 'CZ',
259
+ 'Africa/Djibouti': 'DJ',
260
+ 'Asia/Dubai': 'AE',
261
+ 'Europe/Uzhgorod': 'UA',
262
+ 'America/Edmonton': 'CA',
263
+ 'Asia/Famagusta': 'CY',
264
+ 'America/Indiana/Knox': 'US',
265
+ 'Asia/Hebron': 'PS',
266
+ 'Asia/Taipei': 'TW',
267
+ 'Europe/London': 'GB',
268
+ 'Africa/Dakar': 'SN',
269
+ 'Australia/Darwin': 'AU',
270
+ 'America/Glace_Bay': 'CA',
271
+ 'Antarctica/Vostok': 'AQ',
272
+ 'America/Indiana/Vincennes': 'US',
273
+ 'America/Nipigon': 'CA',
274
+ 'Asia/Kuwait': 'KW',
275
+ 'Pacific/Guadalcanal': 'SB',
276
+ 'America/Toronto': 'CA',
277
+ 'Africa/Gaborone': 'BW',
278
+ 'Africa/Bujumbura': 'BI',
279
+ 'Africa/Lubumbashi': 'CD',
280
+ 'America/Merida': 'MX',
281
+ 'America/Marigot': 'MF',
282
+ 'Europe/Zagreb': 'HR',
283
+ 'Pacific/Easter': 'CL',
284
+ 'America/Santarem': 'BR',
285
+ 'Pacific/Noumea': 'NC',
286
+ 'America/Sitka': 'US',
287
+ 'Atlantic/Stanley': 'FK',
288
+ 'Pacific/Funafuti': 'TV',
289
+ 'America/Iqaluit': 'CA',
290
+ 'America/Rainy_River': 'CA',
291
+ 'America/Anchorage': 'US',
292
+ 'America/Lima': 'PE',
293
+ 'Asia/Baku': 'AZ',
294
+ 'America/Indiana/Vevay': 'US',
295
+ 'Asia/Ulaanbaatar': 'MN',
296
+ 'America/Managua': 'NI',
297
+ 'Asia/Krasnoyarsk': 'RU',
298
+ 'Asia/Qyzylorda': 'KZ',
299
+ 'America/Eirunepe': 'BR',
300
+ 'Europe/Podgorica': 'ME',
301
+ 'Europe/Chisinau': 'MD',
302
+ 'Europe/Mariehamn': 'AX',
303
+ 'Europe/Volgograd': 'RU',
304
+ 'Africa/Nairobi': 'KE',
305
+ 'Europe/Isle_of_Man': 'IM',
306
+ 'America/Menominee': 'US',
307
+ 'Africa/Harare': 'ZW',
308
+ 'Asia/Anadyr': 'RU',
309
+ 'America/Moncton': 'CA',
310
+ 'Indian/Maldives': 'MV',
311
+ 'America/Whitehorse': 'CA',
312
+ 'Antarctica/Mawson': 'AQ',
313
+ 'Europe/Madrid': 'ES',
314
+ 'America/Argentina/Mendoza': 'AR',
315
+ 'America/Manaus': 'BR',
316
+ 'Africa/Bangui': 'CF',
317
+ 'Indian/Mauritius': 'MU',
318
+ 'Africa/Tunis': 'TN',
319
+ 'Australia/Lord_Howe': 'AU',
320
+ 'America/Kentucky/Louisville': 'US',
321
+ 'America/North_Dakota/Center': 'US',
322
+ 'Asia/Novokuznetsk': 'RU',
323
+ 'Asia/Makassar': 'ID',
324
+ 'America/Port_of_Spain': 'TT',
325
+ 'America/Bahia_Banderas': 'MX',
326
+ 'Pacific/Auckland': 'NZ',
327
+ 'America/Sao_Paulo': 'BR',
328
+ 'Asia/Dhaka': 'BD',
329
+ 'America/Pangnirtung': 'CA',
330
+ 'Europe/Dublin': 'IE',
331
+ 'Asia/Brunei': 'BN',
332
+ 'Africa/Brazzaville': 'CG',
333
+ 'America/Montevideo': 'UY',
334
+ 'America/Jamaica': 'JM',
335
+ 'America/Indiana/Indianapolis': 'US',
336
+ 'America/Kralendijk': 'BQ',
337
+ 'Europe/Gibraltar': 'GI',
338
+ 'Pacific/Marquesas': 'PF',
339
+ 'Pacific/Apia': 'WS',
340
+ 'Europe/Jersey': 'JE',
341
+ 'America/Phoenix': 'US',
342
+ 'Africa/Ndjamena': 'TD',
343
+ 'Asia/Karachi': 'PK',
344
+ 'Africa/Kampala': 'UG',
345
+ 'Asia/Sakhalin': 'RU',
346
+ 'America/Martinique': 'MQ',
347
+ 'Europe/Moscow': 'RU',
348
+ 'Africa/Conakry': 'GN',
349
+ 'America/Barbados': 'BB',
350
+ 'Africa/Lome': 'TG',
351
+ 'America/Ojinaga': 'MX',
352
+ 'America/Tegucigalpa': 'HN',
353
+ 'Asia/Bangkok': 'TH',
354
+ 'Africa/Johannesburg': 'ZA',
355
+ 'Europe/Vaduz': 'LI',
356
+ 'Africa/Sao_Tome': 'ST',
357
+ 'America/Cambridge_Bay': 'CA',
358
+ 'America/Lower_Princes': 'SX',
359
+ 'America/Miquelon': 'PM',
360
+ 'America/St_Kitts': 'KN',
361
+ 'Australia/Melbourne': 'AU',
362
+ 'Europe/Minsk': 'BY',
363
+ 'Asia/Vladivostok': 'RU',
364
+ 'Europe/Sofia': 'BG',
365
+ 'Antarctica/Davis': 'AQ',
366
+ 'Pacific/Galapagos': 'EC',
367
+ 'America/North_Dakota/New_Salem': 'US',
368
+ 'Asia/Amman': 'JO',
369
+ 'Pacific/Wallis': 'WF',
370
+ 'America/Hermosillo': 'MX',
371
+ 'Pacific/Kiritimati': 'KI',
372
+ 'Antarctica/Macquarie': 'AU',
373
+ 'America/Guyana': 'GY',
374
+ 'Asia/Riyadh': 'SA',
375
+ 'Pacific/Tahiti': 'PF',
376
+ 'America/St_Vincent': 'VC',
377
+ 'America/Cancun': 'MX',
378
+ 'America/Grenada': 'GD',
379
+ 'Pacific/Wake': 'UM',
380
+ 'America/Dawson': 'CA',
381
+ 'Europe/Brussels': 'BE',
382
+ 'Indian/Kerguelen': 'TF',
383
+ 'America/Yakutat': 'US',
384
+ 'Indian/Mahe': 'SC',
385
+ 'Atlantic/Reykjavik': 'IS',
386
+ 'America/Panama': 'PA',
387
+ 'America/Guadeloupe': 'GP',
388
+ 'Europe/Malta': 'MT',
389
+ 'Antarctica/Troll': 'AQ',
390
+ 'Asia/Jayapura': 'ID',
391
+ 'Asia/Bahrain': 'BH',
392
+ 'Asia/Chita': 'RU',
393
+ 'Europe/Tallinn': 'EE',
394
+ 'Asia/Khandyga': 'RU',
395
+ 'America/Rio_Branco': 'BR',
396
+ 'Atlantic/St_Helena': 'SH',
397
+ 'Africa/Juba': 'SS',
398
+ 'America/Adak': 'US',
399
+ 'Pacific/Saipan': 'MP',
400
+ 'America/St_Lucia': 'LC',
401
+ 'America/Inuvik': 'CA',
402
+ 'Europe/Luxembourg': 'LU',
403
+ 'Africa/Bissau': 'GW',
404
+ 'Asia/Oral': 'KZ',
405
+ 'America/Boa_Vista': 'BR',
406
+ 'Europe/Skopje': 'MK',
407
+ 'America/Port-au-Prince': 'HT',
408
+ 'Pacific/Port_Moresby': 'PG',
409
+ 'Europe/Andorra': 'AD',
410
+ 'America/Indiana/Marengo': 'US',
411
+ 'Africa/Kigali': 'RW',
412
+ 'Africa/Bamako': 'ML',
413
+ 'America/Dominica': 'DM',
414
+ 'Asia/Aqtobe': 'KZ',
415
+ 'Europe/Istanbul': 'TR',
416
+ 'Pacific/Rarotonga': 'CK',
417
+ 'America/Danmarkshavn': 'GL',
418
+ 'Europe/Zurich': 'CH',
419
+ 'Asia/Yangon': 'MM',
420
+ 'America/Monterrey': 'MX',
421
+ 'Europe/Lisbon': 'PT',
422
+ 'Asia/Kuching': 'MY',
423
+ 'Antarctica/Rothera': 'AQ',
424
+ 'Australia/Perth': 'AU',
425
+ 'Asia/Phnom_Penh': 'KH',
426
+ 'America/Swift_Current': 'CA',
427
+ 'Asia/Aqtau': 'KZ',
428
+ 'Asia/Urumqi': 'CN',
429
+ 'Asia/Calcutta': 'IN'
430
+ };
431
+
432
+ /* eslint-disable @typescript-eslint/no-explicit-any */
433
+ let userId = null;
434
+ const PREF = 'saasco-sdk';
435
+ function storeData(key, value, ttl) {
436
+ const fullKey = `${PREF}-${key}`;
437
+ if (value === undefined) return window.localStorage.removeItem(fullKey);
438
+ const now = new Date();
439
+ const item = {
440
+ value,
441
+ expiry: now.getTime() + ttl
442
+ };
443
+ localStorage.setItem(fullKey, JSON.stringify(item));
444
+ }
445
+ function retrieveData(key) {
446
+ const fullKey = `${PREF}-${key}`;
447
+ const itemStr = localStorage.getItem(fullKey);
448
+ if (!itemStr) {
449
+ return null;
450
+ }
451
+ const item = JSON.parse(itemStr);
452
+ const now = new Date();
453
+ if (now.getTime() > item.expiry) {
454
+ localStorage.removeItem(fullKey);
455
+ return null;
456
+ }
457
+ return item.value;
458
+ }
459
+ function getSessionId() {
460
+ return retrieveData(`session-id`);
461
+ }
462
+ function setSessionId({
463
+ reset
464
+ } = {
465
+ reset: false
466
+ }) {
467
+ const sessionId = reset ? v4() : getSessionId() || v4();
468
+ storeData(`session-id`, sessionId, 1000 * 60 * 30);
469
+ }
470
+ function getAnonymousId() {
471
+ return retrieveData(`anonymous-id`);
472
+ }
473
+ function setAnonmousId({
474
+ reset
475
+ } = {
476
+ reset: false
477
+ }) {
478
+ const anonymousId = reset ? v4() : getAnonymousId() || v4();
479
+ storeData(`anonymous-id`, anonymousId, 1000 * 60 * 60 * 24 * 365);
480
+ return anonymousId;
481
+ }
482
+ class Saasco {
483
+ /**
484
+ * Creates an instance of Saasco SDK.
485
+ * @param config Configuration options.
486
+ * @param config.projectId The unique identifier for the project.
487
+ * @param config.proxy The URL of the proxy server to use, if any.
488
+ * @param config.autoPageTracking Whether to automatically track page views. Default is false.
489
+ * @param config.enabled Whether analytics is enabled. Default is true. Set to false for development and staging envioronments. Will still allow debug mode to be true, just no events will be sent
490
+ * @param config.debug Whether to log debug information. Default is false.
491
+ */
492
+ constructor(config) {
493
+ this.config = config;
494
+ this.lastPageViewHref = '';
495
+ this.isInitialized = false;
496
+ // default enabled to true
497
+ this.config.enabled = this.config.enabled === undefined ? true : this.config.enabled;
498
+ }
499
+ init() {
500
+ if (this.isInitialized) {
501
+ this.log('Saasco is already initialized. Please check your code to ensure that init() is not being called multiple times.');
502
+ return;
503
+ }
504
+ this.initiAutoPageTracking();
505
+ this.log('Saasco initialized', this.config);
506
+ this.isInitialized = true;
507
+ }
508
+ debug(value) {
509
+ this.config.debug = value;
510
+ this.log(`Debug mode ${value ? 'activated' : 'deactivated'}.`);
511
+ }
512
+ /**
513
+ * The track method lets you record the actions your users perform.
514
+ * Its good to keep a conistent naming convention for your events.
515
+ * We like the Object Action Framework from segment:
516
+ * https://segment.com/academy/collecting-data/naming-conventions-for-clean-data/
517
+ *
518
+ * @param name The name of the event eg "Song Played"
519
+ * @param properties The properties of the event eg { genre: "Classics", song: "Never Gonna Give You Up" }
520
+ */
521
+ track(name,
522
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
523
+ properties) {
524
+ var _a;
525
+ // Prevent duplicate Page View tracking
526
+ if (name === 'Page View') {
527
+ const pageViewHref = window.location.href;
528
+ if (pageViewHref === this.lastPageViewHref) return;
529
+ this.lastPageViewHref = pageViewHref;
530
+ }
531
+ setSessionId();
532
+ setAnonmousId();
533
+ const customNavigator = navigator;
534
+ const locale = customNavigator.languages && customNavigator.languages.length ? customNavigator.languages[0] : customNavigator.userLanguage || customNavigator.language || customNavigator.browserLanguage || 'en';
535
+ // https://caniuse.com/?search=Intl.DateTimeFormat().resolvedOptions().timeZone
536
+ // Only has 96.63% global support, so we need to check for undefined
537
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
538
+ const location = timezones[timezone] || ((_a = locale === null || locale === void 0 ? void 0 : locale.split('-')) === null || _a === void 0 ? void 0 : _a[1]) || 'undefined';
539
+ const $screenHeight = screen.height;
540
+ const $screenWidth = screen.width;
541
+ const $screenDPI = window.devicePixelRatio;
542
+ const $referrer = document.referrer;
543
+ const $utm_source = this.getSearchParam('utm_source');
544
+ const $utm_medium = this.getSearchParam('utm_medium');
545
+ const $utm_campaign = this.getSearchParam('utm_campaign');
546
+ const $utm_content = this.getSearchParam('utm_content');
547
+ const $utm_term = this.getSearchParam('utm_term');
548
+ const $gclid = this.getSearchParam('gclid');
549
+ const $fbclid = this.getSearchParam('fbclid');
550
+ const data = {
551
+ id: v4(),
552
+ timestamp: new Date().toISOString(),
553
+ action: name,
554
+ version: '1',
555
+ sessionId: getSessionId(),
556
+ anonymousId: getAnonymousId(),
557
+ projectId: this.config.projectId,
558
+ payload: JSON.stringify({
559
+ 'user-agent': window.navigator.userAgent,
560
+ locale,
561
+ location,
562
+ title: document.title,
563
+ pathname: window.location.pathname,
564
+ href: window.location.href,
565
+ $screenHeight,
566
+ $screenWidth,
567
+ $screenDPI,
568
+ $referrer,
569
+ $utm_source,
570
+ $utm_medium,
571
+ $utm_campaign,
572
+ $utm_content,
573
+ $utm_term,
574
+ $gclid,
575
+ $fbclid,
576
+ properties: properties || {}
577
+ })
578
+ };
579
+ this.doRequest('events', data);
580
+ }
581
+ /**
582
+ * The page method lets you record page views on your website
583
+ * This records the page title and path and names the event useing the reserved property "Page Viewed"
584
+ *
585
+ * Before implementing this make sure you have disabled the autoPageTracking in the config or you will get duplicate page views
586
+ */
587
+ page() {
588
+ this.track('Page View');
589
+ }
590
+ identify(distinctIdOrProperties, propertiesOrOptions, optionsOrNothing) {
591
+ const hasId = typeof distinctIdOrProperties === 'string' || typeof distinctIdOrProperties === 'number' || distinctIdOrProperties === null;
592
+ const distinctId = hasId ? distinctIdOrProperties === null || distinctIdOrProperties === void 0 ? void 0 : distinctIdOrProperties.toString() : `soft_${v4()}`;
593
+ const properties = hasId ? propertiesOrOptions : distinctIdOrProperties;
594
+ const options = hasId ? optionsOrNothing : propertiesOrOptions;
595
+ // When the user gets identified as null this will reset the users session and anonymous id
596
+ // This should only be called when distinctId is null and there is an existing userId.
597
+ // This means the user has logged out and we should reset the session and anonymous IDs
598
+ const reset = !distinctId && !!userId;
599
+ if (reset) this.log('User logged out and session reset');
600
+ setSessionId({
601
+ reset
602
+ });
603
+ const anonymousId = setAnonmousId({
604
+ reset
605
+ });
606
+ // set the distinct Id to the userId
607
+ userId = distinctId;
608
+ // No distinctId provided so we don't track the user
609
+ if (!distinctId) return;
610
+ const data = {
611
+ id: v4(),
612
+ timestamp: new Date().toISOString(),
613
+ projectId: this.config.projectId,
614
+ distinctId,
615
+ anonymousId,
616
+ version: '1',
617
+ payload: properties || {},
618
+ options: options || {}
619
+ };
620
+ this.doRequest('identify', data);
621
+ }
622
+ /**
623
+ * Handles sending data to the Saasco API
624
+ * If you have a proxy set up, it will send the data to the proxy and you can handle forawrding the data to the Saasco events API
625
+ * @param path
626
+ * @param data
627
+ */
628
+ doRequest(path, data) {
629
+ const base = this.config.proxy || 'https://www.saasco.com/api/';
630
+ const url = `${base}${path}`;
631
+ const logMessage = data.action === 'Page View' ? `Page View ${window.location.pathname}` // if its a page view, include pathname in console log
632
+ : data.action || path;
633
+ this.log(logMessage, data);
634
+ // If analytics is disabled, don't send the request
635
+ if (this.config.enabled === false) return;
636
+ fetch(url, {
637
+ method: 'POST',
638
+ headers: {
639
+ 'Content-Type': 'application/json'
640
+ },
641
+ body: JSON.stringify(data)
642
+ }).then(response => {
643
+ if (!response.ok) {
644
+ throw new Error(response.status.toString());
645
+ }
646
+ }).catch(e => {
647
+ console.error('Error with Saasco request: ' + e.message, path, data);
648
+ });
649
+ }
650
+ /**
651
+ * @param args Arguments to be logged
652
+ */
653
+ log(...args) {
654
+ if (!this.config.debug) return;
655
+ const message = '◍ Saasco Debug';
656
+ console.log(...[`\x1b[47m\x1b[30m ${message} \x1b[0m`,
657
+ // Message highlighted for easy finding
658
+ ...args]);
659
+ }
660
+ getSearchParam(param) {
661
+ return new URLSearchParams(window.location.search).get(param);
662
+ }
663
+ /**
664
+ * If autoPageTracking is enabled, this will automatically track page views
665
+ * It listens to url changes to track new pages every time the url changes
666
+ * @returns
667
+ */
668
+ initiAutoPageTracking() {
669
+ // Disable auto page tracking if the config is set to false
670
+ // Will run if undefined or true
671
+ if (this.config.autoPageTracking === false) return;
672
+ // Prevent running on the server
673
+ if (typeof window === 'undefined') return;
674
+ // Prevent intitializing auto page tracking more than once
675
+ if (window.saascoAutoPageTrackingActive) {
676
+ this.log('Auto Page Tracking already enabled');
677
+ return;
678
+ }
679
+ window.saascoAutoPageTrackingActive = true;
680
+ this.log('Auto Page Tracking enabled');
681
+ // Track initial page load
682
+ this.page();
683
+ // Listen for hash changes
684
+ window.addEventListener('hashchange', () => this.page());
685
+ // Listen to popstate for back and forward navigation
686
+ window.addEventListener('popstate', () => this.page());
687
+ // Wrap history push state to listen for URL changes
688
+ const historyPushState = history.pushState;
689
+ history.pushState = (...args) => {
690
+ const returnValue = historyPushState.apply(history, args);
691
+ this.page();
692
+ return returnValue;
693
+ };
694
+ // Wrap history replace state to listen for URL changes
695
+ const historyReplaceState = history.replaceState;
696
+ history.replaceState = (...args) => {
697
+ const returnValue = historyReplaceState.apply(history, args);
698
+ this.page();
699
+ return returnValue;
700
+ };
701
+ }
702
+ }
703
+
704
+ function coerceReservedProperties(properties) {
705
+ const coerce = [{
706
+ key: 'age',
707
+ coerceFrom: ['age', 'age_value', 'ageValue', 'user_age', 'userAge', 'user_age_value', 'userAgeValue', 'age_of_user', 'ageOfUser', 'age_in_years', 'ageInYears', 'years_old', 'yearsOld', 'age_years', 'ageYears'],
708
+ schema: z.coerce.number().optional()
709
+ }, {
710
+ key: 'avatar',
711
+ coerceFrom: ['avatar', 'user_avatar', 'userAvatar', 'avatar_url', 'avatarUrl', 'profile_picture', 'profilePicture', 'picture', 'user_picture', 'userPicture', 'profile_pic', 'profilePic', 'pic', 'user_pic', 'userPic', 'image', 'user_image', 'userImage', 'profile_image', 'profileImage', 'profile_image_url', 'profileImageUrl', 'profile_pic_url', 'profilePicUrl', 'pic_url', 'picUrl', 'image_url', 'imageUrl', 'user_image_url', 'userImageUrl', 'user_pic_url', 'userPicUrl', 'profile_pic_url', 'profilePicUrl', 'pic_url', 'picUrl', 'image_url', 'imageUrl', 'user_image_url', 'userImageUrl', 'user_pic_url', 'userPicUrl'],
712
+ schema: z.coerce.string().url().optional()
713
+ }, {
714
+ key: 'birthday',
715
+ coerceFrom: ['birthday', 'birth_date', 'birthDate', 'date_of_birth', 'dateOfBirth', 'dob', 'Dob', 'birth_day', 'birthDay']
716
+ }, {
717
+ key: 'createdAt',
718
+ coerceFrom: ['createdAt', 'created_at', 'created', 'createdDate', 'created_date', 'dateCreated', 'date_created', 'date_created_at', 'dateCreatedAt', 'date_created_at', 'dateCreated', 'date_created'],
719
+ schema: z.coerce.date().optional()
720
+ }, {
721
+ key: 'description',
722
+ coerceFrom: ['description', 'bio', 'about', 'about_me', 'aboutMe', 'user_description', 'userDescription', 'profile_description', 'profileDescription']
723
+ }, {
724
+ key: 'email',
725
+ coerceFrom: ['email', 'user_email', 'userEmail', 'email_address', 'emailAddress', 'e_mail', 'E_Mail', 'mail', 'Mail', 'contact_email', 'contactEmail', 'primary_email', 'primaryEmail'],
726
+ schema: z.coerce.string().email().optional()
727
+ }, {
728
+ key: 'firstName',
729
+ coerceFrom: ['first_name', 'firstName', 'firstname', 'given_name', 'givenName', 'user_first_name', 'userFirstName', 'name_first', 'nameFirst', 'f_name', 'fName']
730
+ }, {
731
+ key: 'gender',
732
+ coerceFrom: ['gender', 'user_gender', 'userGender', 'sex', 'user_sex', 'userSex']
733
+ }, {
734
+ key: 'lastName',
735
+ coerceFrom: ['last_name', 'lastName', 'lastname', 'surname', 'user_last_name', 'userLastName', 'name_last', 'nameLast', 'l_name', 'lName']
736
+ }, {
737
+ key: 'name',
738
+ coerceFrom: ['name', 'full_name', 'fullName', 'user_name', 'userName', 'complete_name', 'completeName']
739
+ }, {
740
+ key: 'phone',
741
+ coerceFrom: ['phone', 'phone_number', 'phoneNumber', 'mobile', 'mobile_number', 'mobileNumber', 'contact_number', 'contactNumber', 'tel', 'telephone']
742
+ }, {
743
+ key: 'title',
744
+ coerceFrom: ['title', 'user_title', 'userTitle', 'position', 'job_title', 'jobTitle']
745
+ }, {
746
+ key: 'username',
747
+ coerceFrom: ['username', 'user_name', 'userName', 'user_login', 'userLogin', 'account_name', 'accountName', 'screen_name', 'screenName', 'handle']
748
+ }, {
749
+ key: 'website',
750
+ coerceFrom: ['website', 'web_site', 'site', 'web', 'personal_website', 'personalWebsite', 'company_website', 'companyWebsite'],
751
+ schema: z.coerce.string().url().optional()
752
+ }, {
753
+ key: 'displayName',
754
+ coerceFrom: ['display_name', 'displayName', 'user_display_name', 'userDisplayName', 'full_name', 'fullName', 'user_full_name', 'userFullName', 'complete_name', 'completeName', 'user_complete_name', 'userCompleteName', 'name', 'username'],
755
+ schema: z.coerce.string().url().optional()
756
+ }];
757
+ return coerce.reduce((acc, {
758
+ key,
759
+ coerceFrom,
760
+ schema
761
+ }) => {
762
+ const coercedValue = coerceValue(properties, coerceFrom, schema);
763
+ if (coercedValue) acc[key] = coercedValue;
764
+ if (!coercedValue && key === 'displayName' && acc['firstName']) {
765
+ const displayName = `${acc['firstName'] || ''} ${acc['lastName'] || ''}`.trim();
766
+ if (displayName) acc[key] = displayName;
767
+ }
768
+ return acc;
769
+ }, properties);
770
+ }
771
+ /**
772
+ * Coerces the first non-null value from the properties object
773
+ * @param properties
774
+ * @param keys Provided in priority order, the first to match will return
775
+ * @returns
776
+ */
777
+ function coerceValue(properties, keys, schema) {
778
+ let coercedValue = null;
779
+ for (const key of keys) {
780
+ if (properties[key] !== undefined) {
781
+ if (!schema) {
782
+ coercedValue = properties[key];
783
+ break;
784
+ } else {
785
+ const result = schema.safeParse(properties[key]);
786
+ if (result.success) {
787
+ coercedValue = properties[key];
788
+ break;
789
+ }
790
+ }
791
+ }
792
+ }
793
+ return coercedValue;
794
+ }
795
+
796
+ const tbAny = z.union([z.string(), z.number(), z.array(z.union([z.string(), z.number()]))]);
797
+ const tinyBirdBaseSchema = z.object({
798
+ meta: z.array(z.object({
799
+ name: z.string(),
800
+ type: z.string()
801
+ })),
802
+ statistics: z.object({
803
+ elapsed: z.number(),
804
+ rows_read: z.number(),
805
+ bytes_read: z.number()
806
+ }),
807
+ rows: z.number()
808
+ });
809
+ const kpisRequestSchema = z.object({
810
+ projectId: z.string(),
811
+ dateTo: z.string().optional(),
812
+ dateFrom: z.string().optional(),
813
+ referringDomain: z.string().optional(),
814
+ location: z.string().optional()
815
+ });
816
+ const kpisResponseSchema = tinyBirdBaseSchema.extend({
817
+ data: z.array(z.object({
818
+ date: z.string(),
819
+ visits: z.number(),
820
+ pageviews: z.number(),
821
+ bounceRate: z.nullable(z.number()),
822
+ avgSessionSec: z.number()
823
+ }))
824
+ });
825
+ const eventsKpisResponseSchema = tinyBirdBaseSchema.extend({
826
+ data: z.array(z.object({
827
+ unique: z.number(),
828
+ total: z.number()
829
+ }))
830
+ });
831
+ const baseTopRequestSchema = z.object({
832
+ projectId: z.string(),
833
+ dateTo: z.string().optional(),
834
+ dateFrom: z.string().optional(),
835
+ limit: z.number().optional(),
836
+ skip: z.number().optional(),
837
+ referringDomain: z.string().optional(),
838
+ location: z.string().optional()
839
+ });
840
+ const topPagesResponseSchema = tinyBirdBaseSchema.extend({
841
+ data: z.array(z.object({
842
+ pathname: z.string(),
843
+ visits: z.number(),
844
+ hits: z.number()
845
+ }))
846
+ });
847
+ const topLocationsResponseSchema = tinyBirdBaseSchema.extend({
848
+ data: z.array(z.object({
849
+ location: z.string(),
850
+ visits: z.number(),
851
+ hits: z.number(),
852
+ bounceRate: z.nullable(z.number()),
853
+ avgSessionSec: z.number()
854
+ }))
855
+ });
856
+ const topDevicesResponseSchema = tinyBirdBaseSchema.extend({
857
+ data: z.array(z.object({
858
+ device: z.string(),
859
+ visits: z.number(),
860
+ hits: z.number(),
861
+ bounceRate: z.nullable(z.number()),
862
+ avgSessionSec: z.number()
863
+ }))
864
+ });
865
+ const topBrowsersResponseSchema = tinyBirdBaseSchema.extend({
866
+ data: z.array(z.object({
867
+ browser: z.string(),
868
+ visits: z.number(),
869
+ hits: z.number(),
870
+ bounceRate: z.nullable(z.number()),
871
+ avgSessionSec: z.number()
872
+ }))
873
+ });
874
+ const topSourcesSchema = z.object({
875
+ referrer: z.string(),
876
+ visits: z.number(),
877
+ hits: z.number(),
878
+ bounceRate: z.nullable(z.number()),
879
+ avgSessionSec: z.number()
880
+ });
881
+ const topSourcesResponseSchema = tinyBirdBaseSchema.extend({
882
+ data: z.array(topSourcesSchema)
883
+ });
884
+ const topActionsResponseSchema = tinyBirdBaseSchema.extend({
885
+ data: z.array(z.object({
886
+ action: z.string(),
887
+ unique: z.number(),
888
+ total: z.number()
889
+ }))
890
+ });
891
+ const analyticsEventSchema = z.object({
892
+ id: z.string(),
893
+ timestamp: z.string(),
894
+ projectId: z.string(),
895
+ anonymousId: z.string(),
896
+ sessionId: z.string(),
897
+ version: z.string(),
898
+ action: z.string(),
899
+ payload: z.string()
900
+ });
901
+ const userEventsResponseSchema = tinyBirdBaseSchema.extend({
902
+ data: z.array(analyticsEventSchema)
903
+ });
904
+ const currentUsersRequestSchema = z.object({
905
+ projectId: z.string(),
906
+ minutes: z.number().optional(),
907
+ referringDomain: z.string().optional(),
908
+ location: z.string().optional()
909
+ });
910
+ const currentUsersResponseSchema = tinyBirdBaseSchema.extend({
911
+ data: z.array(z.object({
912
+ visits: z.number()
913
+ }))
914
+ });
915
+ const reservedPropertiesSchema = z.object({
916
+ age: z.number().nullish(),
917
+ avatar: z.string().url().nullish(),
918
+ birthday: z.string().nullish(),
919
+ createdAt: z.string().nullish(),
920
+ description: z.string().nullish(),
921
+ email: z.string().email().or(z.literal('')).nullish(),
922
+ firstName: z.string().nullish(),
923
+ gender: z.string().nullish(),
924
+ id: z.string().nullish(),
925
+ lastName: z.string().nullish(),
926
+ name: z.string().nullish(),
927
+ phone: z.string().nullish(),
928
+ title: z.string().nullish(),
929
+ username: z.string().nullish(),
930
+ website: z.string().nullish()
931
+ });
932
+ const userPropertiesSchema = reservedPropertiesSchema.and(z.record(z.union([z.string(), z.number(), z.boolean(), z.date(), z.null(), z.array(z.union([z.string(), z.number(), z.boolean(), z.date(), z.null()]))])));
933
+ const analyticsUserRawSchema = z.object({
934
+ timestamp: z.string(),
935
+ distinctId: z.string(),
936
+ projectId: z.string(),
937
+ payload: z.string()
938
+ });
939
+ const analyticsUserSchema = analyticsUserRawSchema.omit({
940
+ payload: true
941
+ }).and(z.object({
942
+ properties: userPropertiesSchema
943
+ }));
944
+ const listUsersParamsSchema = z.object({
945
+ projectId: z.string(),
946
+ limit: z.number().optional()
947
+ });
948
+ const getAnalyticsUserParamsSchema = z.object({
949
+ projectId: z.string(),
950
+ distinctId: z.string()
951
+ });
952
+ const idenfitySchema = z.object({
953
+ id: z.string(),
954
+ timestamp: z.string(),
955
+ projectId: z.string(),
956
+ distinctId: z.string(),
957
+ anonymousId: z.string(),
958
+ version: z.string(),
959
+ payload: userPropertiesSchema,
960
+ options: z.object({
961
+ active: z.boolean().optional()
962
+ }).optional()
963
+ });
964
+
965
+ export { Saasco, analyticsEventSchema, analyticsUserRawSchema, analyticsUserSchema, baseTopRequestSchema, coerceReservedProperties, currentUsersRequestSchema, currentUsersResponseSchema, eventsKpisResponseSchema, getAnalyticsUserParamsSchema, idenfitySchema, kpisRequestSchema, kpisResponseSchema, listUsersParamsSchema, reservedPropertiesSchema, tbAny, tinyBirdBaseSchema, topActionsResponseSchema, topBrowsersResponseSchema, topDevicesResponseSchema, topLocationsResponseSchema, topPagesResponseSchema, topSourcesResponseSchema, topSourcesSchema, userEventsResponseSchema, userPropertiesSchema };