@qikdev/sdk 0.1.180 → 0.1.182

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.
@@ -1,12 +1,10 @@
1
- import _get from 'lodash/get.js';
2
- import _isDate from 'lodash/isDate.js';
3
- import _startsWith from 'lodash/startsWith.js';
4
- import _isObject from 'lodash/isObject.js';
5
- import _camelCase from 'lodash/camelCase.js';
6
- import axios from 'axios';
7
- import { isBrowser, isNode } from 'browser-or-node';
8
-
9
-
1
+ import _get from "lodash/get.js";
2
+ import _isDate from "lodash/isDate.js";
3
+ import _startsWith from "lodash/startsWith.js";
4
+ import _isObject from "lodash/isObject.js";
5
+ import _camelCase from "lodash/camelCase.js";
6
+ import axios from "axios";
7
+ import { isBrowser, isNode } from "browser-or-node";
10
8
 
11
9
  ///////////////////////////////////////////////////////////////////////////////
12
10
 
@@ -14,8 +12,7 @@ const service = {};
14
12
 
15
13
  ////////////////////////////////////
16
14
 
17
- const loadedExternalScripts = {}
18
-
15
+ const loadedExternalScripts = {};
19
16
 
20
17
  /**
21
18
  * A function that dynamically include an external javascript resource
@@ -23,53 +20,46 @@ const loadedExternalScripts = {}
23
20
  * @alias utils.loadExternalScript
24
21
  * @param {String} url The url of the external script
25
22
  * @return {Promise} A promise that will be resolved once the script has been loaded
26
- * @example
27
- *
23
+ * @example
24
+ *
28
25
  * await sdk.utils.loadExternalScript('https://cdn.javascript.com/external/script.js');
29
26
  */
30
27
 
28
+ service.loadExternalScript = function (url) {
29
+ // If we already have a promise
30
+ if (loadedExternalScripts[url]) {
31
+ // return the existing promise
32
+ return loadedExternalScripts[url];
33
+ }
31
34
 
32
- service.loadExternalScript = function(url) {
35
+ // Create a new promise
36
+ const promise = (loadedExternalScripts[url] = new Promise(createNewScript));
33
37
 
34
- // If we already have a promise
35
- if (loadedExternalScripts[url]) {
36
- // return the existing promise
37
- return loadedExternalScripts[url];
38
+ function createNewScript(resolve, reject) {
39
+ if (!document) {
40
+ delete loadedExternalScripts[url];
41
+ return reject("document is undefined");
38
42
  }
39
43
 
44
+ //////////////////////////////////////
40
45
 
41
- // Create a new promise
42
- const promise = loadedExternalScripts[url] = new Promise(createNewScript);
43
-
44
- function createNewScript(resolve, reject) {
46
+ var script = document.createElement("script");
47
+ script.type = "text/javascript";
48
+ script.async = true;
49
+ script.onload = function () {
50
+ console.log("Loaded external script", url);
51
+ return resolve(url);
52
+ };
53
+ script.src = url;
45
54
 
46
- if (!document) {
47
- delete loadedExternalScripts[url];
48
- return reject('document is undefined')
49
- }
50
-
51
- //////////////////////////////////////
52
-
53
- var script = document.createElement('script');
54
- script.type = 'text/javascript';
55
- script.async = true;
56
- script.onload = function() {
57
- console.log('Loaded external script', url);
58
- return resolve(url);
59
- };
60
- script.src = url;
55
+ // Inject it into the document's <head> tag
56
+ document.head.appendChild(script);
57
+ }
61
58
 
62
- // Inject it into the document's <head> tag
63
- document.head.appendChild(script);
64
-
65
- }
66
-
67
- return promise;
68
- }
69
-
70
-
71
- const loadedExternalStyles = {}
59
+ return promise;
60
+ };
72
61
 
62
+ const loadedExternalStyles = {};
73
63
 
74
64
  /**
75
65
  * A function that dynamically include an external css resource
@@ -77,606 +67,794 @@ const loadedExternalStyles = {}
77
67
  * @alias utils.loadExternalStyle
78
68
  * @param {String} url The url of the external css
79
69
  * @return {Promise} A promise that will be resolved once the css has been loaded
80
- * @example
81
- *
70
+ * @example
71
+ *
82
72
  * await sdk.utils.loadExternalStyle('https://cdn.css.com/external/style.css');
83
73
  */
84
- service.loadExternalStyle = function(url) {
85
-
86
- const promise = new Promise(createNewScript);
87
-
88
- function createNewScript(resolve, reject) {
89
-
90
- if (!document) {
91
- return reject('document is undefined')
92
- }
93
-
94
- if (loadedExternalStyles[url]) {
95
- return resolve(url);
96
- }
74
+ service.loadExternalStyle = function (url) {
75
+ const promise = new Promise(createNewScript);
97
76
 
98
- // Avoid duplicate scripts
99
- loadedExternalStyles[url] = true;
77
+ function createNewScript(resolve, reject) {
78
+ if (!document) {
79
+ return reject("document is undefined");
80
+ }
100
81
 
101
- //////////////////////////////////////
82
+ if (loadedExternalStyles[url]) {
83
+ return resolve(url);
84
+ }
102
85
 
103
- var script = document.createElement('link');
104
- script.setAttribute('rel', 'stylesheet')
105
- script.setAttribute('type', 'text/css')
106
- script.setAttribute('href', url)
107
- script.onload = function() {
108
- console.log('Loaded external stylesheet', url);
109
- return resolve(url);
110
- };
86
+ // Avoid duplicate scripts
87
+ loadedExternalStyles[url] = true;
111
88
 
112
- // Inject it into the document's <head> tag
113
- document.head.appendChild(script);
89
+ //////////////////////////////////////
114
90
 
115
- }
91
+ var script = document.createElement("link");
92
+ script.setAttribute("rel", "stylesheet");
93
+ script.setAttribute("type", "text/css");
94
+ script.setAttribute("href", url);
95
+ script.onload = function () {
96
+ console.log("Loaded external stylesheet", url);
97
+ return resolve(url);
98
+ };
116
99
 
117
- return promise;
118
- }
100
+ // Inject it into the document's <head> tag
101
+ document.head.appendChild(script);
102
+ }
119
103
 
104
+ return promise;
105
+ };
120
106
 
121
107
  ///////////////////////////////////////////////////////////////////////////////
122
108
 
123
- service.exists = function(value) {
124
- var isUndefinedOrNull;
125
-
126
- ////////////////////////
127
-
128
- if (Array.isArray(value)) {
129
- return true;
130
- }
109
+ /**
110
+ * A helper function for checking whether a value is truthy/falsy
111
+ * @alias utils.exists
112
+ * @param {Anything} value The value to check
113
+ * @return {Boolean} whether the value is truthy
114
+ * @example
115
+ *
116
+ * sdk.utils.exists('undefined'); // false
117
+ * sdk.utils.exists([]); // true
118
+ * sdk.utils.exists(''); // false
119
+ * sdk.utils.exists(undefined); // false
120
+ */
121
+ service.exists = function (value) {
122
+ var isUndefinedOrNull;
131
123
 
132
- ////////////////////////
124
+ ////////////////////////
133
125
 
134
- if (value === 0) {
135
- return true;
136
- }
126
+ if (Array.isArray(value)) {
127
+ return true;
128
+ }
137
129
 
138
- ////////////////////////
139
-
140
- switch (typeof value) {
141
- case 'undefined':
142
- case 'null':
143
- isUndefinedOrNull = true;
144
- break;
145
- default:
146
- var string = String(value).toLowerCase();
147
- switch (string) {
148
- case '':
149
- case 'undefined':
150
- case 'null':
151
- isUndefinedOrNull = true;
152
- break;
153
- }
154
- break;
155
- }
130
+ ////////////////////////
156
131
 
157
- return !!!isUndefinedOrNull;
158
- }
132
+ if (value === 0) {
133
+ return true;
134
+ }
135
+
136
+ ////////////////////////
137
+
138
+ switch (typeof value) {
139
+ case "undefined":
140
+ case "null":
141
+ isUndefinedOrNull = true;
142
+ break;
143
+ default:
144
+ var string = String(value).toLowerCase();
145
+ switch (string) {
146
+ case "":
147
+ case "undefined":
148
+ case "null":
149
+ isUndefinedOrNull = true;
150
+ break;
151
+ }
152
+ break;
153
+ }
154
+
155
+ return !!!isUndefinedOrNull;
156
+ };
159
157
 
160
158
  //////////////////////////////////
161
159
 
162
- service.parseDate = function(input) {
163
-
164
- if (!input) {
165
- return;
166
- }
167
-
168
- if (_isDate(input)) {
169
- return input;
170
- }
171
-
172
- //Attempt to create a date
173
- var d = new Date(input);
174
- var isValid = d instanceof Date && !isNaN(d);
175
-
176
- if (isValid) {
177
- return d;
178
- }
179
-
160
+ /**
161
+ * A helper function for getting a javascript date object from some input
162
+ * returns undefined if it can not be parsed
163
+ * @alias utils.parseDate
164
+ * @param {String|Number} input The value to parse as a date
165
+ * @return {Date} the javascript date object
166
+ * @example
167
+ *
168
+ * sdk.utils.parseDate(input);
169
+ */
170
+ service.parseDate = function (input) {
171
+ if (!input) {
180
172
  return;
181
- }
182
-
183
- service.parseURL = function(string) {
184
-
185
- if (!string) {
186
- return false;
187
- }
188
-
189
- const relative = _startsWith(string, '/');
190
- if (relative) {
191
- return string;
192
- }
193
-
194
- if (_startsWith(string, '://')) {
195
- return string;
196
- }
197
-
198
- if (_startsWith(string, 'mailto:')) {
199
- return string;
200
- }
201
-
202
- if (_startsWith(string, 'tel:')) {
203
- return string;
204
- }
205
-
206
- if (_startsWith(string, 'sms:')) {
207
- return string;
208
- }
209
-
210
- //////////////////////////////////
211
- //If someone entered an email by accident
212
- var email = service.parseEmail(string);
213
- //Convert it to a mailto link
214
- if (email && email === string) {
215
- return `mailto:${email}`
216
- }
217
-
218
- //////////////////////////////////
219
-
220
- const withHttp = string => !/^https?:\/\//i.test(string) ? `http://${string}` : string;
221
- string = withHttp(string);
222
- //TODO: test this more.
223
- string = string.replace(/\s/g, '');
224
-
225
-
226
-
227
-
173
+ }
228
174
 
175
+ if (_isDate(input)) {
176
+ return input;
177
+ }
229
178
 
230
- var valid = RegExp('(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+@]*)*(\\?[;&a-z\\d%_.~+=-@]*)?(\\#[-a-z\\d_@]*)?$', 'i').test(string);
231
-
232
- if (!valid) {
233
- return false;
234
- }
235
-
179
+ //Attempt to create a date
180
+ var d = new Date(input);
181
+ var isValid = d instanceof Date && !isNaN(d);
236
182
 
183
+ if (isValid) {
184
+ return d;
185
+ }
237
186
 
238
- ///////////////////////////
239
-
240
- return withHttp(string)
241
- }
187
+ return;
188
+ };
242
189
 
190
+ /**
191
+ * A helper function for getting a full url string from some input
192
+ * @alias utils.parseURL
193
+ * @param {String} input The input value
194
+ * @return {String} the fully parsed URL
195
+ * @example
196
+ *
197
+ * sdk.utils.parseURL('google.com'); // Returns https://google.com
198
+ * sdk.utils.parseURL('mailto:hello@qik.dev'); // Returns 'mailto:hello@qik.dev'
199
+ * sdk.utils.parseURL('://hello.com'); // Returns '://hello.com'
200
+ * sdk.utils.parseURL('hello@email.com'); // Returns 'mailto:hello@email.com'
201
+ */
202
+ service.parseURL = function (string) {
203
+ if (!string) {
204
+ return false;
205
+ }
206
+
207
+ const relative = _startsWith(string, "/");
208
+ if (relative) {
209
+ return string;
210
+ }
211
+
212
+ if (_startsWith(string, "://")) {
213
+ return string;
214
+ }
215
+
216
+ if (_startsWith(string, "mailto:")) {
217
+ return string;
218
+ }
219
+
220
+ if (_startsWith(string, "tel:")) {
221
+ return string;
222
+ }
223
+
224
+ if (_startsWith(string, "sms:")) {
225
+ return string;
226
+ }
227
+
228
+ //////////////////////////////////
229
+ //If someone entered an email by accident
230
+ var email = service.parseEmail(string);
231
+ //Convert it to a mailto link
232
+ if (email && email === string) {
233
+ return `mailto:${email}`;
234
+ }
235
+
236
+ //////////////////////////////////
237
+
238
+ const withHttp = (string) =>
239
+ !/^https?:\/\//i.test(string) ? `http://${string}` : string;
240
+ string = withHttp(string);
241
+ //TODO: test this more.
242
+ string = string.replace(/\s/g, "");
243
+
244
+ var valid = RegExp(
245
+ "(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+@]*)*(\\?[;&a-z\\d%_.~+=-@]*)?(\\#[-a-z\\d_@]*)?$",
246
+ "i",
247
+ ).test(string);
248
+
249
+ if (!valid) {
250
+ return false;
251
+ }
252
+
253
+ ///////////////////////////
254
+
255
+ return withHttp(string);
256
+ };
243
257
 
244
258
  ///////////////////////////////////////////////
245
259
 
246
- service.parseNumber = function(input, decimalPoints) {
247
- if (!input) {
248
- return 0;
249
- }
250
-
251
- input = Number(input);
252
- if (isNaN(input)) {
253
- return 0;
254
- }
255
-
256
- if (decimalPoints) {
257
- var str = input.toFixed(decimalPoints);
258
- input = service.parseNumber(str);
259
- }
260
-
261
- return input;
262
- }
263
-
264
-
265
- service.isValidEmailAddress = function(email) {
266
-
267
- var tester = /^[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;
260
+ /**
261
+ * A helper function for getting a number from some input
262
+ * @alias utils.parseNumber
263
+ * @param {String} value The input value
264
+ * @param {Number} decimalPoints The number of decimal points to round to
265
+ * @return {Number} the parsed number value
266
+ * @example
267
+ *
268
+ * sdk.utils.parseNumber('123'); // Returns 123
269
+ * sdk.utils.parseNumber('75.501', 2); // Returns 75.5
270
+ * sdk.utils.parseNumber(''); // Returns 0
271
+ * sdk.utils.parseNumber(null); // Returns 0
272
+ * sdk.utils.parseNumber(); // Returns 0
273
+ */
274
+ service.parseNumber = function (input, decimalPoints) {
275
+ if (!input) {
276
+ return 0;
277
+ }
268
278
 
269
- if (!email) return false;
279
+ input = Number(input);
280
+ if (isNaN(input)) {
281
+ return 0;
282
+ }
270
283
 
271
- var emailParts = email.split('@');
284
+ if (decimalPoints) {
285
+ var str = input.toFixed(decimalPoints);
286
+ input = service.parseNumber(str);
287
+ }
272
288
 
273
- if (emailParts.length !== 2) return false
289
+ return input;
290
+ };
274
291
 
275
- var account = emailParts[0];
276
- var address = emailParts[1];
292
+ /**
293
+ * A helper function for getting a number from some input
294
+ * @alias utils.isValidEmailAddress
295
+ * @param {String} emailAddress The email to validate
296
+ * @return {Boolean} whether or not the input is a valid email address
297
+ * @example
298
+ *
299
+ * sdk.utils.isValidEmailAddress('123.com'); // Returns false
300
+ * sdk.utils.isValidEmailAddress('hello@world.com'); // Returns true
301
+ * sdk.utils.isValidEmailAddress('something@special.io'); // Returns true
302
+ */
303
+ service.isValidEmailAddress = function (email) {
304
+ var tester =
305
+ /^[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;
277
306
 
278
- if (account.length > 64) return false
307
+ if (!email) return false;
279
308
 
280
- else if (address.length > 255) return false
309
+ var emailParts = email.split("@");
281
310
 
282
- var domainParts = address.split('.');
283
- if (domainParts.some(function(part) {
284
- return part.length > 63;
285
- })) return false;
311
+ if (emailParts.length !== 2) return false;
286
312
 
313
+ var account = emailParts[0];
314
+ var address = emailParts[1];
287
315
 
288
- if (!tester.test(email)) return false;
316
+ if (account.length > 64) return false;
317
+ else if (address.length > 255) return false;
289
318
 
290
- return true;
291
- }
319
+ var domainParts = address.split(".");
320
+ if (
321
+ domainParts.some(function (part) {
322
+ return part.length > 63;
323
+ })
324
+ )
325
+ return false;
292
326
 
327
+ if (!tester.test(email)) return false;
293
328
 
294
- service.parseEmail = function(input) {
329
+ return true;
330
+ };
295
331
 
296
- if (!input) {
297
- return false;
298
- }
332
+ /**
333
+ * A helper function for getting a formatted email address
334
+ * @alias utils.parseEmail
335
+ * @param {String} emailAddress The input to parse as an email
336
+ * @return {String|Boolean} a valid email address in lowercase, or false if parse is not possible
337
+ * @example
338
+ *
339
+ * sdk.utils.parseEmail('ToMack@gmail.com'); // returns 'tomack@gmail.com'
340
+ * sdk.utils.isValidEmailAddress('hello.world.com'); // Returns false
341
+ */
342
+ service.parseEmail = function (input) {
343
+ if (!input) {
344
+ return false;
345
+ }
299
346
 
300
- var lowercase = String(input).toLowerCase();
301
- var valid = service.isValidEmailAddress(lowercase);
347
+ var lowercase = String(input).toLowerCase();
348
+ var valid = service.isValidEmailAddress(lowercase);
302
349
 
303
- if (!valid) {
304
- return false;
305
- } else {
306
- return lowercase;
307
- }
308
- }
350
+ if (!valid) {
351
+ return false;
352
+ } else {
353
+ return lowercase;
354
+ }
355
+ };
309
356
 
310
357
  //////////////////////////////////
311
358
 
312
- service.parseInt = function(input) {
313
- if (!input) {
314
- return 0;
315
- }
316
-
317
- input = parseInt(input);
318
- if (isNaN(input)) {
319
- return 0;
320
- }
321
-
322
- return input;
323
- }
324
-
325
-
326
-
327
- service.cleanValue = function(data, type, options) {
359
+ /**
360
+ * A helper function for getting an integer
361
+ * @alias utils.parseInt
362
+ * @param {String|Number} input The input to parse as an integer
363
+ * @return {Integer} the resulting integer or 0
364
+ * @example
365
+ *
366
+ * sdk.utils.parseInt('134'); // returns 134
367
+ * sdk.utils.parseInt('cows'); // returns 0
368
+ * sdk.utils.parseInt(); // returns 0
369
+ */
370
+ service.parseInt = function (input) {
371
+ if (!input) {
372
+ return 0;
373
+ }
328
374
 
329
- if (!options) {
330
- options = {};
331
- }
375
+ input = parseInt(input);
376
+ if (isNaN(input)) {
377
+ return 0;
378
+ }
332
379
 
333
- ////////////////////////
380
+ return input;
381
+ };
334
382
 
335
- var noInputValue = service.exists(data);
336
- if (options.strict && noInputValue && type != 'boolean') {
383
+ /**
384
+ * A helper function for cleaning an input value to match
385
+ * a required type
386
+ * @alias utils.cleanValue
387
+ * @param {*} data The input to clean
388
+ * @param {String} type The data type to parse
389
+ * @param {Object} options Additional options for parsing
390
+ * @return {*} the resulting cleaned value
391
+ * @example
392
+ *
393
+ * sdk.utils.cleanValue({_id:'1234', title:'Item'...}, 'reference'); // returns '1234'
394
+ * sdk.utils.cleanValue('true', 'boolean'); // returns true
395
+ * sdk.utils.cleanValue('Mr Rogers House', 'key'); // returns 'mrRogersHouse';
396
+ * sdk.utils.cleanValue('Hello.World@email.COM', 'email'); // returns 'hello.world@email.com';
397
+ */
398
+ service.cleanValue = function (data, type, options) {
399
+ if (!options) {
400
+ options = {};
401
+ }
402
+
403
+ ////////////////////////
404
+
405
+ var noInputValue = service.exists(data);
406
+ if (options.strict && noInputValue && type != "boolean") {
407
+ return data;
408
+ }
409
+
410
+ ////////////////////////
411
+
412
+ switch (type) {
413
+ case "reference":
414
+ return service.id(data, true);
415
+ break;
416
+ case "boolean":
417
+ return service.parseBoolean(data);
418
+ break;
419
+ case "url":
420
+ return service.parseURL(data);
421
+ break;
422
+ case "key":
423
+ return service.machineName(data);
424
+ break;
425
+ case "email":
426
+ return service.parseEmail(data);
427
+ break;
428
+ case "date":
429
+ var parsed = service.parseDate(data, options);
430
+
431
+ if (parsed === undefined) {
432
+ return;
433
+ } else {
434
+ return parsed;
435
+ }
436
+ break;
437
+ case "number":
438
+ case "decimal":
439
+ case "float":
440
+ var val = service.parseNumber(data);
441
+ if (String(val) == String(Number(data))) {
442
+ return val;
443
+ }
444
+ return;
445
+ break;
446
+ case "integer":
447
+ var val = service.parseInt(data);
448
+ if (String(val) == String(parseInt(data))) {
449
+ return val;
450
+ }
451
+ return;
452
+ break;
453
+ case "group":
454
+ return data;
455
+ break;
456
+ case "object":
457
+ if (_isObject(data) && !Array.isArray(data)) {
337
458
  return data;
338
- }
339
-
340
- ////////////////////////
341
-
342
- switch (type) {
343
- case 'reference':
344
- return service.id(data, true);
345
- break;
346
- case 'boolean':
347
- return service.parseBoolean(data);
348
- break;
349
- case 'url':
350
- return service.parseURL(data);
351
- break;
352
- case 'key':
353
- return service.machineName(data);
354
- break;
355
- case 'email':
356
- return service.parseEmail(data);
357
- break;
358
- case 'date':
359
- var parsed = service.parseDate(data, options);
360
-
361
- if (parsed === undefined) {
362
- return;
363
- } else {
364
- return parsed;
365
- }
366
- break;
367
- case 'number':
368
- case 'decimal':
369
- case 'float':
370
- var val = service.parseNumber(data);
371
- if (String(val) == String(Number(data))) {
372
- return val;
373
- }
374
- return;
375
- break;
376
- case 'integer':
377
- var val = service.parseInt(data);
378
- if (String(val) == String(parseInt(data))) {
379
- return val;
380
- }
381
- return;
382
- break;
383
- case 'group':
384
- return data;
385
- break;
386
- case 'object':
387
- if (_isObject(data) && !Array.isArray(data)) {
388
- return data
389
- }
390
-
391
- return;
392
- break;
393
- case 'string':
394
- if (service.exists(data)) {
395
- var stringed = String(data);
396
- if (stringed == '[object Object]') {
397
- return;
398
- }
399
-
400
- return stringed
401
- } else {
402
- return;
403
- }
404
-
405
- // if(!data) {
406
- // return '';
407
- // }
408
-
409
- // if(Array.isArray(data)) {
410
- // return JSON.stringify(data);
411
- // }
412
-
413
- // if(Object.isObject(data)) {
414
- // return JSON.stringify(data);
415
- // }
416
-
417
- // return String(data);
418
-
419
- // break;
420
- default:
421
- return String(data)
422
- break;
423
- }
424
- }
425
-
426
-
427
-
428
- service.isValidValue = function(value, dataType, strict) {
429
-
430
- var isValue = service.exists(value);
431
- var valueIsNumber = (typeof value == 'number')
432
-
433
- ////////////////////////
459
+ }
460
+
461
+ return;
462
+ break;
463
+ case "string":
464
+ if (service.exists(data)) {
465
+ var stringed = String(data);
466
+ if (stringed == "[object Object]") {
467
+ return;
468
+ }
434
469
 
435
- var isValidEntry = false;
470
+ return stringed;
471
+ } else {
472
+ return;
473
+ }
474
+
475
+ // if(!data) {
476
+ // return '';
477
+ // }
478
+
479
+ // if(Array.isArray(data)) {
480
+ // return JSON.stringify(data);
481
+ // }
482
+
483
+ // if(Object.isObject(data)) {
484
+ // return JSON.stringify(data);
485
+ // }
486
+
487
+ // return String(data);
488
+
489
+ // break;
490
+ default:
491
+ return String(data);
492
+ break;
493
+ }
494
+ };
495
+
496
+ service.isValidValue = function (value, dataType, strict) {
497
+ var isValue = service.exists(value);
498
+ var valueIsNumber = typeof value == "number";
499
+
500
+ ////////////////////////
501
+
502
+ var isValidEntry = false;
503
+
504
+ if (!isValue) {
505
+ return false;
506
+ }
507
+
508
+ ////////////////////////
509
+
510
+ switch (dataType) {
511
+ case "url":
512
+ if (strict) {
513
+ isValidEntry =
514
+ _startsWith(value, "/") ||
515
+ _startsWith(value, "://") ||
516
+ _startsWith(value, "http://") ||
517
+ _startsWith(value, "https://");
518
+ } else {
519
+ isValidEntry = String(value) === service.parseURL(value);
520
+ }
521
+ break;
522
+ case "key":
523
+ isValidEntry = String(value) === service.machineName(value);
524
+ break;
525
+ case "date":
526
+ //If we are being strict
527
+ if (strict) {
528
+ //And the input is not a javascript date object
529
+ if (typeof value != "object" || !_isDate(value)) {
530
+ return false;
531
+ }
532
+ }
533
+
534
+ ///////////////////////////////
535
+ var parsed = service.parseDate(value);
536
+ return parsed !== undefined;
537
+ break;
538
+ case "email":
539
+ if (strict) {
540
+ isValidEntry = value === service.parseEmail(value);
541
+ } else {
542
+ isValidEntry =
543
+ String(value).toLowerCase() === service.parseEmail(value);
544
+ }
545
+
546
+ break;
547
+ case "number":
548
+ case "decimal":
549
+ case "float":
550
+ if (strict) {
551
+ isValidEntry =
552
+ valueIsNumber && Number(value) === service.parseNumber(value);
553
+ } else {
554
+ isValidEntry = Number(value) === service.parseNumber(value);
555
+ }
556
+ break;
557
+ case "integer":
558
+ if (strict) {
559
+ isValidEntry =
560
+ valueIsNumber && Number(value) === service.parseInt(value);
561
+ } else {
562
+ isValidEntry = Number(value) === service.parseInt(value);
563
+ }
564
+ break;
565
+ case "boolean":
566
+ var parsed = service.parseBoolean(value);
567
+
568
+ //Only accept true booleans
569
+ if (strict) {
570
+ if (value === true || value === false) {
571
+ isValidEntry = value === parsed;
572
+ }
573
+ } else {
574
+ isValidEntry = parsed === true || parsed === false;
575
+ }
576
+ break;
577
+ case "reference":
578
+ if (strict) {
579
+ isValidEntry = String(value) === service.id(value);
580
+ } else {
581
+ isValidEntry = !!service.id(value);
582
+ }
583
+ break;
584
+ case "string":
585
+ var checkString = String(value);
586
+ if (strict) {
587
+ if (typeof value != "string") {
588
+ return false;
589
+ }
590
+ }
436
591
 
437
- if (!isValue) {
592
+ if (checkString == "[object Object]") {
438
593
  return false;
439
- }
594
+ }
595
+
596
+ isValidEntry = true;
597
+ break;
598
+ // case 'group':
599
+ // isValidEntry = _isObject(value);
600
+ // break;
601
+ case "object":
602
+ isValidEntry = _isObject(value) && !Array.isArray(value);
603
+ break;
604
+ case "array":
605
+ isValidEntry = Array.isArray(value);
606
+ break;
607
+ }
608
+
609
+ ////////////////////////
610
+
611
+ return isValidEntry;
612
+ };
440
613
 
441
- ////////////////////////
442
-
443
- switch (dataType) {
444
-
445
- case 'url':
446
- if (strict) {
447
- isValidEntry = _startsWith(value, '/') || _startsWith(value, '://') || _startsWith(value, 'http://') || _startsWith(value, 'https://');
448
- } else {
449
- isValidEntry = String(value) === service.parseURL(value);
450
- }
451
- break;
452
- case 'key':
453
- isValidEntry = String(value) === service.machineName(value);
454
- break;
455
- case 'date':
456
-
457
- //If we are being strict
458
- if (strict) {
459
- //And the input is not a javascript date object
460
- if (typeof value != 'object' || !_isDate(value)) {
461
- return false;
462
- }
463
- }
464
-
465
- ///////////////////////////////
466
- var parsed = service.parseDate(value);
467
- return parsed !== undefined;
468
- break;
469
- case 'email':
470
-
471
- if (strict) {
472
- isValidEntry = value === service.parseEmail(value);
473
- } else {
474
- isValidEntry = String(value).toLowerCase() === service.parseEmail(value);
475
- }
476
-
477
- break;
478
- case 'number':
479
- case 'decimal':
480
- case 'float':
481
- if (strict) {
482
- isValidEntry = valueIsNumber && (Number(value) === service.parseNumber(value));
483
- } else {
484
- isValidEntry = Number(value) === service.parseNumber(value);
485
- }
486
- break;
487
- case 'integer':
488
- if (strict) {
489
- isValidEntry = valueIsNumber && (Number(value) === service.parseInt(value));
490
- } else {
491
- isValidEntry = Number(value) === service.parseInt(value);
492
- }
493
- break;
494
- case 'boolean':
495
-
496
- var parsed = service.parseBoolean(value);
497
-
498
- //Only accept true booleans
499
- if (strict) {
500
- if (value === true || value === false) {
501
- isValidEntry = value === parsed;
502
- }
503
- } else {
504
- isValidEntry = parsed === true || parsed === false;
505
- }
506
- break;
507
- case 'reference':
508
- if (strict) {
509
- isValidEntry = String(value) === service.id(value);
510
- } else {
511
- isValidEntry = !!service.id(value);
512
- }
513
- break;
514
- case 'string':
515
- var checkString = String(value);
516
- if (strict) {
517
- if (typeof value != 'string') {
518
- return false;
519
- }
520
- }
521
-
522
- if (checkString == '[object Object]') {
523
- return false;
524
- }
525
-
526
- isValidEntry = true;
527
- break;
528
- // case 'group':
529
- // isValidEntry = _isObject(value);
530
- // break;
531
- case 'object':
532
-
533
-
534
- isValidEntry = _isObject(value) && !Array.isArray(value);
535
- break;
536
- case 'array':
537
- isValidEntry = Array.isArray(value);
538
- break;
539
- }
614
+ /**
615
+ * A helper function for parsing input as boolean values
616
+ * @alias utils.parseBoolean
617
+ * @param {*} value The input to parse
618
+ * @return {Boolean} the resulting true/false value
619
+ * @example
620
+ *
621
+ * sdk.utils.parseBoolean('true'); // returns true
622
+ * sdk.utils.parseBoolean('y'); // returns true
623
+ * sdk.utils.parseBoolean('YES'); // returns true
624
+ * sdk.utils.parseBoolean('1'); // returns true
625
+ * sdk.utils.parseBoolean('t'); // returns true
626
+ * sdk.utils.parseBoolean(''); // returns false
627
+ * sdk.utils.parseBoolean('0'); // returns false
628
+ * sdk.utils.parseBoolean('n'); // returns false
629
+ * sdk.utils.parseBoolean('no'); // returns false
630
+ * sdk.utils.parseBoolean('f'); // returns false
631
+ * sdk.utils.parseBoolean('null'); // returns false
632
+ */
633
+ service.parseBoolean = function (value) {
634
+ switch (String(value).toLowerCase()) {
635
+ case "true":
636
+ case "y":
637
+ case "yes":
638
+ case "1":
639
+ case "t":
640
+ value = true;
641
+ break;
642
+ case "false":
643
+ case "n":
644
+ case "no":
645
+ case "0":
646
+ case "f":
647
+ case "undefined":
648
+ case "null":
649
+ case "":
650
+ case "-1":
651
+ value = false;
652
+ break;
653
+ }
654
+
655
+ return !!value;
656
+ };
540
657
 
541
- ////////////////////////
658
+ ///////////////////////////////////////////////////////////////////////////////
542
659
 
543
- return isValidEntry
544
- }
660
+ service.clone = function (input) {
661
+ return JSON.parse(JSON.stringify(input));
662
+ };
545
663
 
546
- service.parseBoolean = function(value) {
547
- switch (String(value).toLowerCase()) {
548
- case 'true':
549
- case 'y':
550
- case 'yes':
551
- case '1':
552
- case 't':
553
- value = true;
554
- break;
555
- case 'false':
556
- case 'n':
557
- case 'no':
558
- case '0':
559
- case 'f':
560
- case 'undefined':
561
- case 'null':
562
- case '':
563
- case '-1':
564
- value = false;
565
- break;
566
- }
664
+ ///////////////////////////////////////////////////////////////////////////////
567
665
 
568
- return !!value;
569
- }
666
+ service.getAllFields = function (actualDefinition) {
667
+ const self = this;
668
+ const isProfile =
669
+ actualDefinition.definesType === "profile" ||
670
+ actualDefinition.key === "profile";
671
+ const isFormSubmission = actualDefinition.definesType === "submission";
672
+ var allFields = [...actualDefinition.fields];
673
+ var definedFields = actualDefinition.definedFields || [];
674
+
675
+ if (definedFields.length) {
676
+ if (isFormSubmission) {
677
+ var formDataFields = {
678
+ title: `Form Data`,
679
+ minimum: 1,
680
+ maximum: 1,
681
+ key: "formData",
682
+ asObject: true,
683
+ type: "group",
684
+ fields: definedFields,
685
+ };
686
+
687
+ allFields.push(formDataFields);
688
+
689
+ const cleanedDataFields = definedFields.map(function (field) {
690
+ if (field.type === "reference") {
691
+ field = JSON.parse(JSON.stringify(field));
692
+ delete field.fields;
693
+ }
570
694
 
695
+ return field;
696
+ });
571
697
 
698
+ var dataFields = {
699
+ title: `Data`,
700
+ minimum: 1,
701
+ maximum: 1,
702
+ key: "data",
703
+ asObject: true,
704
+ type: "group",
705
+ fields: cleanedDataFields,
706
+ };
572
707
 
708
+ allFields.push(dataFields);
709
+ } else {
710
+ var dataFields = {
711
+ title: `${actualDefinition.title}`,
712
+ minimum: 1,
713
+ maximum: 1,
714
+ key: "data",
715
+ asObject: true,
716
+ type: "group",
717
+ fields: definedFields,
718
+ };
719
+
720
+ allFields.push(dataFields);
721
+ }
722
+ }
723
+
724
+ if (isProfile) {
725
+ allFields.push({
726
+ title: "Age",
727
+ key: "_age",
728
+ minimum: 1,
729
+ maximum: 1,
730
+ type: "integer",
731
+ });
573
732
 
574
- ///////////////////////////////////////////////////////////////////////////////
733
+ allFields.push({
734
+ title: "Date of birth",
735
+ key: "_dob",
736
+ minimum: 1,
737
+ maximum: 1,
738
+ type: "date",
739
+ });
740
+ }
741
+
742
+ var mapped = service
743
+ .mapFields(allFields)
744
+ .filter(function (field) {
745
+ var isObject =
746
+ field.type == "group" &&
747
+ field.asObject &&
748
+ field.minimum == 1 &&
749
+ field.maximum == 1;
750
+ return !isObject;
751
+ })
752
+ .map(function (field) {
753
+ field.title =
754
+ field.filterTitle || field.titles.filter(Boolean).join(" › ");
575
755
 
576
- service.clone = function(input) {
577
- return JSON.parse(JSON.stringify(input));
578
- }
756
+ return field;
757
+ })
758
+ .sort(function (a, b) {
759
+ return a.title < b.title ? -1 : 1;
760
+ });
579
761
 
762
+ return mapped;
763
+ };
580
764
  ///////////////////////////////////////////////////////////////////////////////
581
765
 
582
- service.mapFields = function(fields, options) {
583
-
584
- if (!options) {
585
- options = {};
586
- }
766
+ service.mapFields = function (fields, options) {
767
+ if (!options) {
768
+ options = {};
769
+ }
587
770
 
588
- //////////////////////////////
771
+ //////////////////////////////
589
772
 
590
- var output = [];
591
- var trail = [];
592
- var titles = [];
593
- var currentDepth = 1;
594
- var depthLimit = options.depth;
595
- var delimiter = options.arrayDelimeter || '[]';
773
+ var output = [];
774
+ var trail = [];
775
+ var titles = [];
776
+ var currentDepth = 1;
777
+ var depthLimit = options.depth;
778
+ var delimiter = options.arrayDelimeter || "[]";
596
779
 
780
+ //Loop through each field
781
+ fields.forEach(mapField);
597
782
 
598
- //Loop through each field
599
- fields.forEach(mapField);
783
+ //////////////////////////////
600
784
 
601
- //////////////////////////////
785
+ //Recursively map the fields
786
+ function mapField(field, i) {
787
+ var fieldKey = field.key;
788
+ var isGroup = field.type == "group";
789
+ var singleValue = field.minimum === field.maximum && field.minimum === 1;
790
+ var asObject = field.asObject; // || (isGroup && singleValue);
791
+ var isLayout = isGroup && !asObject;
602
792
 
603
- //Recursively map the fields
604
- function mapField(field, i) {
605
- var fieldKey = field.key;
606
- var isGroup = field.type == 'group';
607
- var singleValue = (field.minimum === field.maximum) && field.minimum === 1;
608
- var asObject = field.asObject; // || (isGroup && singleValue);
609
- var isLayout = isGroup && !asObject;
793
+ //////////////////////////////////
610
794
 
611
- //////////////////////////////////
795
+ // Whether to clone the field or use the existing reference
796
+ var mapped = options.original ? field : service.clone(field);
612
797
 
613
- // Whether to clone the field or use the existing reference
614
- var mapped = options.original ? field : service.clone(field);
798
+ mapped.trail = trail.slice();
799
+ mapped.trail.push(fieldKey);
615
800
 
616
- mapped.trail = trail.slice();
617
- mapped.trail.push(fieldKey)
801
+ mapped.path = mapped.trail.join(".");
802
+ mapped.titles = titles.slice();
803
+ mapped.titles.push(field.filterTitle || field.title || "");
618
804
 
619
- mapped.path = mapped.trail.join('.');
620
- mapped.titles = titles.slice();
621
- mapped.titles.push(field.title || '')
805
+ const isNotLayoutOrIsAllowed = !isLayout || options.includeLayout;
622
806
 
807
+ //If its an actual element or we've asked to include
808
+ //layout only elements
809
+ if (isNotLayoutOrIsAllowed) {
810
+ //Add it to the mix
811
+ output.push(mapped);
812
+ }
623
813
 
624
- const isNotLayoutOrIsAllowed = (!isLayout || options.includeLayout);
814
+ //////////////////////////////////
625
815
 
626
- //If its an actual element or we've asked to include
627
- //layout only elements
628
- if (isNotLayoutOrIsAllowed) {
629
- //Add it to the mix
630
- output.push(mapped);
816
+ //Now see if there are child fields and should we go further
817
+ var limitHit = depthLimit && currentDepth >= depthLimit;
818
+
819
+ //If there are child fields for this field
820
+ if (field.fields && field.fields.length) {
821
+ //If it's just a group with no extra key
822
+ if (isLayout) {
823
+ //Loop through fields as if they are at the same depth
824
+ field.fields.forEach(mapField);
825
+ } else {
826
+ //We don't need to traverse any further
827
+ //because we hit the limit
828
+ if (limitHit) {
829
+ return;
631
830
  }
632
831
 
633
- //////////////////////////////////
634
-
635
- //Now see if there are child fields and should we go further
636
- var limitHit = depthLimit && (currentDepth >= depthLimit);
637
-
638
- //If there are child fields for this field
639
- if (field.fields && field.fields.length) {
640
- //If it's just a group with no extra key
641
- if (isLayout) {
642
- //Loop through fields as if they are at the same depth
643
- field.fields.forEach(mapField)
644
- } else {
645
-
646
- //We don't need to traverse any further
647
- //because we hit the limit
648
- if (limitHit) {
649
- return;
650
- }
651
-
652
- //Move down a level and add to the object
653
- //Include the key in the path trail
654
- currentDepth++;
655
-
656
- let injectKey = fieldKey;
657
- if (options.includeArrayDelimeter) {
658
- if (!singleValue) {
659
- injectKey = `${fieldKey}${delimiter}`
660
- }
661
- }
662
- trail.push(injectKey)
663
- titles.push(field.title);
664
-
665
- //Loop through each field
666
- field.fields.forEach(mapField)
667
-
668
- //Move back up a level before we go to the next field
669
- currentDepth--;
670
- trail.pop();
671
- titles.pop();
672
- }
832
+ //Move down a level and add to the object
833
+ //Include the key in the path trail
834
+ currentDepth++;
673
835
 
836
+ let injectKey = fieldKey;
837
+ if (options.includeArrayDelimeter) {
838
+ if (!singleValue) {
839
+ injectKey = `${fieldKey}${delimiter}`;
840
+ }
674
841
  }
842
+ trail.push(injectKey);
843
+ titles.push(field.filterTitle || field.title);
675
844
 
845
+ //Loop through each field
846
+ field.fields.forEach(mapField);
847
+
848
+ //Move back up a level before we go to the next field
849
+ currentDepth--;
850
+ trail.pop();
851
+ titles.pop();
852
+ }
676
853
  }
854
+ }
677
855
 
678
- return output;
679
- }
856
+ return output;
857
+ };
680
858
 
681
859
  ///////////////////////////////////////////////////////////////////////////////
682
860
 
@@ -685,36 +863,31 @@ service.mapFields = function(fields, options) {
685
863
  * @alias utils.mapParameters
686
864
  * @param {Object} parameters The object you want to transalte
687
865
  * @return {String} The query string
688
- * @example
866
+ * @example
689
867
  * //Returns &this=that&hello=world
690
868
  * sdk.utils.mapParameters({"this":"that", "hello":"world"})
691
869
  */
692
- service.mapParameters = function(parameters) {
693
-
694
- parameters = parameters || {}
695
-
696
- var array = [];
697
-
698
- Object.entries(parameters)
699
- .forEach(function([key, value]) {
700
-
701
- if (value === undefined || value === null || value == false) {
702
- return;
703
- }
870
+ service.mapParameters = function (parameters) {
871
+ parameters = parameters || {};
704
872
 
705
- if (Array.isArray(value)) {
706
- value.forEach(function(v) {
707
- array.push(`${key}=${encodeURIComponent(v)}`);
708
- })
709
- } else {
710
- array.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
711
- }
873
+ var array = [];
712
874
 
713
- })
875
+ Object.entries(parameters).forEach(function ([key, value]) {
876
+ if (value === undefined || value === null || value == false) {
877
+ return;
878
+ }
714
879
 
715
- return array.join('&');
880
+ if (Array.isArray(value)) {
881
+ value.forEach(function (v) {
882
+ array.push(`${key}=${encodeURIComponent(v)}`);
883
+ });
884
+ } else {
885
+ array.push(encodeURIComponent(key) + "=" + encodeURIComponent(value));
886
+ }
887
+ });
716
888
 
717
- }
889
+ return array.join("&");
890
+ };
718
891
 
719
892
  ///////////////////////////////////////////////////////////////////////////////
720
893
 
@@ -724,210 +897,197 @@ service.mapParameters = function(parameters) {
724
897
  * @param {Integer} value The amount in cents
725
898
  * @param {String} currency The currency to format
726
899
  * @return {String} The formatted value
727
- * @example
728
- *
900
+ * @example
901
+ *
729
902
  * //Returns £10.00
730
903
  * sdk.utils.formatCurrency(1000, 'gbp');
731
- *
904
+ *
732
905
  * //Returns $10.00
733
906
  * sdk.utils.formatCurrency(1000, 'usd');
734
- *
907
+ *
735
908
  */
736
- service.formatCurrency = function(value, currency, decimalPoints) {
737
-
738
- if (!value || isNaN(value)) {
739
- value = 0;
740
- }
741
-
742
- decimalPoints = decimalPoints || 2;
743
-
744
- var currencyPrefix = service.currencySymbol(currency);
745
- return `${currencyPrefix}${parseFloat(Number(value) / 100).toFixed(decimalPoints)}`;
746
-
747
- }
909
+ service.formatCurrency = function (value, currency, decimalPoints) {
910
+ if (!value || isNaN(value)) {
911
+ value = 0;
912
+ }
748
913
 
914
+ decimalPoints = decimalPoints || 2;
749
915
 
916
+ var currencyPrefix = service.currencySymbol(currency);
917
+ return `${currencyPrefix}${parseFloat(Number(value) / 100).toFixed(decimalPoints)}`;
918
+ };
750
919
 
751
920
  /**
752
921
  * A function that will take an id and return the type key
753
922
  * @alias utils.getTypeFromID
754
923
  * @param {String} id The id of an object
755
924
  * @return {String} The key
756
- * @example
757
- *
925
+ * @example
926
+ *
758
927
  * // Returns 'user'
759
928
  * sdk.utils.getTypeFromID('52b523f775beea960013f6cd');
760
929
  *
761
930
  * // Returns 'role'
762
931
  * sdk.utils.getTypeFromID('62b59cb572fb4772e7b5fa93');
763
- *
932
+ *
764
933
  */
765
- service.getTypeFromID = function(id) {
766
-
767
- id = service.id(id);
768
-
769
- if (!id) {
770
- return;
771
- }
772
-
773
- const lookup = {
774
- "21": "organisation",
775
- "23": "comment",
776
- "24": "persona",
777
- "25": "audio",
778
- "26": "campaign",
779
- "28": "smartlist",
780
- "29": "cache",
781
- "40": "application",
782
- "41": "action",
783
- "42": "billinginvoice",
784
- "43": "componentsnapshot",
785
- "44": "diff",
786
- "45": "email",
787
- "46": "submission",
788
- "49": "import",
789
- "53": "socket",
790
- "54": "timetrigger",
791
- "61": "article",
792
- "63": "component",
793
- "65": "event",
794
- "66": "file",
795
- "67": "tag",
796
- "69": "image",
797
- "70": "profile",
798
- "72": "role",
799
- "73": "scope",
800
- "74": "transaction",
801
- "75": "user",
802
- "76": "video",
803
- "77": "workflowcard",
804
- "78": "variable",
805
- "3c": "patoken",
806
- "7b": "uatoken",
807
- "7d": "urtoken",
808
- "2d": "systemtask",
809
- "3d": "export",
810
- "5f": "systemflag",
811
- "2b": "batch",
812
- "3a": "log",
813
- "2e": "stat",
814
- "2f": "unsubscribe",
815
- "6b": "intent",
816
- "7c": "upload",
817
- "2c": "systemtrigger",
818
- "6e": "interface",
819
- "4e": "interfacesnapshot",
820
- "4f": "notification",
821
- "2a": "definition",
822
- "7e": "definitionsnapshot",
823
- "5e": "integration",
824
- "4c": "listener",
825
- "6d": "topic",
826
- "7a": "code",
827
- "4d": "paymentmethod",
828
- "6c": "sslcertificate"
829
- }
830
-
831
- var hexKey = id.slice(8, 10);
832
- return lookup[hexKey];
833
- }
934
+ service.getTypeFromID = function (id) {
935
+ id = service.id(id);
834
936
 
937
+ if (!id) {
938
+ return;
939
+ }
940
+
941
+ const lookup = {
942
+ 21: "organisation",
943
+ 23: "comment",
944
+ 24: "persona",
945
+ 25: "audio",
946
+ 26: "campaign",
947
+ 28: "smartlist",
948
+ 29: "cache",
949
+ 40: "application",
950
+ 41: "action",
951
+ 42: "billinginvoice",
952
+ 43: "componentsnapshot",
953
+ 44: "diff",
954
+ 45: "email",
955
+ 46: "submission",
956
+ 49: "import",
957
+ 53: "socket",
958
+ 54: "timetrigger",
959
+ 61: "article",
960
+ 63: "component",
961
+ 65: "event",
962
+ 66: "file",
963
+ 67: "tag",
964
+ 69: "image",
965
+ 70: "profile",
966
+ 72: "role",
967
+ 73: "scope",
968
+ 74: "transaction",
969
+ 75: "user",
970
+ 76: "video",
971
+ 77: "workflowcard",
972
+ 78: "variable",
973
+ "3c": "patoken",
974
+ "7b": "uatoken",
975
+ "7d": "urtoken",
976
+ "2d": "systemtask",
977
+ "3d": "export",
978
+ "5f": "systemflag",
979
+ "2b": "batch",
980
+ "3a": "log",
981
+ "2e": "stat",
982
+ "2f": "unsubscribe",
983
+ "6b": "intent",
984
+ "7c": "upload",
985
+ "2c": "systemtrigger",
986
+ "6e": "interface",
987
+ "4e": "interfacesnapshot",
988
+ "4f": "notification",
989
+ "2a": "definition",
990
+ "7e": "definitionsnapshot",
991
+ "5e": "integration",
992
+ "4c": "listener",
993
+ "6d": "topic",
994
+ "7a": "code",
995
+ "4d": "paymentmethod",
996
+ "6c": "sslcertificate",
997
+ };
998
+
999
+ var hexKey = id.slice(8, 10);
1000
+ return lookup[hexKey];
1001
+ };
835
1002
 
836
1003
  /**
837
1004
  * A function that will take a currency string and return the symbol
838
1005
  * @alias utils.currencySymbol
839
1006
  * @param {String} currency The currency
840
1007
  * @return {String} The symbol
841
- * @example
842
- *
1008
+ * @example
1009
+ *
843
1010
  * //Returns £
844
1011
  * sdk.utils.currencySymbol('gbp');
845
- *
1012
+ *
846
1013
  * //Returns $
847
1014
  * sdk.utils.currencySymbol('usd');
848
- *
1015
+ *
849
1016
  */
850
- service.currencySymbol = function(currency) {
851
- //Ensure lowercase currency
852
- currency = String(currency).toLowerCase();
853
-
854
- switch (String(currency).toLowerCase()) {
855
- case 'gbp':
856
- return '£';
857
- break;
858
- case 'eur':
859
- return '€';
860
- break;
861
- default:
862
- return '$';
863
- break;
864
- }
865
- }
866
-
867
-
868
-
869
- service.getAvailableCurrencies = function(DefaultCountryID) {
870
-
871
-
872
- var array = [];
873
-
874
- array.push({
875
- name: `USD (${service.currencySymbol("usd")})`,
876
- value: "usd",
877
- countryCode: { 'US': true },
878
- });
879
-
880
- array.push({
881
- name: `GBP (${service.currencySymbol("gbp")})`,
882
- value: "gbp",
883
- countryCode: { 'GB': true, 'UK': true },
1017
+ service.currencySymbol = function (currency) {
1018
+ //Ensure lowercase currency
1019
+ currency = String(currency).toLowerCase();
1020
+
1021
+ switch (String(currency).toLowerCase()) {
1022
+ case "gbp":
1023
+ return "£";
1024
+ break;
1025
+ case "eur":
1026
+ return "€";
1027
+ break;
1028
+ default:
1029
+ return "$";
1030
+ break;
1031
+ }
1032
+ };
1033
+
1034
+ service.getAvailableCurrencies = function (DefaultCountryID) {
1035
+ var array = [];
1036
+
1037
+ array.push({
1038
+ name: `USD (${service.currencySymbol("usd")})`,
1039
+ value: "usd",
1040
+ countryCode: { US: true },
1041
+ });
1042
+
1043
+ array.push({
1044
+ name: `GBP (${service.currencySymbol("gbp")})`,
1045
+ value: "gbp",
1046
+ countryCode: { GB: true, UK: true },
1047
+ });
1048
+
1049
+ array.push({
1050
+ name: `CAD (${service.currencySymbol("cad")})`,
1051
+ value: "cad",
1052
+ countryCode: { CA: true },
1053
+ });
1054
+
1055
+ array.push({
1056
+ name: `AUD (${service.currencySymbol("aud")})`,
1057
+ value: "aud",
1058
+ countryCode: { AU: true },
1059
+ });
1060
+
1061
+ array.push({
1062
+ name: `NZD (${service.currencySymbol("nzd")})`,
1063
+ value: "nzd",
1064
+ countryCode: { NZ: true },
1065
+ });
1066
+
1067
+ array.push({
1068
+ name: `SGD (${service.currencySymbol("sgd")})`,
1069
+ value: "sgd",
1070
+ countryCode: { SG: true },
1071
+ });
1072
+
1073
+ if (DefaultCountryID) {
1074
+ var findMatch = array.findIndex(function (currency) {
1075
+ return currency.countryCode[DefaultCountryID];
884
1076
  });
885
1077
 
886
- array.push({
887
- name: `CAD (${service.currencySymbol("cad")})`,
888
- value: "cad",
889
- countryCode: { 'CA': true },
890
- });
891
-
892
- array.push({
893
- name: `AUD (${service.currencySymbol("aud")})`,
894
- value: "aud",
895
- countryCode: { 'AU': true },
896
- });
897
-
898
-
899
- array.push({
900
- name: `NZD (${service.currencySymbol("nzd")})`,
901
- value: "nzd",
902
- countryCode: { 'NZ': true },
903
- });
904
-
905
- array.push({
906
- name: `SGD (${service.currencySymbol("sgd")})`,
907
- value: "sgd",
908
- countryCode: { 'SG': true },
909
- });
910
-
911
-
912
- if (DefaultCountryID) {
913
-
914
- var findMatch = array.findIndex(function(currency) {
915
- return currency.countryCode[DefaultCountryID];
916
- })
1078
+ const moveArrayItem = (array, fromIndex, toIndex) => {
1079
+ const arr = [...array];
1080
+ arr.splice(toIndex, 0, ...arr.splice(fromIndex, 1));
1081
+ return arr;
1082
+ };
917
1083
 
918
- const moveArrayItem = (array, fromIndex, toIndex) => {
919
- const arr = [...array];
920
- arr.splice(toIndex, 0, ...arr.splice(fromIndex, 1));
921
- return arr;
922
- }
923
-
924
- if (findMatch != -1) {
925
- array = moveArrayItem(array, findMatch, 0)
926
- }
1084
+ if (findMatch != -1) {
1085
+ array = moveArrayItem(array, findMatch, 0);
927
1086
  }
1087
+ }
928
1088
 
929
- return array;
930
- }
1089
+ return array;
1090
+ };
931
1091
 
932
1092
  ///////////////////////////////////////////////////////////////////////////////
933
1093
 
@@ -937,22 +1097,19 @@ service.getAvailableCurrencies = function(DefaultCountryID) {
937
1097
  * @param {Array} array The array of items to convert into a hash
938
1098
  * @param {String} key The key or path to the property on each item to use as the hashed key
939
1099
  * @return {Object} A key/value paired object
940
- * @example
1100
+ * @example
941
1101
  * //Returns { jimbo:{id:'jimbo', title:'Jim Jones'}, {id:'roger', title:'Roger Fellow'} }
942
1102
  * sdk.utils.hash([{id:'jimbo', title:'Jim Jones'}, {id:'roger', title:'Roger Fellow'}], 'id');
943
- *
1103
+ *
944
1104
  */
945
- service.hash = function(items, key) {
946
- items = !Array.isArray(items) ? [] : items;
947
- return items.reduce(function(memo, item) {
948
- const k = _get(item, key);
949
- memo[k] = item;
950
- return memo;
951
- }, {});
952
- }
953
-
954
-
955
-
1105
+ service.hash = function (items, key) {
1106
+ items = !Array.isArray(items) ? [] : items;
1107
+ return items.reduce(function (memo, item) {
1108
+ const k = _get(item, key);
1109
+ memo[k] = item;
1110
+ return memo;
1111
+ }, {});
1112
+ };
956
1113
 
957
1114
  //////////////////////////////////////////////////
958
1115
 
@@ -967,67 +1124,74 @@ service.hash = function(items, key) {
967
1124
  * @param {Boolean} exclude Whether to exclude null or undefined values
968
1125
  * @param {Object} options Pass through extra options for how to extract the values
969
1126
  * @return {Array} An array of all values retrieved from the array, unless provided arguments require otherwise
970
- * @example
1127
+ * @example
971
1128
  * //Returns [12, 45] as all the values
972
1129
  * sdk.utils.extractFromArray([{name:'Wendy', age:12}, {name:'Roger', age:45}], 'age');
973
- *
1130
+ *
974
1131
  * //Returns 32
975
1132
  * sdk.utils.extractFromArray([{name:'Wendy', age:12}, {name:'Roger', age:20}], 'age', {sum:true});
976
- *
1133
+ *
977
1134
  */
978
- service.extractFromArray = function(array, key, sum, flatten, unique, exclude, options) {
979
-
980
- options = options || {}
981
-
982
- if (sum) {
983
- options.sum = sum;
984
- }
985
-
986
- if (flatten) {
987
- options.flatten = true;
1135
+ service.extractFromArray = function (
1136
+ array,
1137
+ key,
1138
+ sum,
1139
+ flatten,
1140
+ unique,
1141
+ exclude,
1142
+ options,
1143
+ ) {
1144
+ options = options || {};
1145
+
1146
+ if (sum) {
1147
+ options.sum = sum;
1148
+ }
1149
+
1150
+ if (flatten) {
1151
+ options.flatten = true;
1152
+ }
1153
+
1154
+ if (unique) {
1155
+ options.unique = true;
1156
+ }
1157
+
1158
+ if (exclude) {
1159
+ options.excludeNull = true;
1160
+ }
1161
+
1162
+ /////////////////
1163
+
1164
+ //Filter the array options by a certain value and operator
1165
+ var extractedValues = array.reduce(function (set, entry) {
1166
+ //Get the value from the object
1167
+ var retrievedValue = _get(entry, key);
1168
+
1169
+ var isNull =
1170
+ !retrievedValue && retrievedValue !== false && retrievedValue !== 0;
1171
+ if (options.excludeNull && isNull) {
1172
+ return set;
988
1173
  }
989
1174
 
990
- if (unique) {
991
- options.unique = true;
992
- }
993
-
994
- if (exclude) {
995
- options.excludeNull = true;
996
- }
997
-
998
- /////////////////
999
-
1000
- //Filter the array options by a certain value and operator
1001
- var extractedValues = array.reduce(function(set, entry) {
1002
- //Get the value from the object
1003
- var retrievedValue = _get(entry, key);
1175
+ set.push(retrievedValue);
1176
+ return set;
1177
+ }, []);
1004
1178
 
1005
- var isNull = (!retrievedValue && (retrievedValue !== false && retrievedValue !== 0));
1006
- if (options.excludeNull && isNull) {
1007
- return set;
1008
- }
1009
-
1010
- set.push(retrievedValue);
1011
- return set;
1012
- }, [])
1179
+ if (options.flatten) {
1180
+ extractedValues = _.flatten(extractedValues);
1181
+ }
1013
1182
 
1014
- if (options.flatten) {
1015
- extractedValues = _.flatten(extractedValues);
1016
- }
1183
+ if (options.unique) {
1184
+ extractedValues = _.uniq(extractedValues);
1185
+ }
1017
1186
 
1018
- if (options.unique) {
1019
- extractedValues = _.uniq(extractedValues);
1020
- }
1021
-
1022
- if (options.sum) {
1023
- extractedValues = extractedValues.reduce(function(a, b) {
1024
- return a + b;
1025
- }, 0);
1026
- }
1027
-
1028
- return extractedValues;
1029
- }
1187
+ if (options.sum) {
1188
+ extractedValues = extractedValues.reduce(function (a, b) {
1189
+ return a + b;
1190
+ }, 0);
1191
+ }
1030
1192
 
1193
+ return extractedValues;
1194
+ };
1031
1195
 
1032
1196
  //////////////////////////////////////////////////////
1033
1197
 
@@ -1040,50 +1204,49 @@ service.extractFromArray = function(array, key, sum, flatten, unique, exclude, o
1040
1204
  * @param {String} value The value to compare against
1041
1205
  * @param {String} comparator The logical operator to use to compare the extracted value with the provided value ('>', '<', '>=', '<=', 'in', '==') Defaults to '==' (Is equal to)
1042
1206
  * @return {Array} Returns an array of matching values
1043
- * @example
1207
+ * @example
1044
1208
  * //Returns [{name:'Michael', age:45}] as that is only item in the array that matches the criteria
1045
1209
  * sdk.utils.matchInArray([{name:'Wendy', age:12}, {name:'Michael', age:45}], 'age', 45, '>=');
1046
- *
1210
+ *
1047
1211
  */
1048
- service.matchInArray = function(array, key, v, comparator) {
1049
-
1050
- //Filter the array options by a certain v and comparator
1051
- var matches = array.filter(function(entry) {
1052
- //Get the v from the object
1053
- var extracted = _get(entry, key);
1054
- var found;
1055
-
1056
- switch (comparator) {
1057
- case 'in':
1058
- found = extracted.includes(v);
1059
- break;
1060
- case '>=':
1061
- found = (extracted >= v);
1062
- break;
1063
- case '<=':
1064
- found = (extracted <= v);
1065
- break;
1066
- case '<':
1067
- found = (extracted < v);
1068
- break;
1069
- case '>':
1070
- found = (extracted > v);
1071
- break;
1072
- case '==':
1073
- default:
1074
- if (v === undefined) {
1075
- found = extracted;
1076
- } else {
1077
- found = (extracted == v);
1078
- }
1079
- break;
1212
+ service.matchInArray = function (array, key, v, comparator) {
1213
+ //Filter the array options by a certain v and comparator
1214
+ var matches = array.filter(function (entry) {
1215
+ //Get the v from the object
1216
+ var extracted = _get(entry, key);
1217
+ var found;
1218
+
1219
+ switch (comparator) {
1220
+ case "in":
1221
+ found = extracted.includes(v);
1222
+ break;
1223
+ case ">=":
1224
+ found = extracted >= v;
1225
+ break;
1226
+ case "<=":
1227
+ found = extracted <= v;
1228
+ break;
1229
+ case "<":
1230
+ found = extracted < v;
1231
+ break;
1232
+ case ">":
1233
+ found = extracted > v;
1234
+ break;
1235
+ case "==":
1236
+ default:
1237
+ if (v === undefined) {
1238
+ found = extracted;
1239
+ } else {
1240
+ found = extracted == v;
1080
1241
  }
1242
+ break;
1243
+ }
1081
1244
 
1082
- return found;
1083
- })
1245
+ return found;
1246
+ });
1084
1247
 
1085
- return matches;
1086
- }
1248
+ return matches;
1249
+ };
1087
1250
 
1088
1251
  ///////////////////////////////////////////////////////////////////////////////
1089
1252
 
@@ -1097,28 +1260,27 @@ service.matchInArray = function(array, key, v, comparator) {
1097
1260
  * @example
1098
1261
  * //Returns 'cat, dog, bird'
1099
1262
  * sdk.utils.comma(['cat', 'dog', 'bird']);
1100
- *
1263
+ *
1101
1264
  * //Returns 'cat, dog, bird'
1102
1265
  * sdk.utils.comma([{title:'cat'}, {title:'dog'}, {title:'bird'}], 'title');
1103
1266
  */
1104
- service.comma = function(array, path, limit) {
1105
-
1106
- if (limit) {
1107
- array = array.slice(0, limit);
1108
- }
1109
-
1110
- return _.chain(array)
1111
- .compact()
1112
- .map(function(item) {
1113
- if (path && path.length) {
1114
- return _get(item, path);
1115
- }
1116
-
1117
- return item;
1118
- })
1119
- .value()
1120
- .join(', ');
1121
- }
1267
+ service.comma = function (array, path, limit) {
1268
+ if (limit) {
1269
+ array = array.slice(0, limit);
1270
+ }
1271
+
1272
+ return _.chain(array)
1273
+ .compact()
1274
+ .map(function (item) {
1275
+ if (path && path.length) {
1276
+ return _get(item, path);
1277
+ }
1278
+
1279
+ return item;
1280
+ })
1281
+ .value()
1282
+ .join(", ");
1283
+ };
1122
1284
 
1123
1285
  ///////////////////////////////////////////////////////////////////////////////
1124
1286
 
@@ -1142,36 +1304,34 @@ service.comma = function(array, path, limit) {
1142
1304
  * //Returns true
1143
1305
  * typeof service.id({_id:'5cb3d8b3a2219970e6f86927'}, true) == 'object';
1144
1306
  */
1145
- service.id = function(source) {
1146
-
1147
- if (!source) {
1148
- return;
1149
- }
1150
-
1151
- /////////////////////////////////
1307
+ service.id = function (source) {
1308
+ if (!source) {
1309
+ return;
1310
+ }
1152
1311
 
1153
- var output;
1312
+ /////////////////////////////////
1154
1313
 
1155
- if (source._id) {
1156
- output = String(source._id);
1157
- } else {
1158
- output = String(source);
1159
- }
1314
+ var output;
1160
1315
 
1316
+ if (source._id) {
1317
+ output = String(source._id);
1318
+ } else {
1319
+ output = String(source);
1320
+ }
1161
1321
 
1162
- var isValid = service.isValidID(output);
1163
- if (!isValid) {
1164
- return;
1165
- }
1322
+ var isValid = service.isValidID(output);
1323
+ if (!isValid) {
1324
+ return;
1325
+ }
1166
1326
 
1167
- return output;
1168
- }
1327
+ return output;
1328
+ };
1169
1329
 
1170
1330
  ///////////////////////////////////////////////////////////////////////////////
1171
1331
 
1172
1332
  /**
1173
- * Cleans and maps an array of objects to an array of IDs
1174
- * @alias utils.ids
1333
+ * Cleans and maps an array of objects to an array of IDs
1334
+ * @alias utils.ids
1175
1335
  * @param {Array} array An array of objects or object ids
1176
1336
  * @param {Boolean} asObjectID Whether or not to map the ids as Mongo ObjectIds
1177
1337
  * @return {Array} An array of Ids
@@ -1181,96 +1341,87 @@ service.id = function(source) {
1181
1341
  * sdk.utils.ids([{_id:'5cb3d8b3a2219970e6f86927'}, {_id:'5cb3d8b3a2219970e6f86927'}, null, '5cb3d8b3a2219970e6f86927'])
1182
1342
  */
1183
1343
 
1184
- service.ids = function(array) {
1185
-
1186
- if (!array) {
1187
- return [];
1188
- }
1344
+ service.ids = function (array) {
1345
+ if (!array) {
1346
+ return [];
1347
+ }
1189
1348
 
1190
- /////////////////////////////////
1349
+ /////////////////////////////////
1191
1350
 
1192
- var ids = Object.keys(array.reduce(function(set, entry) {
1351
+ var ids = Object.keys(
1352
+ array.reduce(function (set, entry) {
1353
+ if (!entry) {
1354
+ return set;
1355
+ }
1193
1356
 
1194
- if (!entry) {
1195
- return set;
1196
- }
1357
+ var cleaned = service.id(entry);
1197
1358
 
1198
- var cleaned = service.id(entry)
1359
+ if (cleaned) {
1360
+ set[cleaned] = 1;
1361
+ }
1199
1362
 
1200
- if (cleaned) {
1201
- set[cleaned] = 1;
1202
- }
1363
+ return set;
1364
+ }, {}),
1365
+ );
1203
1366
 
1204
- return set;
1205
- }, {}))
1206
-
1207
- ///////////////////////////////
1208
-
1209
- return ids;
1210
- }
1367
+ ///////////////////////////////
1211
1368
 
1369
+ return ids;
1370
+ };
1212
1371
 
1213
1372
  ///////////////////////////////////////////////////////////////////////////////
1214
1373
 
1215
- service.isValidID = function(input) {
1216
- var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$")
1217
- return checkForHexRegExp.test(String(input));
1218
-
1219
- }
1374
+ service.isValidID = function (input) {
1375
+ var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
1376
+ return checkForHexRegExp.test(String(input));
1377
+ };
1220
1378
 
1221
1379
  ///////////////////////////////////////////////////////////////////////////////
1222
1380
 
1223
1381
  /**
1224
1382
  * Helper function for retrieving a human readable error message from server error response objects
1225
1383
  * @alias utils.errorMessage
1226
- * @param {Object} error The error object to translate
1384
+ * @param {Object} error The error object to translate
1227
1385
  * @return {String} The resulting human readable error message
1228
1386
  */
1229
- service.errorMessage = function(err) {
1230
-
1231
- if (!err) {
1232
- return;
1233
- }
1234
-
1235
-
1236
- if (Array.isArray(err)) {
1237
- err = err[0];
1238
- }
1239
-
1240
- ////////////////////////////////////
1387
+ service.errorMessage = function (err) {
1388
+ if (!err) {
1389
+ return;
1390
+ }
1241
1391
 
1392
+ if (Array.isArray(err)) {
1393
+ err = err[0];
1394
+ }
1242
1395
 
1243
- var candidates = [
1244
- 'response.data.message',
1245
- 'response.data',
1246
- 'message',
1247
- ]
1396
+ ////////////////////////////////////
1248
1397
 
1249
- var message;
1398
+ var candidates = ["response.data.message", "response.data", "message"];
1250
1399
 
1251
- candidates.forEach(function(path) {
1252
- if (message) {
1253
- return;
1254
- }
1400
+ var message;
1255
1401
 
1256
- var m = _get(err, path);
1257
- if (m) {
1258
- message = m;
1259
- }
1260
- })
1402
+ candidates.forEach(function (path) {
1403
+ if (message) {
1404
+ return;
1405
+ }
1261
1406
 
1262
- if (Array.isArray(message)) {
1263
- message = message[0];
1407
+ var m = _get(err, path);
1408
+ if (m) {
1409
+ message = m;
1264
1410
  }
1411
+ });
1265
1412
 
1266
- ////////////////////////////////////
1413
+ if (Array.isArray(message)) {
1414
+ message = message[0];
1415
+ }
1267
1416
 
1268
- message = message || JSON.stringify(err);
1417
+ ////////////////////////////////////
1269
1418
 
1270
- ////////////////////////////////////
1419
+ message = message || JSON.stringify(err);
1271
1420
 
1272
- return message;
1273
- }
1421
+ ////////////////////////////////////
1422
+
1423
+ return message;
1424
+ };
1274
1425
 
1275
1426
  ////////////////////////////////////
1276
1427
 
@@ -1278,17 +1429,25 @@ service.errorMessage = function(err) {
1278
1429
  * Generates a globally unique ID, helpful for adding unique keys for iterable loops
1279
1430
  * @alias utils.guid
1280
1431
  * @return {String} The new globally unique identifier
1281
- * @example
1432
+ * @example
1282
1433
  * //Returns 4323a78br-z16h-289j-zwl1-938lda334asd
1283
1434
  * sdk.utils.guid()
1284
1435
  */
1285
- service.guid = function() {
1286
- var u = (new Date()).getTime().toString(16) + Math.random().toString(16).substring(2) + "0".repeat(16);
1287
- return u.substr(0, 8) + '-' + u.substr(8, 4) + '-4000-8' + u.substr(12, 3) + '-' + u.substr(15, 12);
1288
- }
1289
-
1290
-
1291
-
1436
+ service.guid = function () {
1437
+ var u =
1438
+ new Date().getTime().toString(16) +
1439
+ Math.random().toString(16).substring(2) +
1440
+ "0".repeat(16);
1441
+ return (
1442
+ u.substr(0, 8) +
1443
+ "-" +
1444
+ u.substr(8, 4) +
1445
+ "-4000-8" +
1446
+ u.substr(12, 3) +
1447
+ "-" +
1448
+ u.substr(15, 12)
1449
+ );
1450
+ };
1292
1451
 
1293
1452
  ////////////////////////////////////
1294
1453
  ////////////////////////////////////
@@ -1300,111 +1459,105 @@ service.guid = function() {
1300
1459
  * @param {String} string The string to clean eg. (Awesome Event!)
1301
1460
  * @return {String} A cleaned and formatted string eg. (awesomeEvent)
1302
1461
  */
1303
- service.machineName = function(string) {
1304
-
1305
- if (!string || !string.length) {
1306
- return;
1307
- }
1462
+ service.machineName = function (string) {
1463
+ if (!string || !string.length) {
1464
+ return;
1465
+ }
1308
1466
 
1309
- var regexp = /[^a-zA-Z0-9-_]+/g;
1310
- var cleaned = String(string).replace(regexp, ' ').trim();
1311
- return _camelCase(cleaned);
1312
- }
1467
+ var regexp = /[^a-zA-Z0-9-_]+/g;
1468
+ var cleaned = String(string).replace(regexp, " ").trim();
1469
+ return _camelCase(cleaned);
1470
+ };
1313
1471
 
1314
1472
  /////////////////////////////////////////////
1315
1473
  /////////////////////////////////////////////
1316
1474
  /////////////////////////////////////////////
1317
1475
 
1318
-
1319
1476
  export default service;
1320
1477
 
1321
-
1322
1478
  /////////////////////////////////////////////
1323
1479
 
1324
1480
  //Export the event dispatcher
1325
1481
  export function EventDispatcher() {
1482
+ var listeners = {};
1326
1483
 
1327
- var listeners = {};
1484
+ /////////////////////////////////////////////
1328
1485
 
1329
- /////////////////////////////////////////////
1486
+ var dispatcher = {};
1330
1487
 
1331
- var dispatcher = {}
1332
-
1333
- /////////////////////////////////////////////
1334
-
1335
- //Remove all listeners
1336
- dispatcher.removeAllListeners = function() {
1337
- listeners = {};
1338
- }
1488
+ /////////////////////////////////////////////
1339
1489
 
1340
- /////////////////////////////////////////////
1490
+ //Remove all listeners
1491
+ dispatcher.removeAllListeners = function () {
1492
+ listeners = {};
1493
+ };
1341
1494
 
1342
- dispatcher.dispatch = function(event, details) {
1495
+ /////////////////////////////////////////////
1343
1496
 
1344
- if (listeners[event]) {
1345
- //For each listener
1346
- listeners[event].forEach(function(callback) {
1347
- return callback(details);
1348
- });
1349
- }
1497
+ dispatcher.dispatch = function (event, details) {
1498
+ if (listeners[event]) {
1499
+ //For each listener
1500
+ listeners[event].forEach(function (callback) {
1501
+ return callback(details);
1502
+ });
1350
1503
  }
1504
+ };
1351
1505
 
1352
- /////////////////////////////////////////////
1353
-
1354
- dispatcher.addEventListener = function(event, callback) {
1506
+ /////////////////////////////////////////////
1355
1507
 
1356
- if (!listeners[event]) {
1357
- listeners[event] = [];
1358
- }
1359
-
1360
- const type = typeof callback;
1361
- if (type !== 'function') {
1362
- throw new Error(`addEventListener() requires a function but ${type} was added`);
1363
- } else {
1364
- if (listeners[event].indexOf(callback) == -1) {
1365
- //Add to the listeners
1366
- listeners[event].push(callback)
1367
- } else {
1368
- //A
1369
- //lready listening
1370
- }
1371
- }
1508
+ dispatcher.addEventListener = function (event, callback) {
1509
+ if (!listeners[event]) {
1510
+ listeners[event] = [];
1372
1511
  }
1373
1512
 
1374
- /////////////////////////////////////////////
1375
-
1376
- dispatcher.removeEventListener = function(event, callback) {
1377
-
1378
- if (!listeners[event]) {
1379
- listeners[event] = [];
1380
- }
1513
+ const type = typeof callback;
1514
+ if (type !== "function") {
1515
+ throw new Error(
1516
+ `addEventListener() requires a function but ${type} was added`,
1517
+ );
1518
+ } else {
1519
+ if (listeners[event].indexOf(callback) == -1) {
1520
+ //Add to the listeners
1521
+ listeners[event].push(callback);
1522
+ } else {
1523
+ //A
1524
+ //lready listening
1525
+ }
1526
+ }
1527
+ };
1381
1528
 
1382
- //Get the index of the listener
1383
- var index = listeners[event].indexOf(callback);
1529
+ /////////////////////////////////////////////
1384
1530
 
1385
- if (index != -1) {
1386
- //Remove from the listeners
1387
- listeners[event].splice(index, 1);
1388
- }
1531
+ dispatcher.removeEventListener = function (event, callback) {
1532
+ if (!listeners[event]) {
1533
+ listeners[event] = [];
1389
1534
  }
1390
1535
 
1536
+ //Get the index of the listener
1537
+ var index = listeners[event].indexOf(callback);
1391
1538
 
1392
- /////////////////////////////////////////////
1539
+ if (index != -1) {
1540
+ //Remove from the listeners
1541
+ listeners[event].splice(index, 1);
1542
+ }
1543
+ };
1393
1544
 
1394
- //Wrap the event listener functionality
1395
- dispatcher.bootstrap = function(service) {
1396
- if (!service) {
1397
- // console.log('No service to bootstrap to')
1398
- return;
1399
- }
1545
+ /////////////////////////////////////////////
1400
1546
 
1401
- service.dispatch = dispatcher.dispatch;
1402
- service.addEventListener = dispatcher.addEventListener;
1403
- service.removeEventListener = dispatcher.removeEventListener;
1404
- service.removeAllListeners = dispatcher.removeAllListeners;
1547
+ //Wrap the event listener functionality
1548
+ dispatcher.bootstrap = function (service) {
1549
+ if (!service) {
1550
+ // console.log('No service to bootstrap to')
1551
+ return;
1405
1552
  }
1406
1553
 
1407
- /////////////////////////////////////////////
1554
+ service.dispatch = dispatcher.dispatch;
1555
+ service.addEventListener = dispatcher.addEventListener;
1556
+ service.removeEventListener = dispatcher.removeEventListener;
1557
+ service.removeAllListeners = dispatcher.removeAllListeners;
1558
+ };
1408
1559
 
1409
- return dispatcher;
1410
- }
1560
+ /////////////////////////////////////////////
1561
+
1562
+ return dispatcher;
1563
+ }