@zoho_apptics/apptics-js-sdk 2.0.0-beta.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +229 -174
  3. package/dist/apptics-pn-sw.js +3 -0
  4. package/dist/apptics-pn-sw.js.map +1 -0
  5. package/dist/apptics.esm.min.js +2 -2
  6. package/dist/apptics.esm.min.js.map +1 -1
  7. package/dist/apptics.min.js +2 -2
  8. package/dist/apptics.min.js.map +1 -1
  9. package/dist/chunks/batch-Axq9sTzR.min.js +3 -0
  10. package/dist/chunks/batch-Axq9sTzR.min.js.map +1 -0
  11. package/dist/chunks/lifecycle-Cvg78jN_.min.js +3 -0
  12. package/dist/chunks/lifecycle-Cvg78jN_.min.js.map +1 -0
  13. package/dist/chunks/send-DBpesydB.min.js +3 -0
  14. package/dist/chunks/send-DBpesydB.min.js.map +1 -0
  15. package/dist/chunks/transport-B21X39p4.min.js +3 -0
  16. package/dist/chunks/transport-B21X39p4.min.js.map +1 -0
  17. package/dist/cjs/core/attempts.js +1 -1
  18. package/dist/cjs/core/batch.js +4 -3
  19. package/dist/cjs/core/consent.d.ts +9 -6
  20. package/dist/cjs/core/consent.js +63 -10
  21. package/dist/cjs/core/console-call.d.ts +23 -0
  22. package/dist/cjs/core/console-call.js +63 -0
  23. package/dist/cjs/core/constants.d.ts +44 -0
  24. package/dist/cjs/core/constants.js +55 -1
  25. package/dist/cjs/core/db.js +31 -7
  26. package/dist/cjs/core/debug.d.ts +6 -4
  27. package/dist/cjs/core/debug.js +36 -12
  28. package/dist/cjs/core/env.js +1 -1
  29. package/dist/cjs/core/framework-id.d.ts +1 -1
  30. package/dist/cjs/core/framework-id.js +3 -3
  31. package/dist/cjs/core/guard.js +19 -4
  32. package/dist/cjs/core/hooks.d.ts +25 -1
  33. package/dist/cjs/core/hooks.js +11 -1
  34. package/dist/cjs/core/locks.js +1 -1
  35. package/dist/cjs/core/logger.js +1 -1
  36. package/dist/cjs/core/shield.d.ts +31 -0
  37. package/dist/cjs/core/shield.js +129 -0
  38. package/dist/cjs/core/state.d.ts +5 -1
  39. package/dist/cjs/core/state.js +3 -1
  40. package/dist/cjs/core/storage.d.ts +7 -0
  41. package/dist/cjs/core/storage.js +28 -6
  42. package/dist/cjs/core/stylesheet.js +1 -1
  43. package/dist/cjs/core/transport.d.ts +15 -4
  44. package/dist/cjs/core/transport.js +63 -13
  45. package/dist/cjs/core/utils.js +1 -1
  46. package/dist/cjs/core/validate.js +6 -5
  47. package/dist/cjs/device/appversion.js +1 -1
  48. package/dist/cjs/device/index.js +63 -15
  49. package/dist/cjs/engagement/api-rules.js +1 -1
  50. package/dist/cjs/engagement/auto-api.js +4 -3
  51. package/dist/cjs/engagement/auto-screen.js +10 -6
  52. package/dist/cjs/engagement/defined-events.d.ts +2 -3
  53. package/dist/cjs/engagement/defined-events.js +10 -16
  54. package/dist/cjs/engagement/send.js +1 -1
  55. package/dist/cjs/engagement/session.js +77 -37
  56. package/dist/cjs/engagement/track.js +9 -6
  57. package/dist/cjs/errors/send.js +1 -1
  58. package/dist/cjs/errors/track.js +3 -2
  59. package/dist/cjs/feedback/controls.d.ts +30 -4
  60. package/dist/cjs/feedback/controls.js +237 -51
  61. package/dist/cjs/feedback/i18n/index.d.ts +31 -0
  62. package/dist/cjs/feedback/i18n/index.js +187 -0
  63. package/dist/cjs/feedback/i18n/strings.d.ts +9 -0
  64. package/dist/cjs/feedback/i18n/strings.js +8 -0
  65. package/dist/cjs/feedback/index.js +1 -1
  66. package/dist/cjs/feedback/logs.js +5 -4
  67. package/dist/cjs/feedback/quartz.js +5 -2
  68. package/dist/cjs/feedback/send.d.ts +4 -1
  69. package/dist/cjs/feedback/send.js +56 -15
  70. package/dist/cjs/feedback/styles.js +2 -2
  71. package/dist/cjs/feedback/template.d.ts +4 -2
  72. package/dist/cjs/feedback/template.js +67 -46
  73. package/dist/cjs/feedback/ui.d.ts +40 -4
  74. package/dist/cjs/feedback/ui.js +208 -89
  75. package/dist/cjs/heatmap/send.js +1 -1
  76. package/dist/cjs/heatmap/track.js +13 -9
  77. package/dist/cjs/index.js +2 -2
  78. package/dist/cjs/lifecycle.js +119 -72
  79. package/dist/cjs/pushnotification/display.d.ts +65 -0
  80. package/dist/cjs/pushnotification/display.js +112 -0
  81. package/dist/cjs/pushnotification/index.d.ts +20 -0
  82. package/dist/cjs/pushnotification/index.js +96 -0
  83. package/dist/cjs/pushnotification/kept-opens.d.ts +23 -0
  84. package/dist/cjs/pushnotification/kept-opens.js +64 -0
  85. package/dist/cjs/pushnotification/notify.d.ts +45 -0
  86. package/dist/cjs/pushnotification/notify.js +476 -0
  87. package/dist/cjs/pushnotification/payload.d.ts +65 -0
  88. package/dist/cjs/pushnotification/payload.js +279 -0
  89. package/dist/cjs/pushnotification/session.d.ts +46 -0
  90. package/dist/cjs/pushnotification/session.js +413 -0
  91. package/dist/cjs/pushnotification/stats.d.ts +45 -0
  92. package/dist/cjs/pushnotification/stats.js +244 -0
  93. package/dist/cjs/pushnotification/wms.d.ts +30 -0
  94. package/dist/cjs/pushnotification/wms.js +374 -0
  95. package/dist/cjs/remoteconfig/country.js +1 -1
  96. package/dist/cjs/remoteconfig/custom.js +4 -3
  97. package/dist/cjs/remoteconfig/evaluate.js +1 -1
  98. package/dist/cjs/remoteconfig/fetch.js +27 -8
  99. package/dist/cjs/remoteconfig/index.d.ts +1 -6
  100. package/dist/cjs/remoteconfig/index.js +4 -28
  101. package/dist/cjs/remoteconfig/store.js +1 -1
  102. package/dist/cjs/remoteconfig/tz-countries.js +1 -1
  103. package/dist/cjs/remotelog/callsite.js +1 -1
  104. package/dist/cjs/remotelog/gate.js +1 -1
  105. package/dist/cjs/remotelog/logger.js +1 -1
  106. package/dist/cjs/remotelog/send.js +5 -4
  107. package/dist/cjs/remotelogger/index.js +1 -1
  108. package/dist/cjs/scheduler.js +11 -5
  109. package/dist/cjs/sw/apptics-pn-sw.d.ts +83 -0
  110. package/dist/cjs/sw/timers.d.ts +44 -0
  111. package/dist/cjs/types.d.ts +31 -15
  112. package/dist/cjs/user/index.d.ts +7 -0
  113. package/dist/cjs/user/index.js +25 -7
  114. package/dist/esm/core/attempts.js +1 -1
  115. package/dist/esm/core/batch.js +4 -3
  116. package/dist/esm/core/consent.d.ts +9 -6
  117. package/dist/esm/core/consent.js +67 -16
  118. package/dist/esm/core/console-call.d.ts +23 -0
  119. package/dist/esm/core/console-call.js +60 -0
  120. package/dist/esm/core/constants.d.ts +44 -0
  121. package/dist/esm/core/constants.js +52 -2
  122. package/dist/esm/core/db.js +31 -7
  123. package/dist/esm/core/debug.d.ts +6 -4
  124. package/dist/esm/core/debug.js +37 -13
  125. package/dist/esm/core/env.js +1 -1
  126. package/dist/esm/core/framework-id.d.ts +1 -1
  127. package/dist/esm/core/framework-id.js +3 -3
  128. package/dist/esm/core/guard.js +19 -4
  129. package/dist/esm/core/hooks.d.ts +25 -1
  130. package/dist/esm/core/hooks.js +11 -1
  131. package/dist/esm/core/locks.js +1 -1
  132. package/dist/esm/core/logger.js +1 -1
  133. package/dist/esm/core/shield.d.ts +31 -0
  134. package/dist/esm/core/shield.js +119 -0
  135. package/dist/esm/core/state.d.ts +5 -1
  136. package/dist/esm/core/state.js +3 -1
  137. package/dist/esm/core/storage.d.ts +7 -0
  138. package/dist/esm/core/storage.js +28 -8
  139. package/dist/esm/core/stylesheet.js +1 -1
  140. package/dist/esm/core/transport.d.ts +15 -4
  141. package/dist/esm/core/transport.js +64 -16
  142. package/dist/esm/core/utils.js +1 -1
  143. package/dist/esm/core/validate.js +6 -5
  144. package/dist/esm/device/appversion.js +1 -1
  145. package/dist/esm/device/index.js +67 -19
  146. package/dist/esm/engagement/api-rules.js +1 -1
  147. package/dist/esm/engagement/auto-api.js +4 -3
  148. package/dist/esm/engagement/auto-screen.js +10 -6
  149. package/dist/esm/engagement/defined-events.d.ts +2 -3
  150. package/dist/esm/engagement/defined-events.js +10 -16
  151. package/dist/esm/engagement/send.js +1 -1
  152. package/dist/esm/engagement/session.js +77 -37
  153. package/dist/esm/engagement/track.js +9 -6
  154. package/dist/esm/errors/send.js +1 -1
  155. package/dist/esm/errors/track.js +3 -2
  156. package/dist/esm/feedback/controls.d.ts +30 -4
  157. package/dist/esm/feedback/controls.js +234 -52
  158. package/dist/esm/feedback/i18n/index.d.ts +31 -0
  159. package/dist/esm/feedback/i18n/index.js +178 -0
  160. package/dist/esm/feedback/i18n/strings.d.ts +9 -0
  161. package/dist/esm/feedback/i18n/strings.js +4 -0
  162. package/dist/esm/feedback/index.js +1 -1
  163. package/dist/esm/feedback/logs.js +5 -4
  164. package/dist/esm/feedback/quartz.js +5 -2
  165. package/dist/esm/feedback/send.d.ts +4 -1
  166. package/dist/esm/feedback/send.js +56 -16
  167. package/dist/esm/feedback/styles.js +2 -2
  168. package/dist/esm/feedback/template.d.ts +4 -2
  169. package/dist/esm/feedback/template.js +67 -46
  170. package/dist/esm/feedback/ui.d.ts +40 -4
  171. package/dist/esm/feedback/ui.js +210 -91
  172. package/dist/esm/heatmap/send.js +1 -1
  173. package/dist/esm/heatmap/track.js +13 -9
  174. package/dist/esm/index.js +2 -2
  175. package/dist/esm/lifecycle.js +120 -73
  176. package/dist/esm/pushnotification/display.d.ts +65 -0
  177. package/dist/esm/pushnotification/display.js +95 -0
  178. package/dist/esm/pushnotification/index.d.ts +20 -0
  179. package/dist/esm/pushnotification/index.js +91 -0
  180. package/dist/esm/pushnotification/kept-opens.d.ts +23 -0
  181. package/dist/esm/pushnotification/kept-opens.js +62 -0
  182. package/dist/esm/pushnotification/notify.d.ts +45 -0
  183. package/dist/esm/pushnotification/notify.js +469 -0
  184. package/dist/esm/pushnotification/payload.d.ts +65 -0
  185. package/dist/esm/pushnotification/payload.js +272 -0
  186. package/dist/esm/pushnotification/session.d.ts +46 -0
  187. package/dist/esm/pushnotification/session.js +402 -0
  188. package/dist/esm/pushnotification/stats.d.ts +45 -0
  189. package/dist/esm/pushnotification/stats.js +238 -0
  190. package/dist/esm/pushnotification/wms.d.ts +30 -0
  191. package/dist/esm/pushnotification/wms.js +368 -0
  192. package/dist/esm/remoteconfig/country.js +1 -1
  193. package/dist/esm/remoteconfig/custom.js +4 -3
  194. package/dist/esm/remoteconfig/evaluate.js +1 -1
  195. package/dist/esm/remoteconfig/fetch.js +27 -8
  196. package/dist/esm/remoteconfig/index.d.ts +1 -6
  197. package/dist/esm/remoteconfig/index.js +4 -28
  198. package/dist/esm/remoteconfig/store.js +1 -1
  199. package/dist/esm/remoteconfig/tz-countries.js +1 -1
  200. package/dist/esm/remotelog/callsite.js +1 -1
  201. package/dist/esm/remotelog/gate.js +1 -1
  202. package/dist/esm/remotelog/logger.js +1 -1
  203. package/dist/esm/remotelog/send.js +5 -4
  204. package/dist/esm/remotelogger/index.js +1 -1
  205. package/dist/esm/scheduler.js +11 -5
  206. package/dist/esm/sw/apptics-pn-sw.d.ts +83 -0
  207. package/dist/esm/sw/timers.d.ts +44 -0
  208. package/dist/esm/types.d.ts +31 -15
  209. package/dist/esm/user/index.d.ts +7 -0
  210. package/dist/esm/user/index.js +26 -9
  211. package/dist/feedback.esm.min.js +2 -2
  212. package/dist/feedback.esm.min.js.map +1 -1
  213. package/dist/pushnotification.esm.min.js +3 -0
  214. package/dist/pushnotification.esm.min.js.map +1 -0
  215. package/dist/remoteconfig.esm.min.js +2 -2
  216. package/dist/remoteconfig.esm.min.js.map +1 -1
  217. package/dist/remotelogger.esm.min.js +2 -2
  218. package/dist/remotelogger.esm.min.js.map +1 -1
  219. package/package.json +15 -2
  220. package/dist/chunks/lifecycle-C6m1W7jo.min.js +0 -3
  221. package/dist/chunks/lifecycle-C6m1W7jo.min.js.map +0 -1
  222. package/dist/chunks/send-CgUO82ne.min.js +0 -3
  223. package/dist/chunks/send-CgUO82ne.min.js.map +0 -1
@@ -0,0 +1,244 @@
1
+ /*! @zoho_apptics/apptics-js-sdk v2.0.0 | (c) Zoho Corporation Private Limited | see LICENSE */
2
+ 'use strict';
3
+
4
+ var constants = require('../core/constants.js');
5
+ var logger = require('../core/logger.js');
6
+ var hooks = require('../core/hooks.js');
7
+ var utils = require('../core/utils.js');
8
+ var storage = require('../core/storage.js');
9
+ var locks = require('../core/locks.js');
10
+ var consent = require('../core/consent.js');
11
+ var transport = require('../core/transport.js');
12
+ var batch = require('../core/batch.js');
13
+ var env = require('../core/env.js');
14
+ var keptOpens = require('./kept-opens.js');
15
+
16
+ /**
17
+ * Push notification stats, sent to channel/add: received (4) when a message reaches the SDK,
18
+ * opened (5) on a click (with the button's action id), conversion (6) when the app tracks the
19
+ * message's conversion event after it was opened.
20
+ *
21
+ * They are kept in storage until the server takes them, under a lock the site's tabs share: two
22
+ * tabs often both receive a message, and each stat is counted once on this browser.
23
+ */
24
+ const LABEL = 'AppticsPushNotification stats'; // no i18n
25
+ const STORE_KEY = 'push_stats'; // no i18n
26
+ const LOCK = 'push-stats'; // no i18n
27
+ const STATUS = Object.freeze({ RECEIVED: 4, OPENED: 5, CONVERSION: 6 });
28
+ /** The most stats kept unsent; the oldest go first. */
29
+ const QUEUE_MAX = 500;
30
+ /** Stats per channel/add request. */
31
+ const BATCH = 100;
32
+ /** How long a recorded stat is remembered, so the same one isn't counted twice. */
33
+ const SEEN_MS = 30 * 24 * 60 * 60 * 1000;
34
+ /** actionid is a safe_string of at most 100 characters. */
35
+ const ACTION_MAX = 100;
36
+ /** The key a stat is counted once by: its run's send time too, when the server sent no number. */
37
+ function seenKey(stat, target) {
38
+ return stat.notificationnumber === undefined && target.run ? keyOf(stat) + '|run ' + target.run : keyOf(stat); // no i18n
39
+ }
40
+ function stored() {
41
+ var s = storage.user_defaults.item(STORE_KEY);
42
+ var ok = s && typeof s === 'object'; // no i18n
43
+ return {
44
+ queue: ok && Array.isArray(s.queue) ? s.queue : [],
45
+ seen: ok && s.seen && typeof s.seen === 'object' ? s.seen : {}, // no i18n
46
+ };
47
+ }
48
+ function keyOf(stat) {
49
+ return [stat.notificationid, stat.notificationnumber === undefined ? '' : stat.notificationnumber, stat.status, stat.actionid || ''].join('|'); // no i18n
50
+ }
51
+ /** Runs `change` on the stored stats under the tabs' shared lock, after reading the latest copy. */
52
+ function update(change) {
53
+ return locks.withLock(LOCK, function () {
54
+ return storage.reloadSettings([STORE_KEY]).then(function () {
55
+ var s = stored();
56
+ change(s);
57
+ return storage.user_defaults.save(STORE_KEY, s);
58
+ });
59
+ });
60
+ }
61
+ /** The stat to record, or null when it can't be one (no id, a number that isn't). */
62
+ function statFor(target, status, actionid, timestamp) {
63
+ var id = Number(target.id);
64
+ if (!target.id || !isFinite(id) || id <= 0 || Math.floor(id) !== id) {
65
+ return null;
66
+ }
67
+ var stat = { notificationid: id, timestamp: timestamp, status: status };
68
+ if (typeof target.number === 'number' && isFinite(target.number) && Math.floor(target.number) === target.number) { // no i18n
69
+ stat.notificationnumber = target.number;
70
+ }
71
+ if (status === STATUS.OPENED && typeof actionid === 'string' && actionid !== '') { // no i18n
72
+ stat.actionid = actionid.slice(0, ACTION_MAX);
73
+ }
74
+ return stat;
75
+ }
76
+ /**
77
+ * Records a stat for the message `target`: once on this browser, and not at all while tracking
78
+ * is off or the message has no appticsPnID. `timestamp` is when it happened (now by default).
79
+ */
80
+ function recordStat(target, status, actionid, timestamp) {
81
+ if (consent.opt_in_status() === constants.AP_TRACKING_STATUS.NO_TRACKING) {
82
+ return;
83
+ }
84
+ var stat = statFor(target, status, actionid, typeof timestamp === 'number' ? timestamp : utils.nowMs()); // no i18n
85
+ if (!stat) {
86
+ return;
87
+ }
88
+ var key = seenKey(stat, target);
89
+ update(function (s) {
90
+ var now = utils.nowMs();
91
+ Object.keys(s.seen).forEach(function (k) {
92
+ if (now - s.seen[k] > SEEN_MS) {
93
+ delete s.seen[k];
94
+ }
95
+ });
96
+ if (s.seen[key]) {
97
+ return;
98
+ }
99
+ s.seen[key] = now;
100
+ s.queue.push(stat);
101
+ if (s.queue.length > QUEUE_MAX) {
102
+ s.queue.splice(0, s.queue.length - QUEUE_MAX);
103
+ }
104
+ }).catch(function (err) {
105
+ logger.Console.log(LABEL + ': not recorded: ' + String(err)); // no i18n
106
+ });
107
+ }
108
+ /* ---- conversion: the message's event, tracked after it was opened ------------------------- */
109
+ const CONVERSIONS_KEY = 'push_conversions'; // no i18n
110
+ /** How long an opened message waits for its conversion event. */
111
+ const CONVERSION_MS = 7 * 24 * 60 * 60 * 1000;
112
+ function pending() {
113
+ var list = storage.user_defaults.item(CONVERSIONS_KEY);
114
+ return Array.isArray(list) ? list : [];
115
+ }
116
+ /** An opened message with a conversion event: it waits for that event for 7 days. */
117
+ function awaitConversion(target, event) {
118
+ if (!target.id || consent.opt_in_status() === constants.AP_TRACKING_STATUS.NO_TRACKING) {
119
+ return;
120
+ }
121
+ locks.withLock(LOCK, function () {
122
+ return storage.reloadSettings([CONVERSIONS_KEY]).then(function () {
123
+ var list = pending().filter(function (p) { return !(p.id === target.id && p.number === target.number && p.run === target.run); });
124
+ list.push({ id: target.id, number: target.number, run: target.run, name: event.name, group: event.group, until: utils.nowMs() + CONVERSION_MS });
125
+ return storage.user_defaults.save(CONVERSIONS_KEY, list);
126
+ });
127
+ }).catch(function (err) {
128
+ logger.Console.log(LABEL + ': conversion not kept: ' + String(err)); // no i18n
129
+ });
130
+ }
131
+ /** How often a tab with no conversion waiting of its own looks again for ones other tabs made. */
132
+ const CONVERSION_RECHECK_MS = 60 * 1000;
133
+ /**
134
+ * The tab's own copy of the waits is read at start-up, with every wait made before it: only waits
135
+ * other tabs make later need the minute's look.
136
+ */
137
+ var conversionsCheckedAt = utils.nowMs();
138
+ /** The app tracked an event: a message opened within 7 days that waits for it converts, once. */
139
+ function eventTracked(name, group) {
140
+ var now = utils.nowMs();
141
+ // most events come with nothing waiting: no lock and no storage read for those, only a look
142
+ // every minute for waits another tab made
143
+ if (pending().length === 0 && now - conversionsCheckedAt < CONVERSION_RECHECK_MS) {
144
+ return;
145
+ }
146
+ conversionsCheckedAt = now;
147
+ var matched = [];
148
+ locks.withLock(LOCK, function () {
149
+ return storage.reloadSettings([CONVERSIONS_KEY]).then(function () {
150
+ var before = pending();
151
+ var kept = before.filter(function (p) {
152
+ if (p.until <= now) {
153
+ return false;
154
+ }
155
+ if (p.name === name && p.group === group) {
156
+ matched.push(p);
157
+ return false;
158
+ }
159
+ return true;
160
+ });
161
+ return kept.length === before.length ? undefined : storage.user_defaults.save(CONVERSIONS_KEY, kept);
162
+ });
163
+ }).then(function () {
164
+ matched.forEach(function (p) { recordStat({ id: p.id, number: p.number, run: p.run }, STATUS.CONVERSION); });
165
+ }, function (err) {
166
+ logger.Console.log(LABEL + ': ' + String(err)); // no i18n
167
+ });
168
+ }
169
+ hooks.hooks.pushEventTracked = eventTracked;
170
+ /**
171
+ * The opens the service worker kept while no tab of the site was open: each becomes an opened
172
+ * stat with when it happened, and starts its conversion wait. Push start-up calls it.
173
+ */
174
+ function drainWorkerOpens() {
175
+ return keptOpens.takeOpens().then(function (list) {
176
+ list.forEach(function (open) {
177
+ if (!open || !open.notificationid) {
178
+ return;
179
+ }
180
+ var target = { id: String(open.notificationid), number: typeof open.notificationnumber === 'number' ? open.notificationnumber : null, run: typeof open.run === 'string' && open.run ? open.run : undefined }; // no i18n
181
+ recordStat(target, STATUS.OPENED, open.actionid || undefined, typeof open.timestamp === 'number' ? open.timestamp : undefined); // no i18n
182
+ if (open.conversion && open.conversion.name && open.conversion.group) {
183
+ awaitConversion(target, open.conversion);
184
+ }
185
+ });
186
+ }, function () { });
187
+ }
188
+ var sending = null;
189
+ /**
190
+ * Sends a batch of the stored stats, and removes it once the server takes it, or when it refuses
191
+ * it for good (a malformed batch would otherwise block every later one). Nothing goes while the
192
+ * SDK is disabled or tracking is off. `forget`: the page is closing, so it goes by keepalive.
193
+ */
194
+ function sendPushStats(forget) {
195
+ if (env.is_apptics_disabled() || !consent.shouldTrackOrSendData()) {
196
+ return Promise.resolve();
197
+ }
198
+ if (sending) {
199
+ return sending;
200
+ }
201
+ var blocked = transport.rejectIfOffline(LABEL) || transport.rejectIfNoDeviceIds(LABEL, 'pnstats'); // no i18n
202
+ if (blocked) {
203
+ return blocked.then(null, function () { });
204
+ }
205
+ var drop = function (batch) {
206
+ var sentKeys = {};
207
+ batch.forEach(function (stat) { sentKeys[keyOf(stat) + '|' + stat.timestamp] = true; }); // no i18n
208
+ var s = stored();
209
+ s.queue = s.queue.filter(function (stat) { return !sentKeys[keyOf(stat) + '|' + stat.timestamp]; }); // no i18n
210
+ return storage.user_defaults.save(STORE_KEY, s);
211
+ };
212
+ sending = locks.withLock(LOCK, function () {
213
+ return storage.reloadSettings([STORE_KEY]).then(function () {
214
+ var batch$1 = stored().queue.slice(0, BATCH);
215
+ if (batch$1.length === 0) {
216
+ return undefined;
217
+ }
218
+ var landed = batch.sendBatch('pnstats', LABEL, { pnstats: batch$1 }, forget).then(function () {
219
+ return drop(batch$1);
220
+ }, function (err) {
221
+ if (transport.isPermanentRefusal(err)) {
222
+ logger.warnAlways(LABEL + ': the server refused a batch for good, so it is dropped: ' + String(err)); // no i18n
223
+ return drop(batch$1);
224
+ }
225
+ logger.Console.log(LABEL + ': kept for the next send: ' + String(err)); // no i18n
226
+ return undefined;
227
+ });
228
+ return batch.awaitUnlessClosing(landed, forget, LABEL);
229
+ });
230
+ }).then(function () {
231
+ sending = null;
232
+ }, function (err) {
233
+ sending = null;
234
+ logger.Console.log(LABEL + ': ' + String(err)); // no i18n
235
+ });
236
+ return sending;
237
+ }
238
+ hooks.hooks.sendPushStats = function (forget) { return sendPushStats(forget); };
239
+
240
+ exports.STATUS = STATUS;
241
+ exports.awaitConversion = awaitConversion;
242
+ exports.drainWorkerOpens = drainWorkerOpens;
243
+ exports.recordStat = recordStat;
244
+ exports.sendPushStats = sendPushStats;
@@ -0,0 +1,30 @@
1
+ import type { PushSession } from './session.js';
2
+ type Message = Record<string, unknown>;
3
+ /** A message as the key-value object it carries, or null when it is not a JSON object. */
4
+ export declare function decodeMessage(msg: unknown): Message | null;
5
+ /**
6
+ * Adds a listener for each message's key-value object. The first one also gets the messages that
7
+ * arrived before it. Returns the function that removes it.
8
+ */
9
+ export declare function addMessageListener(fn: (data: Message) => void): () => void;
10
+ /**
11
+ * Whether `hostname` is a Zoho-owned application domain, where WMS reaches its servers as
12
+ * zmp-wms.<domain>. Anything else is a custom domain to WMS: its requests go to the site's own
13
+ * /wmssrv, which the site must route to WMS.
14
+ */
15
+ export declare function isZohoDomain(hostname: string): boolean;
16
+ /**
17
+ * The origin WMS's cross-origin flow loads its connector from (<origin>/wms/pconnect.sas): base_url's
18
+ * own host when that is a Zoho domain (apptics.zoho.in, preapptics.zoho.in, apptics.localzoho.com),
19
+ * else the US one. With the scheme: WmsLite puts it before the path as it is, so a bare host would
20
+ * load the frame from the page's own site.
21
+ */
22
+ export declare function crossOriginHost(serviceUrl: string): string;
23
+ /**
24
+ * Connects `session` to WMS, loading wmsliteapi.js the first time. A load that failed is tried
25
+ * again only when the app asked (`manual`), never on its own.
26
+ */
27
+ export declare function connect(session: PushSession, manual?: boolean): void;
28
+ /** Stops delivering this session's messages, closing the connection where WmsLite can. */
29
+ export declare function disconnect(): void;
30
+ export {};
@@ -0,0 +1,374 @@
1
+ /*! @zoho_apptics/apptics-js-sdk v2.0.0 | (c) Zoho Corporation Private Limited | see LICENSE */
2
+ 'use strict';
3
+
4
+ var state = require('../core/state.js');
5
+ var logger = require('../core/logger.js');
6
+ var utils = require('../core/utils.js');
7
+ var session = require('./session.js');
8
+ var notify = require('./notify.js');
9
+ var stats = require('./stats.js');
10
+ var payload = require('./payload.js');
11
+
12
+ /**
13
+ * The WMS connection a push session is delivered over: wmsliteapi.js, loaded from getsdkconfig's
14
+ * wms_js_url with its SRI hash, connected with WmsLite.registerAnnon, and called back on
15
+ * window.WmsliteImpl. Each message is key-value JSON for the app, handed to every listener.
16
+ *
17
+ * WmsLite and WmsliteImpl are the page's globals: a Zoho product page may use WMS itself. Its
18
+ * callbacks are kept, and every message that is not for this session's product goes to them. A
19
+ * WmsLite the page loaded is never disabled: only one this SDK loaded.
20
+ *
21
+ * wmsliteapi.js also declares a global `function push`, which its frame calls to deliver
22
+ * messages: a page with a top-level `let`, `const` or `class` named push stops it loading.
23
+ */
24
+ const LABEL = 'AppticsPushNotification'; // no i18n
25
+ /** The shortest wait between two registers after WMS refused the session's token. */
26
+ const AUTH_RETRY_MS = 60000;
27
+ const DEFAULT_DISPLAY_NAME = 'Apptics Web Device'; // no i18n
28
+ var active = null;
29
+ /** The session WmsLite was last registered with, so the same one is not registered twice. */
30
+ var connectedSessionId = ''; // no i18n
31
+ var scriptState = 'none'; // no i18n
32
+ /** Whether the WmsLite in use is the one this SDK loaded, the only one it may close. */
33
+ var loadedByUs = false;
34
+ /** Set while a page handler runs, so a page that wrapped ours cannot send a message round again. */
35
+ var inPrevious = false;
36
+ var warnedLoadFailure = false;
37
+ var lastAuthRetry = -Infinity;
38
+ var listeners = [];
39
+ /** The page's own WmsliteImpl callbacks, from before ours went on. */
40
+ var previous = {};
41
+ var installed = {};
42
+ function wmsLite() {
43
+ var api = window.WmsLite;
44
+ return api && typeof api.registerAnnon === 'function' ? api : undefined; // no i18n
45
+ }
46
+ /**
47
+ * Calls the page's own callback, on WmsliteImpl as WMS would. What it throws is the page's, kept
48
+ * from stopping ours; a page handler that calls back into ours is not sent round again.
49
+ */
50
+ function callPrevious(name, args) {
51
+ var fn = previous[name];
52
+ if (typeof fn !== 'function' || inPrevious) { // no i18n
53
+ return;
54
+ }
55
+ inPrevious = true;
56
+ try {
57
+ fn.apply(window.WmsliteImpl, args);
58
+ }
59
+ catch (err) {
60
+ logger.Console.warn(LABEL + ': the page\'s WmsliteImpl.' + name + ' threw', err); // no i18n
61
+ }
62
+ finally {
63
+ inPrevious = false;
64
+ }
65
+ }
66
+ /** \xNN and \uNNNN escapes, as WMS can send a message, back to their characters. */
67
+ function unescape(text) {
68
+ return text.replace(/\\x([0-9A-Fa-f]{2})|\\u([0-9A-Fa-f]{4})/g, function (_match, hex, uni) {
69
+ return String.fromCharCode(parseInt(hex || uni, 16));
70
+ });
71
+ }
72
+ /**
73
+ * Drops the backslash of an escape JSON doesn't have (WMS sends - as \-), keeping \\ and the
74
+ * escapes JSON allows (\" \\ \/ \b \f \n \r \t \uNNNN) as they are.
75
+ */
76
+ function dropInvalidEscapes(text) {
77
+ return text.replace(/\\(\\|["\/bfnrtu]|.)/g, function (match, next) {
78
+ return next === '\\' || '"/bfnrtu'.indexOf(next) !== -1 ? match : next; // no i18n
79
+ });
80
+ }
81
+ function isPlainObject(value) {
82
+ return !!value && typeof value === 'object' && !Array.isArray(value); // no i18n
83
+ }
84
+ /** A message as the key-value object it carries, or null when it is not a JSON object. */
85
+ function decodeMessage(msg) {
86
+ if (isPlainObject(msg)) {
87
+ return msg;
88
+ }
89
+ if (typeof msg !== 'string') { // no i18n
90
+ return null;
91
+ }
92
+ // valid JSON as it came; only text that is not gets its \x and \u escapes undone first, and
93
+ // then the backslash dropped from escapes JSON doesn't have (\- in a URL or text)
94
+ var parsed = parseJson(msg);
95
+ if (parsed === undefined) {
96
+ parsed = parseJson(unescape(msg));
97
+ }
98
+ if (parsed === undefined) {
99
+ parsed = parseJson(dropInvalidEscapes(unescape(msg)));
100
+ }
101
+ return isPlainObject(parsed) ? parsed : null;
102
+ }
103
+ function parseJson(text) {
104
+ try {
105
+ return JSON.parse(text);
106
+ }
107
+ catch (e) {
108
+ return undefined;
109
+ }
110
+ }
111
+ function deliver(data) {
112
+ if (listeners.length === 0) {
113
+ return;
114
+ }
115
+ listeners.slice().forEach(function (fn) {
116
+ try {
117
+ fn(data);
118
+ }
119
+ catch (err) {
120
+ logger.Console.warn(LABEL + ': a message listener threw', err); // no i18n
121
+ }
122
+ });
123
+ }
124
+ function handleMessage(mtype, msg, _meta, prd) {
125
+ if (active === null || String(prd) !== active.prdId) {
126
+ // exactly as WMS called it: the page's handler sees what it would without us
127
+ callPrevious('handleMessage', Array.prototype.slice.call(arguments)); // no i18n
128
+ return;
129
+ }
130
+ // WMS's control messages come with a negative mtype (-3 Re-Register, after each reconnect):
131
+ // not a push, not shown
132
+ if (Number(mtype) < 0) {
133
+ logger.Console.log(LABEL + ': a WMS control message (mtype ' + String(mtype) + ') was ignored'); // no i18n
134
+ return;
135
+ }
136
+ var decoded = decodeMessage(msg);
137
+ if (decoded === null) {
138
+ logger.Console.log(LABEL + ': a message that is not a JSON object was dropped'); // no i18n
139
+ return;
140
+ }
141
+ // the server wraps the console's key-value data as { type, module, action, timestamp, data }
142
+ var envelope = isEnvelope(decoded) ? decoded : null;
143
+ var data = envelope ? envelope.data : decoded;
144
+ // WMS sends a new session messages of its own ({ ac, uctime, uc }): not a push, not shown
145
+ if (!envelope && isWmsOwn(data)) {
146
+ logger.Console.log(LABEL + ': a WMS message that is not a push was ignored'); // no i18n
147
+ return;
148
+ }
149
+ // received: counted whether or not a notification can be shown
150
+ var view = payload.webNotificationFrom(data);
151
+ // a recurring push repeats its appticsPnID: the envelope's send time tells the runs apart
152
+ var run = envelope && (typeof envelope.timestamp === 'number' || typeof envelope.timestamp === 'string') ? String(envelope.timestamp) : undefined; // no i18n
153
+ stats.recordStat({ id: view.id, number: view.number, run: run }, stats.STATUS.RECEIVED);
154
+ deliver(data);
155
+ notify.showNotification(data, envelope ? envelope.timestamp : undefined);
156
+ }
157
+ /** The keys of the message WMS sends each new session on its own ({ ac, uctime, uc }). */
158
+ const WMS_OWN_KEYS = ['ac', 'uc', 'uctime']; // no i18n
159
+ /** WMS's own session message: every key one of its own. Custom key-value data is kept. */
160
+ function isWmsOwn(value) {
161
+ var keys = Object.keys(value);
162
+ return keys.length > 0 && keys.every(function (k) { return WMS_OWN_KEYS.indexOf(k) !== -1; });
163
+ }
164
+ function isEnvelope(value) {
165
+ return isPlainObject(value.data) && (value.type !== undefined || value.module !== undefined);
166
+ }
167
+ function handleAuthFailure() {
168
+ callPrevious('handleAuthFailure', Array.prototype.slice.call(arguments)); // no i18n
169
+ if (active === null || utils.nowMs() - lastAuthRetry < AUTH_RETRY_MS) {
170
+ return;
171
+ }
172
+ lastAuthRetry = utils.nowMs();
173
+ session.sessionRefused();
174
+ }
175
+ /** Puts our callbacks on window.WmsliteImpl, keeping whatever the page had there. */
176
+ function installCallbacks() {
177
+ var win = window;
178
+ // the page's object, or wmsliteapi.js's own `function WmsliteImpl(){}` with its defaults:
179
+ // decorated in place, so whatever else is on it stays
180
+ var current = win.WmsliteImpl;
181
+ var impl = current && (typeof current === 'object' || typeof current === 'function') ? current : {}; // no i18n
182
+ win.WmsliteImpl = impl;
183
+ var ours = {
184
+ serverup: function () { logger.Console.log(LABEL + ': WMS connected'); session.sessionConnected(); callPrevious('serverup', Array.prototype.slice.call(arguments)); }, // no i18n
185
+ serverdown: function () { logger.Console.log(LABEL + ': WMS disconnected'); callPrevious('serverdown', Array.prototype.slice.call(arguments)); }, // no i18n
186
+ connectionup: function () { callPrevious('connectionup', Array.prototype.slice.call(arguments)); }, // no i18n
187
+ handleMessage: handleMessage,
188
+ handleAuthFailure: handleAuthFailure,
189
+ };
190
+ Object.keys(ours).forEach(function (name) {
191
+ if (impl[name] === installed[name] && installed[name] !== undefined) {
192
+ return; // already ours
193
+ }
194
+ previous[name] = typeof impl[name] === 'function' ? impl[name] : undefined; // no i18n
195
+ impl[name] = ours[name];
196
+ installed[name] = ours[name];
197
+ });
198
+ }
199
+ /** The labels a Zoho-owned domain is named by, before its top-level domain: zoho.com, zohocloud.ca, localzoho.com. */
200
+ const ZOHO_LABELS = ['zoho', 'zohocloud', 'localzoho']; // no i18n
201
+ /** Zoho-owned domains named otherwise, matched with their subdomains. */
202
+ const ZOHO_DOMAINS = ['arattai.in', 'charmtracker.com']; // no i18n
203
+ /**
204
+ * Whether `hostname` is a Zoho-owned application domain, where WMS reaches its servers as
205
+ * zmp-wms.<domain>. Anything else is a custom domain to WMS: its requests go to the site's own
206
+ * /wmssrv, which the site must route to WMS.
207
+ */
208
+ function isZohoDomain(hostname) {
209
+ var host = String(hostname || '').toLowerCase().replace(/\.$/, ''); // no i18n
210
+ for (var d = 0; d < ZOHO_DOMAINS.length; d++) {
211
+ if (host === ZOHO_DOMAINS[d] || host.slice(-(ZOHO_DOMAINS[d].length + 1)) === '.' + ZOHO_DOMAINS[d]) { // no i18n
212
+ return true;
213
+ }
214
+ }
215
+ var labels = host.split('.'); // no i18n
216
+ for (var i = 0; i < labels.length - 1; i++) {
217
+ if (ZOHO_LABELS.indexOf(labels[i]) === -1) {
218
+ continue;
219
+ }
220
+ // what follows is the top-level domain: one label (zoho.eu), or com/co and one (zoho.com.au)
221
+ var rest = labels.slice(i + 1);
222
+ if (rest.length === 1 || (rest.length === 2 && (rest[0] === 'com' || rest[0] === 'co'))) { // no i18n
223
+ return true;
224
+ }
225
+ }
226
+ return false;
227
+ }
228
+ /** The Apptics host US apps' WMS connector loads from, and the one used when base_url names no Zoho host. */
229
+ const DEFAULT_CROSS_ORIGIN_HOST = 'https://apptics.zoho.com'; // no i18n
230
+ /**
231
+ * The origin WMS's cross-origin flow loads its connector from (<origin>/wms/pconnect.sas): base_url's
232
+ * own host when that is a Zoho domain (apptics.zoho.in, preapptics.zoho.in, apptics.localzoho.com),
233
+ * else the US one. With the scheme: WmsLite puts it before the path as it is, so a bare host would
234
+ * load the frame from the page's own site.
235
+ */
236
+ function crossOriginHost(serviceUrl) {
237
+ try {
238
+ var host = new URL(serviceUrl).hostname.toLowerCase();
239
+ return isZohoDomain(host) ? 'https://' + host : DEFAULT_CROSS_ORIGIN_HOST; // no i18n
240
+ }
241
+ catch (e) {
242
+ return DEFAULT_CROSS_ORIGIN_HOST;
243
+ }
244
+ }
245
+ function registerWithWms(session) {
246
+ var api = wmsLite();
247
+ if (!api || connectedSessionId === session.sessionID) {
248
+ return;
249
+ }
250
+ var wms = state._ZAP._wmsConfig;
251
+ try {
252
+ // a disable() of ours is undone only by the script's own start: undo it before connecting
253
+ if (loadedByUs && api.disablewms === true) {
254
+ api.disablewms = false;
255
+ }
256
+ if (wms && wms.wms_sri_values && typeof api.setClientSRIValues === 'function') { // no i18n
257
+ api.setClientSRIValues(wms.wms_sri_values);
258
+ }
259
+ // as the WMS docs and the reference page do; this wmsliteapi.js already starts with it on
260
+ if (typeof api.setNoDomainChange === 'function') { // no i18n
261
+ api.setNoDomainChange();
262
+ }
263
+ // a customer's own site. Only on a WmsLite this SDK loaded, since the setting is the whole page's
264
+ if (loadedByUs && !isZohoDomain(window.location.hostname)) {
265
+ if (typeof api.allowCrossOrigin === 'function') { // no i18n
266
+ // WMS's cross-origin flow, for anonymous sessions ($ ids): its connector loads from
267
+ // the Apptics host, so the site needs no /wmssrv of its own
268
+ api.allowCrossOrigin(crossOriginHost(String(state._ZAP._defaultoptions.serviceUrl || ''))); // no i18n
269
+ }
270
+ else if (typeof api.enableCustomDomain === 'function') { // no i18n
271
+ // an older WmsLite: everything goes through the site's own /wmssrv
272
+ api.enableCustomDomain();
273
+ }
274
+ }
275
+ api.registerAnnon(session.prdId, session.sessionID, session.displayName || DEFAULT_DISPLAY_NAME, true, session.token);
276
+ connectedSessionId = session.sessionID;
277
+ }
278
+ catch (err) {
279
+ logger.Console.warn(LABEL + ': WmsLite.registerAnnon failed', err); // no i18n
280
+ }
281
+ }
282
+ function loadScript() {
283
+ var wms = state._ZAP._wmsConfig;
284
+ if (!wms || scriptState === 'loading') { // no i18n
285
+ return;
286
+ }
287
+ scriptState = 'loading'; // no i18n
288
+ var script = document.createElement('script'); // no i18n
289
+ script.src = wms.wms_js_url;
290
+ if (wms.wms_sri) {
291
+ script.integrity = wms.wms_sri;
292
+ script.crossOrigin = 'anonymous'; // no i18n
293
+ }
294
+ script.onload = function () {
295
+ if (!wmsLite()) {
296
+ failed('wmsliteapi.js loaded without WmsLite'); // no i18n
297
+ return;
298
+ }
299
+ scriptState = 'loaded'; // no i18n
300
+ loadedByUs = true;
301
+ // wmsliteapi.js declares a global `function WmsliteImpl(){}` with empty defaults, which
302
+ // replaces the object our callbacks were on: they go on again, onto the script's own
303
+ installCallbacks();
304
+ if (active !== null) {
305
+ registerWithWms(active);
306
+ }
307
+ };
308
+ script.onerror = function () {
309
+ failed('wmsliteapi.js failed to load from ' + wms.wms_js_url + ' (network, integrity or Content-Security-Policy)'); // no i18n
310
+ };
311
+ document.head.appendChild(script);
312
+ }
313
+ function failed(reason) {
314
+ scriptState = 'failed'; // no i18n
315
+ if (!warnedLoadFailure) {
316
+ warnedLoadFailure = true;
317
+ logger.warnAlways(LABEL + ': ' + reason + '; push messages are off for this page'); // no i18n
318
+ }
319
+ }
320
+ /**
321
+ * Connects `session` to WMS, loading wmsliteapi.js the first time. A load that failed is tried
322
+ * again only when the app asked (`manual`), never on its own.
323
+ */
324
+ function connect(session, manual) {
325
+ active = session;
326
+ installCallbacks();
327
+ if (wmsLite()) {
328
+ scriptState = 'loaded'; // no i18n
329
+ registerWithWms(session);
330
+ return;
331
+ }
332
+ if (scriptState === 'failed' && !manual) { // no i18n
333
+ return;
334
+ }
335
+ loadScript();
336
+ }
337
+ /** Stops delivering this session's messages, closing the connection where WmsLite can. */
338
+ function disconnect() {
339
+ // the timers of what is on screen go with the session
340
+ notify.stopAllNotifications();
341
+ if (active === null) {
342
+ return;
343
+ }
344
+ active = null;
345
+ connectedSessionId = ''; // no i18n
346
+ var api = wmsLite();
347
+ // a WmsLite the page loaded is the page's connection: closing it would log the page out
348
+ if (!api || !loadedByUs) {
349
+ return;
350
+ }
351
+ // wmsliteapi.js has no logout or close: disable() sets disablewms and aborts the connection
352
+ if (typeof api.disable === 'function') { // no i18n
353
+ try {
354
+ api.disable();
355
+ }
356
+ catch (err) {
357
+ logger.Console.warn(LABEL + ': WmsLite.disable failed', err); // no i18n
358
+ }
359
+ }
360
+ }
361
+ session.setSessionListener(function (session, manual) {
362
+ if (session) {
363
+ connect(session, manual);
364
+ }
365
+ else {
366
+ disconnect();
367
+ }
368
+ });
369
+
370
+ exports.connect = connect;
371
+ exports.crossOriginHost = crossOriginHost;
372
+ exports.decodeMessage = decodeMessage;
373
+ exports.disconnect = disconnect;
374
+ exports.isZohoDomain = isZohoDomain;
@@ -1,4 +1,4 @@
1
- /*! @zoho_apptics/apptics-js-sdk v2.0.0-beta.2 | (c) Zoho Corporation Private Limited | see LICENSE */
1
+ /*! @zoho_apptics/apptics-js-sdk v2.0.0 | (c) Zoho Corporation Private Limited | see LICENSE */
2
2
  'use strict';
3
3
 
4
4
  var state = require('../core/state.js');
@@ -1,9 +1,10 @@
1
- /*! @zoho_apptics/apptics-js-sdk v2.0.0-beta.2 | (c) Zoho Corporation Private Limited | see LICENSE */
1
+ /*! @zoho_apptics/apptics-js-sdk v2.0.0 | (c) Zoho Corporation Private Limited | see LICENSE */
2
2
  'use strict';
3
3
 
4
4
  var storage = require('../core/storage.js');
5
5
  var logger = require('../core/logger.js');
6
6
  var store = require('./store.js');
7
+ var shield = require('../core/shield.js');
7
8
 
8
9
  /**
9
10
  * Custom condition values: a console condition on the custom criteria (`custom_sdk_value`) is
@@ -41,12 +42,12 @@ function setCustomConditionValue(conditionname, value) {
41
42
  else {
42
43
  mine[name] = values;
43
44
  }
44
- storage.storageReady().then(function (backend) {
45
+ shield.quietly('remote config', storage.storageReady().then(function (backend) {
45
46
  // only once storage has loaded: re-resolving before it would read an empty rule set and keep it
46
47
  if (backend) {
47
48
  store.reresolve();
48
49
  }
49
- });
50
+ }));
50
51
  }
51
52
  /** reset(): forgets the values set on this page. */
52
53
  function clearCustomConditionValues() {