@qikdev/sdk 0.1.170 → 0.1.181

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
-
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
+ }
326
374
 
327
- service.cleanValue = function(data, type, options) {
375
+ input = parseInt(input);
376
+ if (isNaN(input)) {
377
+ return 0;
378
+ }
328
379
 
329
- if (!options) {
330
- options = {};
331
- }
380
+ return input;
381
+ };
332
382
 
333
- ////////////////////////
334
-
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) {
766
+ service.mapFields = function (fields, options) {
767
+ if (!options) {
768
+ options = {};
769
+ }
583
770
 
584
- if (!options) {
585
- options = {};
586
- }
771
+ //////////////////////////////
587
772
 
588
- //////////////////////////////
773
+ var output = [];
774
+ var trail = [];
775
+ var titles = [];
776
+ var currentDepth = 1;
777
+ var depthLimit = options.depth;
778
+ var delimiter = options.arrayDelimeter || "[]";
589
779
 
590
- var output = [];
591
- var trail = [];
592
- var titles = [];
593
- var currentDepth = 1;
594
- var depthLimit = options.depth;
595
- var delimiter = options.arrayDelimeter || '[]';
780
+ //Loop through each field
781
+ fields.forEach(mapField);
596
782
 
783
+ //////////////////////////////
597
784
 
598
- //Loop through each field
599
- fields.forEach(mapField);
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;
600
792
 
601
- //////////////////////////////
602
-
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.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.title);
844
+
845
+ //Loop through each field
846
+ field.fields.forEach(mapField);
675
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,38 +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 || {}
870
+ service.mapParameters = function (parameters) {
871
+ parameters = parameters || {};
695
872
 
696
- var array = [];
873
+ var array = [];
697
874
 
698
- Object.entries(parameters)
699
- .forEach(function([key, value]) {
700
-
701
- if (value === undefined || value === null || value == false) {
702
- return;
703
- }
704
-
705
-
706
-
707
- if (Array.isArray(value)) {
708
- value.forEach(function(v) {
709
- array.push(`${key}=${encodeURIComponent(v)}`);
710
- })
711
- } else {
712
- array.push(encodeURIComponent(key) + '=' + encodeURIComponent(String(value)));
713
- }
714
-
715
- })
875
+ Object.entries(parameters).forEach(function ([key, value]) {
876
+ if (value === undefined || value === null || value == false) {
877
+ return;
878
+ }
716
879
 
717
- 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
+ });
718
888
 
719
- }
889
+ return array.join("&");
890
+ };
720
891
 
721
892
  ///////////////////////////////////////////////////////////////////////////////
722
893
 
@@ -726,210 +897,197 @@ service.mapParameters = function(parameters) {
726
897
  * @param {Integer} value The amount in cents
727
898
  * @param {String} currency The currency to format
728
899
  * @return {String} The formatted value
729
- * @example
730
- *
900
+ * @example
901
+ *
731
902
  * //Returns £10.00
732
903
  * sdk.utils.formatCurrency(1000, 'gbp');
733
- *
904
+ *
734
905
  * //Returns $10.00
735
906
  * sdk.utils.formatCurrency(1000, 'usd');
736
- *
907
+ *
737
908
  */
738
- service.formatCurrency = function(value, currency, decimalPoints) {
739
-
740
- if (!value || isNaN(value)) {
741
- value = 0;
742
- }
743
-
744
- decimalPoints = decimalPoints || 2;
745
-
746
- var currencyPrefix = service.currencySymbol(currency);
747
- return `${currencyPrefix}${parseFloat(Number(value) / 100).toFixed(decimalPoints)}`;
748
-
749
- }
909
+ service.formatCurrency = function (value, currency, decimalPoints) {
910
+ if (!value || isNaN(value)) {
911
+ value = 0;
912
+ }
750
913
 
914
+ decimalPoints = decimalPoints || 2;
751
915
 
916
+ var currencyPrefix = service.currencySymbol(currency);
917
+ return `${currencyPrefix}${parseFloat(Number(value) / 100).toFixed(decimalPoints)}`;
918
+ };
752
919
 
753
920
  /**
754
921
  * A function that will take an id and return the type key
755
922
  * @alias utils.getTypeFromID
756
923
  * @param {String} id The id of an object
757
924
  * @return {String} The key
758
- * @example
759
- *
925
+ * @example
926
+ *
760
927
  * // Returns 'user'
761
928
  * sdk.utils.getTypeFromID('52b523f775beea960013f6cd');
762
929
  *
763
930
  * // Returns 'role'
764
931
  * sdk.utils.getTypeFromID('62b59cb572fb4772e7b5fa93');
765
- *
932
+ *
766
933
  */
767
- service.getTypeFromID = function(id) {
768
-
769
- id = service.id(id);
770
-
771
- if (!id) {
772
- return;
773
- }
774
-
775
- const lookup = {
776
- "21": "organisation",
777
- "23": "comment",
778
- "24": "persona",
779
- "25": "audio",
780
- "26": "campaign",
781
- "28": "smartlist",
782
- "29": "cache",
783
- "40": "application",
784
- "41": "action",
785
- "42": "billinginvoice",
786
- "43": "componentsnapshot",
787
- "44": "diff",
788
- "45": "email",
789
- "46": "submission",
790
- "49": "import",
791
- "53": "socket",
792
- "54": "timetrigger",
793
- "61": "article",
794
- "63": "component",
795
- "65": "event",
796
- "66": "file",
797
- "67": "tag",
798
- "69": "image",
799
- "70": "profile",
800
- "72": "role",
801
- "73": "scope",
802
- "74": "transaction",
803
- "75": "user",
804
- "76": "video",
805
- "77": "workflowcard",
806
- "78": "variable",
807
- "3c": "patoken",
808
- "7b": "uatoken",
809
- "7d": "urtoken",
810
- "2d": "systemtask",
811
- "3d": "export",
812
- "5f": "systemflag",
813
- "2b": "batch",
814
- "3a": "log",
815
- "2e": "stat",
816
- "2f": "unsubscribe",
817
- "6b": "intent",
818
- "7c": "upload",
819
- "2c": "systemtrigger",
820
- "6e": "interface",
821
- "4e": "interfacesnapshot",
822
- "4f": "notification",
823
- "2a": "definition",
824
- "7e": "definitionsnapshot",
825
- "5e": "integration",
826
- "4c": "listener",
827
- "6d": "topic",
828
- "7a": "code",
829
- "4d": "paymentmethod",
830
- "6c": "sslcertificate"
831
- }
832
-
833
- var hexKey = id.slice(8, 10);
834
- return lookup[hexKey];
835
- }
934
+ service.getTypeFromID = function (id) {
935
+ id = service.id(id);
836
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
+ };
837
1002
 
838
1003
  /**
839
1004
  * A function that will take a currency string and return the symbol
840
1005
  * @alias utils.currencySymbol
841
1006
  * @param {String} currency The currency
842
1007
  * @return {String} The symbol
843
- * @example
844
- *
1008
+ * @example
1009
+ *
845
1010
  * //Returns £
846
1011
  * sdk.utils.currencySymbol('gbp');
847
- *
1012
+ *
848
1013
  * //Returns $
849
1014
  * sdk.utils.currencySymbol('usd');
850
- *
1015
+ *
851
1016
  */
852
- service.currencySymbol = function(currency) {
853
- //Ensure lowercase currency
854
- currency = String(currency).toLowerCase();
855
-
856
- switch (String(currency).toLowerCase()) {
857
- case 'gbp':
858
- return '£';
859
- break;
860
- case 'eur':
861
- return '€';
862
- break;
863
- default:
864
- return '$';
865
- break;
866
- }
867
- }
868
-
869
-
870
-
871
- service.getAvailableCurrencies = function(DefaultCountryID) {
872
-
873
-
874
- var array = [];
875
-
876
- array.push({
877
- name: `USD (${service.currencySymbol("usd")})`,
878
- value: "usd",
879
- countryCode: { 'US': true },
880
- });
881
-
882
- array.push({
883
- name: `GBP (${service.currencySymbol("gbp")})`,
884
- value: "gbp",
885
- 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];
886
1076
  });
887
1077
 
888
- array.push({
889
- name: `CAD (${service.currencySymbol("cad")})`,
890
- value: "cad",
891
- countryCode: { 'CA': true },
892
- });
893
-
894
- array.push({
895
- name: `AUD (${service.currencySymbol("aud")})`,
896
- value: "aud",
897
- countryCode: { 'AU': true },
898
- });
899
-
900
-
901
- array.push({
902
- name: `NZD (${service.currencySymbol("nzd")})`,
903
- value: "nzd",
904
- countryCode: { 'NZ': true },
905
- });
906
-
907
- array.push({
908
- name: `SGD (${service.currencySymbol("sgd")})`,
909
- value: "sgd",
910
- countryCode: { 'SG': true },
911
- });
912
-
913
-
914
- if (DefaultCountryID) {
915
-
916
- var findMatch = array.findIndex(function(currency) {
917
- return currency.countryCode[DefaultCountryID];
918
- })
1078
+ const moveArrayItem = (array, fromIndex, toIndex) => {
1079
+ const arr = [...array];
1080
+ arr.splice(toIndex, 0, ...arr.splice(fromIndex, 1));
1081
+ return arr;
1082
+ };
919
1083
 
920
- const moveArrayItem = (array, fromIndex, toIndex) => {
921
- const arr = [...array];
922
- arr.splice(toIndex, 0, ...arr.splice(fromIndex, 1));
923
- return arr;
924
- }
925
-
926
- if (findMatch != -1) {
927
- array = moveArrayItem(array, findMatch, 0)
928
- }
1084
+ if (findMatch != -1) {
1085
+ array = moveArrayItem(array, findMatch, 0);
929
1086
  }
1087
+ }
930
1088
 
931
- return array;
932
- }
1089
+ return array;
1090
+ };
933
1091
 
934
1092
  ///////////////////////////////////////////////////////////////////////////////
935
1093
 
@@ -939,22 +1097,19 @@ service.getAvailableCurrencies = function(DefaultCountryID) {
939
1097
  * @param {Array} array The array of items to convert into a hash
940
1098
  * @param {String} key The key or path to the property on each item to use as the hashed key
941
1099
  * @return {Object} A key/value paired object
942
- * @example
1100
+ * @example
943
1101
  * //Returns { jimbo:{id:'jimbo', title:'Jim Jones'}, {id:'roger', title:'Roger Fellow'} }
944
1102
  * sdk.utils.hash([{id:'jimbo', title:'Jim Jones'}, {id:'roger', title:'Roger Fellow'}], 'id');
945
- *
1103
+ *
946
1104
  */
947
- service.hash = function(items, key) {
948
- items = !Array.isArray(items) ? [] : items;
949
- return items.reduce(function(memo, item) {
950
- const k = _get(item, key);
951
- memo[k] = item;
952
- return memo;
953
- }, {});
954
- }
955
-
956
-
957
-
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
+ };
958
1113
 
959
1114
  //////////////////////////////////////////////////
960
1115
 
@@ -969,67 +1124,74 @@ service.hash = function(items, key) {
969
1124
  * @param {Boolean} exclude Whether to exclude null or undefined values
970
1125
  * @param {Object} options Pass through extra options for how to extract the values
971
1126
  * @return {Array} An array of all values retrieved from the array, unless provided arguments require otherwise
972
- * @example
1127
+ * @example
973
1128
  * //Returns [12, 45] as all the values
974
1129
  * sdk.utils.extractFromArray([{name:'Wendy', age:12}, {name:'Roger', age:45}], 'age');
975
- *
1130
+ *
976
1131
  * //Returns 32
977
1132
  * sdk.utils.extractFromArray([{name:'Wendy', age:12}, {name:'Roger', age:20}], 'age', {sum:true});
978
- *
1133
+ *
979
1134
  */
980
- service.extractFromArray = function(array, key, sum, flatten, unique, exclude, options) {
981
-
982
- options = options || {}
983
-
984
- if (sum) {
985
- options.sum = sum;
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;
986
1173
  }
987
1174
 
988
- if (flatten) {
989
- options.flatten = true;
990
- }
1175
+ set.push(retrievedValue);
1176
+ return set;
1177
+ }, []);
991
1178
 
992
- if (unique) {
993
- options.unique = true;
994
- }
1179
+ if (options.flatten) {
1180
+ extractedValues = _.flatten(extractedValues);
1181
+ }
995
1182
 
996
- if (exclude) {
997
- options.excludeNull = true;
998
- }
999
-
1000
- /////////////////
1183
+ if (options.unique) {
1184
+ extractedValues = _.uniq(extractedValues);
1185
+ }
1001
1186
 
1002
- //Filter the array options by a certain value and operator
1003
- var extractedValues = array.reduce(function(set, entry) {
1004
- //Get the value from the object
1005
- var retrievedValue = _get(entry, key);
1006
-
1007
- var isNull = (!retrievedValue && (retrievedValue !== false && retrievedValue !== 0));
1008
- if (options.excludeNull && isNull) {
1009
- return set;
1010
- }
1011
-
1012
- set.push(retrievedValue);
1013
- return set;
1014
- }, [])
1015
-
1016
- if (options.flatten) {
1017
- extractedValues = _.flatten(extractedValues);
1018
- }
1019
-
1020
- if (options.unique) {
1021
- extractedValues = _.uniq(extractedValues);
1022
- }
1023
-
1024
- if (options.sum) {
1025
- extractedValues = extractedValues.reduce(function(a, b) {
1026
- return a + b;
1027
- }, 0);
1028
- }
1029
-
1030
- return extractedValues;
1031
- }
1187
+ if (options.sum) {
1188
+ extractedValues = extractedValues.reduce(function (a, b) {
1189
+ return a + b;
1190
+ }, 0);
1191
+ }
1032
1192
 
1193
+ return extractedValues;
1194
+ };
1033
1195
 
1034
1196
  //////////////////////////////////////////////////////
1035
1197
 
@@ -1042,50 +1204,49 @@ service.extractFromArray = function(array, key, sum, flatten, unique, exclude, o
1042
1204
  * @param {String} value The value to compare against
1043
1205
  * @param {String} comparator The logical operator to use to compare the extracted value with the provided value ('>', '<', '>=', '<=', 'in', '==') Defaults to '==' (Is equal to)
1044
1206
  * @return {Array} Returns an array of matching values
1045
- * @example
1207
+ * @example
1046
1208
  * //Returns [{name:'Michael', age:45}] as that is only item in the array that matches the criteria
1047
1209
  * sdk.utils.matchInArray([{name:'Wendy', age:12}, {name:'Michael', age:45}], 'age', 45, '>=');
1048
- *
1210
+ *
1049
1211
  */
1050
- service.matchInArray = function(array, key, v, comparator) {
1051
-
1052
- //Filter the array options by a certain v and comparator
1053
- var matches = array.filter(function(entry) {
1054
- //Get the v from the object
1055
- var extracted = _get(entry, key);
1056
- var found;
1057
-
1058
- switch (comparator) {
1059
- case 'in':
1060
- found = extracted.includes(v);
1061
- break;
1062
- case '>=':
1063
- found = (extracted >= v);
1064
- break;
1065
- case '<=':
1066
- found = (extracted <= v);
1067
- break;
1068
- case '<':
1069
- found = (extracted < v);
1070
- break;
1071
- case '>':
1072
- found = (extracted > v);
1073
- break;
1074
- case '==':
1075
- default:
1076
- if (v === undefined) {
1077
- found = extracted;
1078
- } else {
1079
- found = (extracted == v);
1080
- }
1081
- 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;
1082
1241
  }
1242
+ break;
1243
+ }
1083
1244
 
1084
- return found;
1085
- })
1245
+ return found;
1246
+ });
1086
1247
 
1087
- return matches;
1088
- }
1248
+ return matches;
1249
+ };
1089
1250
 
1090
1251
  ///////////////////////////////////////////////////////////////////////////////
1091
1252
 
@@ -1099,28 +1260,27 @@ service.matchInArray = function(array, key, v, comparator) {
1099
1260
  * @example
1100
1261
  * //Returns 'cat, dog, bird'
1101
1262
  * sdk.utils.comma(['cat', 'dog', 'bird']);
1102
- *
1263
+ *
1103
1264
  * //Returns 'cat, dog, bird'
1104
1265
  * sdk.utils.comma([{title:'cat'}, {title:'dog'}, {title:'bird'}], 'title');
1105
1266
  */
1106
- service.comma = function(array, path, limit) {
1107
-
1108
- if (limit) {
1109
- array = array.slice(0, limit);
1110
- }
1111
-
1112
- return _.chain(array)
1113
- .compact()
1114
- .map(function(item) {
1115
- if (path && path.length) {
1116
- return _get(item, path);
1117
- }
1118
-
1119
- return item;
1120
- })
1121
- .value()
1122
- .join(', ');
1123
- }
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
+ };
1124
1284
 
1125
1285
  ///////////////////////////////////////////////////////////////////////////////
1126
1286
 
@@ -1144,36 +1304,34 @@ service.comma = function(array, path, limit) {
1144
1304
  * //Returns true
1145
1305
  * typeof service.id({_id:'5cb3d8b3a2219970e6f86927'}, true) == 'object';
1146
1306
  */
1147
- service.id = function(source) {
1148
-
1149
- if (!source) {
1150
- return;
1151
- }
1152
-
1153
- /////////////////////////////////
1307
+ service.id = function (source) {
1308
+ if (!source) {
1309
+ return;
1310
+ }
1154
1311
 
1155
- var output;
1312
+ /////////////////////////////////
1156
1313
 
1157
- if (source._id) {
1158
- output = String(source._id);
1159
- } else {
1160
- output = String(source);
1161
- }
1314
+ var output;
1162
1315
 
1316
+ if (source._id) {
1317
+ output = String(source._id);
1318
+ } else {
1319
+ output = String(source);
1320
+ }
1163
1321
 
1164
- var isValid = service.isValidID(output);
1165
- if (!isValid) {
1166
- return;
1167
- }
1322
+ var isValid = service.isValidID(output);
1323
+ if (!isValid) {
1324
+ return;
1325
+ }
1168
1326
 
1169
- return output;
1170
- }
1327
+ return output;
1328
+ };
1171
1329
 
1172
1330
  ///////////////////////////////////////////////////////////////////////////////
1173
1331
 
1174
1332
  /**
1175
- * Cleans and maps an array of objects to an array of IDs
1176
- * @alias utils.ids
1333
+ * Cleans and maps an array of objects to an array of IDs
1334
+ * @alias utils.ids
1177
1335
  * @param {Array} array An array of objects or object ids
1178
1336
  * @param {Boolean} asObjectID Whether or not to map the ids as Mongo ObjectIds
1179
1337
  * @return {Array} An array of Ids
@@ -1183,96 +1341,87 @@ service.id = function(source) {
1183
1341
  * sdk.utils.ids([{_id:'5cb3d8b3a2219970e6f86927'}, {_id:'5cb3d8b3a2219970e6f86927'}, null, '5cb3d8b3a2219970e6f86927'])
1184
1342
  */
1185
1343
 
1186
- service.ids = function(array) {
1187
-
1188
- if (!array) {
1189
- return [];
1190
- }
1344
+ service.ids = function (array) {
1345
+ if (!array) {
1346
+ return [];
1347
+ }
1191
1348
 
1192
- /////////////////////////////////
1349
+ /////////////////////////////////
1193
1350
 
1194
- 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
+ }
1195
1356
 
1196
- if (!entry) {
1197
- return set;
1198
- }
1357
+ var cleaned = service.id(entry);
1199
1358
 
1200
- var cleaned = service.id(entry)
1359
+ if (cleaned) {
1360
+ set[cleaned] = 1;
1361
+ }
1201
1362
 
1202
- if (cleaned) {
1203
- set[cleaned] = 1;
1204
- }
1363
+ return set;
1364
+ }, {}),
1365
+ );
1205
1366
 
1206
- return set;
1207
- }, {}))
1208
-
1209
- ///////////////////////////////
1210
-
1211
- return ids;
1212
- }
1367
+ ///////////////////////////////
1213
1368
 
1369
+ return ids;
1370
+ };
1214
1371
 
1215
1372
  ///////////////////////////////////////////////////////////////////////////////
1216
1373
 
1217
- service.isValidID = function(input) {
1218
- var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$")
1219
- return checkForHexRegExp.test(String(input));
1220
-
1221
- }
1374
+ service.isValidID = function (input) {
1375
+ var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
1376
+ return checkForHexRegExp.test(String(input));
1377
+ };
1222
1378
 
1223
1379
  ///////////////////////////////////////////////////////////////////////////////
1224
1380
 
1225
1381
  /**
1226
1382
  * Helper function for retrieving a human readable error message from server error response objects
1227
1383
  * @alias utils.errorMessage
1228
- * @param {Object} error The error object to translate
1384
+ * @param {Object} error The error object to translate
1229
1385
  * @return {String} The resulting human readable error message
1230
1386
  */
1231
- service.errorMessage = function(err) {
1232
-
1233
- if (!err) {
1234
- return;
1235
- }
1236
-
1237
-
1238
- if (Array.isArray(err)) {
1239
- err = err[0];
1240
- }
1241
-
1242
- ////////////////////////////////////
1387
+ service.errorMessage = function (err) {
1388
+ if (!err) {
1389
+ return;
1390
+ }
1243
1391
 
1392
+ if (Array.isArray(err)) {
1393
+ err = err[0];
1394
+ }
1244
1395
 
1245
- var candidates = [
1246
- 'response.data.message',
1247
- 'response.data',
1248
- 'message',
1249
- ]
1396
+ ////////////////////////////////////
1250
1397
 
1251
- var message;
1398
+ var candidates = ["response.data.message", "response.data", "message"];
1252
1399
 
1253
- candidates.forEach(function(path) {
1254
- if (message) {
1255
- return;
1256
- }
1400
+ var message;
1257
1401
 
1258
- var m = _get(err, path);
1259
- if (m) {
1260
- message = m;
1261
- }
1262
- })
1402
+ candidates.forEach(function (path) {
1403
+ if (message) {
1404
+ return;
1405
+ }
1263
1406
 
1264
- if (Array.isArray(message)) {
1265
- message = message[0];
1407
+ var m = _get(err, path);
1408
+ if (m) {
1409
+ message = m;
1266
1410
  }
1411
+ });
1267
1412
 
1268
- ////////////////////////////////////
1413
+ if (Array.isArray(message)) {
1414
+ message = message[0];
1415
+ }
1269
1416
 
1270
- message = message || JSON.stringify(err);
1417
+ ////////////////////////////////////
1271
1418
 
1272
- ////////////////////////////////////
1419
+ message = message || JSON.stringify(err);
1273
1420
 
1274
- return message;
1275
- }
1421
+ ////////////////////////////////////
1422
+
1423
+ return message;
1424
+ };
1276
1425
 
1277
1426
  ////////////////////////////////////
1278
1427
 
@@ -1280,17 +1429,25 @@ service.errorMessage = function(err) {
1280
1429
  * Generates a globally unique ID, helpful for adding unique keys for iterable loops
1281
1430
  * @alias utils.guid
1282
1431
  * @return {String} The new globally unique identifier
1283
- * @example
1432
+ * @example
1284
1433
  * //Returns 4323a78br-z16h-289j-zwl1-938lda334asd
1285
1434
  * sdk.utils.guid()
1286
1435
  */
1287
- service.guid = function() {
1288
- var u = (new Date()).getTime().toString(16) + Math.random().toString(16).substring(2) + "0".repeat(16);
1289
- return u.substr(0, 8) + '-' + u.substr(8, 4) + '-4000-8' + u.substr(12, 3) + '-' + u.substr(15, 12);
1290
- }
1291
-
1292
-
1293
-
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
+ };
1294
1451
 
1295
1452
  ////////////////////////////////////
1296
1453
  ////////////////////////////////////
@@ -1302,111 +1459,105 @@ service.guid = function() {
1302
1459
  * @param {String} string The string to clean eg. (Awesome Event!)
1303
1460
  * @return {String} A cleaned and formatted string eg. (awesomeEvent)
1304
1461
  */
1305
- service.machineName = function(string) {
1306
-
1307
- if (!string || !string.length) {
1308
- return;
1309
- }
1462
+ service.machineName = function (string) {
1463
+ if (!string || !string.length) {
1464
+ return;
1465
+ }
1310
1466
 
1311
- var regexp = /[^a-zA-Z0-9-_]+/g;
1312
- var cleaned = String(string).replace(regexp, ' ').trim();
1313
- return _camelCase(cleaned);
1314
- }
1467
+ var regexp = /[^a-zA-Z0-9-_]+/g;
1468
+ var cleaned = String(string).replace(regexp, " ").trim();
1469
+ return _camelCase(cleaned);
1470
+ };
1315
1471
 
1316
1472
  /////////////////////////////////////////////
1317
1473
  /////////////////////////////////////////////
1318
1474
  /////////////////////////////////////////////
1319
1475
 
1320
-
1321
1476
  export default service;
1322
1477
 
1323
-
1324
1478
  /////////////////////////////////////////////
1325
1479
 
1326
1480
  //Export the event dispatcher
1327
1481
  export function EventDispatcher() {
1482
+ var listeners = {};
1328
1483
 
1329
- var listeners = {};
1484
+ /////////////////////////////////////////////
1330
1485
 
1331
- /////////////////////////////////////////////
1486
+ var dispatcher = {};
1332
1487
 
1333
- var dispatcher = {}
1334
-
1335
- /////////////////////////////////////////////
1336
-
1337
- //Remove all listeners
1338
- dispatcher.removeAllListeners = function() {
1339
- listeners = {};
1340
- }
1488
+ /////////////////////////////////////////////
1341
1489
 
1342
- /////////////////////////////////////////////
1490
+ //Remove all listeners
1491
+ dispatcher.removeAllListeners = function () {
1492
+ listeners = {};
1493
+ };
1343
1494
 
1344
- dispatcher.dispatch = function(event, details) {
1495
+ /////////////////////////////////////////////
1345
1496
 
1346
- if (listeners[event]) {
1347
- //For each listener
1348
- listeners[event].forEach(function(callback) {
1349
- return callback(details);
1350
- });
1351
- }
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
+ });
1352
1503
  }
1504
+ };
1353
1505
 
1354
- /////////////////////////////////////////////
1355
-
1356
- dispatcher.addEventListener = function(event, callback) {
1506
+ /////////////////////////////////////////////
1357
1507
 
1358
- if (!listeners[event]) {
1359
- listeners[event] = [];
1360
- }
1361
-
1362
- const type = typeof callback;
1363
- if (type !== 'function') {
1364
- throw new Error(`addEventListener() requires a function but ${type} was added`);
1365
- } else {
1366
- if (listeners[event].indexOf(callback) == -1) {
1367
- //Add to the listeners
1368
- listeners[event].push(callback)
1369
- } else {
1370
- //A
1371
- //lready listening
1372
- }
1373
- }
1508
+ dispatcher.addEventListener = function (event, callback) {
1509
+ if (!listeners[event]) {
1510
+ listeners[event] = [];
1374
1511
  }
1375
1512
 
1376
- /////////////////////////////////////////////
1377
-
1378
- dispatcher.removeEventListener = function(event, callback) {
1379
-
1380
- if (!listeners[event]) {
1381
- listeners[event] = [];
1382
- }
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
+ };
1383
1528
 
1384
- //Get the index of the listener
1385
- var index = listeners[event].indexOf(callback);
1529
+ /////////////////////////////////////////////
1386
1530
 
1387
- if (index != -1) {
1388
- //Remove from the listeners
1389
- listeners[event].splice(index, 1);
1390
- }
1531
+ dispatcher.removeEventListener = function (event, callback) {
1532
+ if (!listeners[event]) {
1533
+ listeners[event] = [];
1391
1534
  }
1392
1535
 
1536
+ //Get the index of the listener
1537
+ var index = listeners[event].indexOf(callback);
1393
1538
 
1394
- /////////////////////////////////////////////
1539
+ if (index != -1) {
1540
+ //Remove from the listeners
1541
+ listeners[event].splice(index, 1);
1542
+ }
1543
+ };
1395
1544
 
1396
- //Wrap the event listener functionality
1397
- dispatcher.bootstrap = function(service) {
1398
- if (!service) {
1399
- // console.log('No service to bootstrap to')
1400
- return;
1401
- }
1545
+ /////////////////////////////////////////////
1402
1546
 
1403
- service.dispatch = dispatcher.dispatch;
1404
- service.addEventListener = dispatcher.addEventListener;
1405
- service.removeEventListener = dispatcher.removeEventListener;
1406
- 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;
1407
1552
  }
1408
1553
 
1409
- /////////////////////////////////////////////
1554
+ service.dispatch = dispatcher.dispatch;
1555
+ service.addEventListener = dispatcher.addEventListener;
1556
+ service.removeEventListener = dispatcher.removeEventListener;
1557
+ service.removeAllListeners = dispatcher.removeAllListeners;
1558
+ };
1410
1559
 
1411
- return dispatcher;
1412
- }
1560
+ /////////////////////////////////////////////
1561
+
1562
+ return dispatcher;
1563
+ }