ialert-web 0.0.0-stage → 0.1.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.
- package/LICENSE +202 -0
- package/NOTICE +7 -0
- package/README.md +52 -2
- package/dist/api.d.ts +34 -0
- package/dist/api.js +65 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +13 -0
- package/dist/gateway.d.ts +47 -0
- package/dist/gateway.js +156 -0
- package/dist/ialert.d.ts +76 -0
- package/dist/ialert.js +301 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/storage.d.ts +19 -0
- package/dist/storage.js +60 -0
- package/dist/types.d.ts +57 -0
- package/dist/types.js +1 -0
- package/package.json +46 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,53 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ialert-web
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
iAlert Web SDK. It registers the browser as a `web` device of your app and receives notifications while the page is open, over iAlert's own channel: a WebSocket to the iAlert Gateway, plus the device Inbox for anything sent while the page was closed. Each notification reaches your listeners once, across both channels and page loads.
|
|
4
|
+
|
|
5
|
+
Browser Web Push (VAPID, notifications while the site is closed) is not available yet; it will be added to this SDK without changing the API below.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install ialert-web
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { IAlert } from "ialert-web";
|
|
17
|
+
|
|
18
|
+
const ialert = new IAlert({ publicKey: "ia_pk_live_…" });
|
|
19
|
+
|
|
20
|
+
ialert.onMessage((message) => {
|
|
21
|
+
showToast(message.title, message.body, message.data);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
await ialert.register({ externalUserId: "user-42", tags: { plan: "gold" } });
|
|
25
|
+
|
|
26
|
+
// later
|
|
27
|
+
await ialert.setTags({ plan: "silver", trial: null }); // merged; null removes
|
|
28
|
+
await ialert.ack([message.id], "clicked");
|
|
29
|
+
await ialert.unsubscribe();
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
- Use the app's **public** key (`ia_pk_…`); the constructor refuses secret keys.
|
|
33
|
+
- `register()` is safe on every page load: a stable per-browser installation id maps to the same device.
|
|
34
|
+
- Messages are acknowledged as `delivered` automatically (`autoAckDelivered: false` to turn off). Report `read` / `clicked` yourself.
|
|
35
|
+
- Options: `apiUrl`, `gatewayUrl`, `storage` (defaults to `localStorage`, memory when blocked), `fetch`, `WebSocket`, `autoConnect`.
|
|
36
|
+
- `onConnectionStateChange(state)` reports `connecting` / `ready` / `closed`.
|
|
37
|
+
|
|
38
|
+
## Development
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
npm install
|
|
42
|
+
npm test # node --test, no browser needed
|
|
43
|
+
npm run typecheck
|
|
44
|
+
npm run build # dist/
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
API reference: `docs/api-v1.md` in the iAlert server repository.
|
|
48
|
+
|
|
49
|
+
## License
|
|
50
|
+
|
|
51
|
+
Copyright 2026 iAlert.ir
|
|
52
|
+
|
|
53
|
+
Licensed under the [Apache License, Version 2.0](LICENSE). See [NOTICE](NOTICE).
|
package/dist/api.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { AckEvent, Device } from "./types.ts";
|
|
2
|
+
type Fetch = typeof globalThis.fetch;
|
|
3
|
+
export interface InboxEntry {
|
|
4
|
+
id: string;
|
|
5
|
+
content: {
|
|
6
|
+
title: string | null;
|
|
7
|
+
body: string | null;
|
|
8
|
+
image: string | null;
|
|
9
|
+
data: Record<string, unknown> | unknown[] | null;
|
|
10
|
+
};
|
|
11
|
+
collapse_id: string | null;
|
|
12
|
+
delivered_at: string | null;
|
|
13
|
+
read_at: string | null;
|
|
14
|
+
clicked_at: string | null;
|
|
15
|
+
created_at: string;
|
|
16
|
+
}
|
|
17
|
+
/** Thin REST client for the public-key endpoints of API v1. */
|
|
18
|
+
export declare class ApiClient {
|
|
19
|
+
private readonly baseUrl;
|
|
20
|
+
private readonly publicKey;
|
|
21
|
+
private readonly fetchFn;
|
|
22
|
+
constructor(baseUrl: string, publicKey: string, fetchFn: Fetch);
|
|
23
|
+
register(body: Record<string, unknown>): Promise<{
|
|
24
|
+
data: Device;
|
|
25
|
+
device_token: string;
|
|
26
|
+
}>;
|
|
27
|
+
update(deviceId: string, deviceToken: string, body: Record<string, unknown>): Promise<Device>;
|
|
28
|
+
unsubscribe(deviceId: string, deviceToken: string): Promise<Device>;
|
|
29
|
+
/** Every Inbox page (newest first), following `links.next`, up to `maxPages`. */
|
|
30
|
+
inbox(deviceId: string, deviceToken: string, unreadOnly: boolean, maxPages?: number): Promise<InboxEntry[]>;
|
|
31
|
+
ack(deviceId: string, deviceToken: string, ids: string[], event: AckEvent): Promise<number>;
|
|
32
|
+
private request;
|
|
33
|
+
}
|
|
34
|
+
export {};
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { IAlertError } from "./errors.js";
|
|
2
|
+
/** Thin REST client for the public-key endpoints of API v1. */
|
|
3
|
+
export class ApiClient {
|
|
4
|
+
baseUrl;
|
|
5
|
+
publicKey;
|
|
6
|
+
fetchFn;
|
|
7
|
+
constructor(baseUrl, publicKey, fetchFn) {
|
|
8
|
+
this.baseUrl = baseUrl.replace(/\/+$/, "");
|
|
9
|
+
this.publicKey = publicKey;
|
|
10
|
+
this.fetchFn = fetchFn;
|
|
11
|
+
}
|
|
12
|
+
register(body) {
|
|
13
|
+
return this.request("POST", "/devices", body);
|
|
14
|
+
}
|
|
15
|
+
async update(deviceId, deviceToken, body) {
|
|
16
|
+
return (await this.request("PATCH", `/devices/${encodeURIComponent(deviceId)}`, body, deviceToken)).data;
|
|
17
|
+
}
|
|
18
|
+
async unsubscribe(deviceId, deviceToken) {
|
|
19
|
+
return (await this.request("POST", `/devices/${encodeURIComponent(deviceId)}/unsubscribe`, undefined, deviceToken)).data;
|
|
20
|
+
}
|
|
21
|
+
/** Every Inbox page (newest first), following `links.next`, up to `maxPages`. */
|
|
22
|
+
async inbox(deviceId, deviceToken, unreadOnly, maxPages = 5) {
|
|
23
|
+
const entries = [];
|
|
24
|
+
let url = `${this.baseUrl}/devices/${encodeURIComponent(deviceId)}/inbox?per_page=100${unreadOnly ? "&unread=1" : ""}`;
|
|
25
|
+
for (let page = 0; url !== null && page < maxPages; page++) {
|
|
26
|
+
const result = await this.request("GET", url, undefined, deviceToken);
|
|
27
|
+
entries.push(...result.data);
|
|
28
|
+
url = result.links?.next ?? null;
|
|
29
|
+
}
|
|
30
|
+
return entries;
|
|
31
|
+
}
|
|
32
|
+
async ack(deviceId, deviceToken, ids, event) {
|
|
33
|
+
let acknowledged = 0;
|
|
34
|
+
for (let start = 0; start < ids.length; start += 100) {
|
|
35
|
+
const result = await this.request("POST", `/devices/${encodeURIComponent(deviceId)}/inbox/ack`, { ids: ids.slice(start, start + 100), event }, deviceToken);
|
|
36
|
+
acknowledged += result.acknowledged;
|
|
37
|
+
}
|
|
38
|
+
return acknowledged;
|
|
39
|
+
}
|
|
40
|
+
async request(method, pathOrUrl, body, deviceToken) {
|
|
41
|
+
const headers = {
|
|
42
|
+
Accept: "application/json",
|
|
43
|
+
Authorization: `Bearer ${this.publicKey}`,
|
|
44
|
+
};
|
|
45
|
+
if (body !== undefined) {
|
|
46
|
+
headers["Content-Type"] = "application/json";
|
|
47
|
+
}
|
|
48
|
+
if (deviceToken !== undefined) {
|
|
49
|
+
headers["X-Device-Token"] = deviceToken;
|
|
50
|
+
}
|
|
51
|
+
const url = pathOrUrl.startsWith("http") ? pathOrUrl : this.baseUrl + pathOrUrl;
|
|
52
|
+
let response;
|
|
53
|
+
try {
|
|
54
|
+
response = await this.fetchFn(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
throw new IAlertError(0, "network_error", error instanceof Error ? error.message : "Network error");
|
|
58
|
+
}
|
|
59
|
+
const payload = (await response.json().catch(() => null));
|
|
60
|
+
if (!response.ok) {
|
|
61
|
+
throw new IAlertError(response.status, typeof payload?.code === "string" ? payload.code : "server_error", typeof payload?.message === "string" ? payload.message : `HTTP ${response.status}`, payload?.errors);
|
|
62
|
+
}
|
|
63
|
+
return payload;
|
|
64
|
+
}
|
|
65
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Error returned by the iAlert API: `{ message, code, errors? }`. */
|
|
2
|
+
export declare class IAlertError extends Error {
|
|
3
|
+
readonly status: number;
|
|
4
|
+
readonly code: string;
|
|
5
|
+
readonly errors: Record<string, string[]> | undefined;
|
|
6
|
+
constructor(status: number, code: string, message: string, errors?: Record<string, string[]>);
|
|
7
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Error returned by the iAlert API: `{ message, code, errors? }`. */
|
|
2
|
+
export class IAlertError extends Error {
|
|
3
|
+
status;
|
|
4
|
+
code;
|
|
5
|
+
errors;
|
|
6
|
+
constructor(status, code, message, errors) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = "IAlertError";
|
|
9
|
+
this.status = status;
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.errors = errors;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { AckEvent, ConnectionState } from "./types.ts";
|
|
2
|
+
/** Constructor shape of the browser WebSocket (injectable for tests and other runtimes). */
|
|
3
|
+
export type WebSocketFactory = new (url: string) => WebSocket;
|
|
4
|
+
export interface GatewayHandlers {
|
|
5
|
+
onReady(): void;
|
|
6
|
+
onMessage(message: Record<string, unknown>): void;
|
|
7
|
+
/** The token was rejected: reconnecting would not help. */
|
|
8
|
+
onUnauthorized(): void;
|
|
9
|
+
onStateChange(state: ConnectionState): void;
|
|
10
|
+
}
|
|
11
|
+
export interface GatewayOptions {
|
|
12
|
+
url: string;
|
|
13
|
+
deviceToken: string;
|
|
14
|
+
WebSocket: WebSocketFactory;
|
|
15
|
+
handlers: GatewayHandlers;
|
|
16
|
+
/** Client ping interval; the Gateway drops a socket after about 75 s of silence. */
|
|
17
|
+
pingIntervalMs?: number;
|
|
18
|
+
minReconnectMs?: number;
|
|
19
|
+
maxReconnectMs?: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* One WebSocket to the iAlert Gateway: authenticates with the device token,
|
|
23
|
+
* answers pings, sends acks and reconnects with jittered exponential backoff.
|
|
24
|
+
*/
|
|
25
|
+
export declare class GatewayConnection {
|
|
26
|
+
private readonly options;
|
|
27
|
+
private socket;
|
|
28
|
+
private stopped;
|
|
29
|
+
private attempt;
|
|
30
|
+
private reconnectTimer;
|
|
31
|
+
private pingTimer;
|
|
32
|
+
private ready;
|
|
33
|
+
private readonly pendingAcks;
|
|
34
|
+
constructor(options: GatewayOptions);
|
|
35
|
+
get isReady(): boolean;
|
|
36
|
+
start(): void;
|
|
37
|
+
stop(): void;
|
|
38
|
+
/** Sends an ack now, or once the socket is ready again. */
|
|
39
|
+
ack(ids: string[], event: AckEvent): void;
|
|
40
|
+
private open;
|
|
41
|
+
private handleFrame;
|
|
42
|
+
private send;
|
|
43
|
+
private flushAcks;
|
|
44
|
+
private startPinging;
|
|
45
|
+
private scheduleReconnect;
|
|
46
|
+
private clearTimers;
|
|
47
|
+
}
|
package/dist/gateway.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One WebSocket to the iAlert Gateway: authenticates with the device token,
|
|
3
|
+
* answers pings, sends acks and reconnects with jittered exponential backoff.
|
|
4
|
+
*/
|
|
5
|
+
export class GatewayConnection {
|
|
6
|
+
options;
|
|
7
|
+
socket = null;
|
|
8
|
+
stopped = true;
|
|
9
|
+
attempt = 0;
|
|
10
|
+
reconnectTimer = null;
|
|
11
|
+
pingTimer = null;
|
|
12
|
+
ready = false;
|
|
13
|
+
pendingAcks = [];
|
|
14
|
+
constructor(options) {
|
|
15
|
+
this.options = { pingIntervalMs: 30_000, minReconnectMs: 1_000, maxReconnectMs: 60_000, ...options };
|
|
16
|
+
}
|
|
17
|
+
get isReady() {
|
|
18
|
+
return this.ready;
|
|
19
|
+
}
|
|
20
|
+
start() {
|
|
21
|
+
if (!this.stopped) {
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
this.stopped = false;
|
|
25
|
+
this.open();
|
|
26
|
+
}
|
|
27
|
+
stop() {
|
|
28
|
+
this.stopped = true;
|
|
29
|
+
this.clearTimers();
|
|
30
|
+
this.ready = false;
|
|
31
|
+
const socket = this.socket;
|
|
32
|
+
this.socket = null;
|
|
33
|
+
socket?.close(1000);
|
|
34
|
+
this.options.handlers.onStateChange("closed");
|
|
35
|
+
}
|
|
36
|
+
/** Sends an ack now, or once the socket is ready again. */
|
|
37
|
+
ack(ids, event) {
|
|
38
|
+
for (let start = 0; start < ids.length; start += 100) {
|
|
39
|
+
const chunk = { ids: ids.slice(start, start + 100), event };
|
|
40
|
+
if (!this.ready || !this.send({ type: "ack", ...chunk })) {
|
|
41
|
+
this.pendingAcks.push(chunk);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
open() {
|
|
46
|
+
this.options.handlers.onStateChange("connecting");
|
|
47
|
+
let socket;
|
|
48
|
+
try {
|
|
49
|
+
socket = new this.options.WebSocket(this.options.url);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
this.scheduleReconnect();
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
this.socket = socket;
|
|
56
|
+
socket.onopen = () => {
|
|
57
|
+
this.send({ type: "auth", device_token: this.options.deviceToken });
|
|
58
|
+
};
|
|
59
|
+
socket.onmessage = (event) => {
|
|
60
|
+
this.handleFrame(typeof event.data === "string" ? event.data : "");
|
|
61
|
+
};
|
|
62
|
+
socket.onclose = () => {
|
|
63
|
+
if (this.socket !== socket) {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
this.socket = null;
|
|
67
|
+
this.ready = false;
|
|
68
|
+
this.clearTimers();
|
|
69
|
+
if (!this.stopped) {
|
|
70
|
+
this.scheduleReconnect();
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
socket.onerror = () => {
|
|
74
|
+
// onclose follows and schedules the reconnect.
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
handleFrame(raw) {
|
|
78
|
+
let frame;
|
|
79
|
+
try {
|
|
80
|
+
frame = JSON.parse(raw);
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
switch (frame.type) {
|
|
86
|
+
case "ready":
|
|
87
|
+
this.ready = true;
|
|
88
|
+
this.attempt = 0;
|
|
89
|
+
this.startPinging();
|
|
90
|
+
this.flushAcks();
|
|
91
|
+
this.options.handlers.onStateChange("ready");
|
|
92
|
+
this.options.handlers.onReady();
|
|
93
|
+
break;
|
|
94
|
+
case "message":
|
|
95
|
+
if (frame.message !== null && typeof frame.message === "object") {
|
|
96
|
+
this.options.handlers.onMessage(frame.message);
|
|
97
|
+
}
|
|
98
|
+
break;
|
|
99
|
+
case "ping":
|
|
100
|
+
this.send({ type: "pong" });
|
|
101
|
+
break;
|
|
102
|
+
case "error":
|
|
103
|
+
if (frame.error === "device_token_invalid" || frame.error === "auth_required") {
|
|
104
|
+
this.stopped = true;
|
|
105
|
+
this.clearTimers();
|
|
106
|
+
this.options.handlers.onUnauthorized();
|
|
107
|
+
}
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
send(frame) {
|
|
112
|
+
if (this.socket === null || this.socket.readyState !== 1) {
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
this.socket.send(JSON.stringify(frame));
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
flushAcks() {
|
|
124
|
+
const pending = this.pendingAcks.splice(0);
|
|
125
|
+
for (const chunk of pending) {
|
|
126
|
+
if (!this.send({ type: "ack", ...chunk })) {
|
|
127
|
+
this.pendingAcks.push(chunk);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
startPinging() {
|
|
132
|
+
this.pingTimer = setInterval(() => this.send({ type: "ping" }), this.options.pingIntervalMs);
|
|
133
|
+
}
|
|
134
|
+
scheduleReconnect() {
|
|
135
|
+
this.options.handlers.onStateChange("connecting");
|
|
136
|
+
const ceiling = Math.min(this.options.maxReconnectMs, this.options.minReconnectMs * 2 ** this.attempt);
|
|
137
|
+
const delay = ceiling / 2 + Math.random() * (ceiling / 2);
|
|
138
|
+
this.attempt++;
|
|
139
|
+
this.reconnectTimer = setTimeout(() => {
|
|
140
|
+
this.reconnectTimer = null;
|
|
141
|
+
if (!this.stopped) {
|
|
142
|
+
this.open();
|
|
143
|
+
}
|
|
144
|
+
}, delay);
|
|
145
|
+
}
|
|
146
|
+
clearTimers() {
|
|
147
|
+
if (this.reconnectTimer !== null) {
|
|
148
|
+
clearTimeout(this.reconnectTimer);
|
|
149
|
+
this.reconnectTimer = null;
|
|
150
|
+
}
|
|
151
|
+
if (this.pingTimer !== null) {
|
|
152
|
+
clearInterval(this.pingTimer);
|
|
153
|
+
this.pingTimer = null;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
package/dist/ialert.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { type WebSocketFactory } from "./gateway.ts";
|
|
2
|
+
import type { AckEvent, ConnectionState, Device, IAlertMessage, KeyValueStorage, RegisterOptions, TagValue, UpdateOptions } from "./types.ts";
|
|
3
|
+
export declare const SDK_VERSION = "0.1.0";
|
|
4
|
+
export interface IAlertOptions {
|
|
5
|
+
/** Public key of the app (`ia_pk_…`); it can only register and manage its own device. */
|
|
6
|
+
publicKey: string;
|
|
7
|
+
apiUrl?: string;
|
|
8
|
+
gatewayUrl?: string;
|
|
9
|
+
storage?: KeyValueStorage;
|
|
10
|
+
fetch?: typeof globalThis.fetch;
|
|
11
|
+
WebSocket?: WebSocketFactory;
|
|
12
|
+
/** Connect to the Gateway right after `register()`; default true. */
|
|
13
|
+
autoConnect?: boolean;
|
|
14
|
+
/** Ack "delivered" for every message handed to listeners; default true. */
|
|
15
|
+
autoAckDelivered?: boolean;
|
|
16
|
+
}
|
|
17
|
+
type MessageListener = (message: IAlertMessage) => void;
|
|
18
|
+
type StateListener = (state: ConnectionState) => void;
|
|
19
|
+
/**
|
|
20
|
+
* iAlert Web SDK. Registers the browser as a `web` device, keeps a Gateway
|
|
21
|
+
* socket open while the page is open, syncs the Inbox after every (re)connect
|
|
22
|
+
* and hands each notification to listeners exactly once.
|
|
23
|
+
*/
|
|
24
|
+
export declare class IAlert {
|
|
25
|
+
private readonly api;
|
|
26
|
+
private readonly store;
|
|
27
|
+
private readonly options;
|
|
28
|
+
private readonly messageListeners;
|
|
29
|
+
private readonly stateListeners;
|
|
30
|
+
private gateway;
|
|
31
|
+
private seen;
|
|
32
|
+
private syncing;
|
|
33
|
+
constructor(options: IAlertOptions);
|
|
34
|
+
/** The registered device id, or null before `register()`. */
|
|
35
|
+
get deviceId(): string | null;
|
|
36
|
+
/**
|
|
37
|
+
* Register (or re-register) this browser. Safe to call on every page load:
|
|
38
|
+
* the same installation id maps to the same device and re-subscribes it.
|
|
39
|
+
*/
|
|
40
|
+
register(options?: RegisterOptions): Promise<Device>;
|
|
41
|
+
/** Update the external user id, tags (merged) or locale of this device. */
|
|
42
|
+
update(options: UpdateOptions): Promise<Device>;
|
|
43
|
+
setTags(tags: Record<string, TagValue | null>): Promise<Device>;
|
|
44
|
+
setExternalUserId(externalUserId: string | null): Promise<Device>;
|
|
45
|
+
/** Stop receiving notifications; call `register()` to subscribe again. */
|
|
46
|
+
unsubscribe(): Promise<Device>;
|
|
47
|
+
/** Open the Gateway socket (done by `register()` unless `autoConnect: false`). */
|
|
48
|
+
connect(): void;
|
|
49
|
+
disconnect(): void;
|
|
50
|
+
/**
|
|
51
|
+
* Pull Inbox entries not yet delivered here (missed while the page was closed)
|
|
52
|
+
* and hand the new ones to listeners. Concurrent calls share one request.
|
|
53
|
+
*/
|
|
54
|
+
syncInbox(): Promise<IAlertMessage[]>;
|
|
55
|
+
/** Report that the user read or clicked notifications (by notification id). */
|
|
56
|
+
ack(ids: string[], event: AckEvent): Promise<void>;
|
|
57
|
+
/** Listen for notifications; returns a function that removes the listener. */
|
|
58
|
+
onMessage(listener: MessageListener): () => void;
|
|
59
|
+
onConnectionStateChange(listener: StateListener): () => void;
|
|
60
|
+
private pullInbox;
|
|
61
|
+
/** Dedupe by notification id across Gateway, Inbox and page loads. */
|
|
62
|
+
private receive;
|
|
63
|
+
private hasSeen;
|
|
64
|
+
private fromGateway;
|
|
65
|
+
private fromInbox;
|
|
66
|
+
private deviceFields;
|
|
67
|
+
/** Locale, timezone and browser details detected when the caller does not set them. */
|
|
68
|
+
private environmentFields;
|
|
69
|
+
private installationId;
|
|
70
|
+
private registration;
|
|
71
|
+
private requireRegistration;
|
|
72
|
+
/** A rejected device token means the device was deleted or unsubscribed elsewhere. */
|
|
73
|
+
private withToken;
|
|
74
|
+
private emitState;
|
|
75
|
+
}
|
|
76
|
+
export {};
|
package/dist/ialert.js
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { ApiClient } from "./api.js";
|
|
2
|
+
import { IAlertError } from "./errors.js";
|
|
3
|
+
import { GatewayConnection } from "./gateway.js";
|
|
4
|
+
import { Store, defaultStorage } from "./storage.js";
|
|
5
|
+
export const SDK_VERSION = "0.1.0";
|
|
6
|
+
const TAG_KEY = /^[A-Za-z0-9_.:-]{1,64}$/;
|
|
7
|
+
const SEEN_LIMIT = 500;
|
|
8
|
+
/**
|
|
9
|
+
* iAlert Web SDK. Registers the browser as a `web` device, keeps a Gateway
|
|
10
|
+
* socket open while the page is open, syncs the Inbox after every (re)connect
|
|
11
|
+
* and hands each notification to listeners exactly once.
|
|
12
|
+
*/
|
|
13
|
+
export class IAlert {
|
|
14
|
+
api;
|
|
15
|
+
store;
|
|
16
|
+
options;
|
|
17
|
+
messageListeners = new Set();
|
|
18
|
+
stateListeners = new Set();
|
|
19
|
+
gateway = null;
|
|
20
|
+
seen;
|
|
21
|
+
syncing = null;
|
|
22
|
+
constructor(options) {
|
|
23
|
+
if (!options.publicKey.startsWith("ia_pk_")) {
|
|
24
|
+
throw new IAlertError(0, "invalid_public_key", "Use the app's public key (ia_pk_…); secret keys must never ship to browsers.");
|
|
25
|
+
}
|
|
26
|
+
this.options = options;
|
|
27
|
+
const fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
28
|
+
this.api = new ApiClient(options.apiUrl ?? "https://api.ialert.ir/api/v1", options.publicKey, fetchFn);
|
|
29
|
+
this.store = new Store(options.storage ?? defaultStorage(), options.publicKey.slice(-12));
|
|
30
|
+
this.seen = this.store.get("seen") ?? [];
|
|
31
|
+
}
|
|
32
|
+
/** The registered device id, or null before `register()`. */
|
|
33
|
+
get deviceId() {
|
|
34
|
+
return this.registration()?.deviceId ?? null;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Register (or re-register) this browser. Safe to call on every page load:
|
|
38
|
+
* the same installation id maps to the same device and re-subscribes it.
|
|
39
|
+
*/
|
|
40
|
+
async register(options = {}) {
|
|
41
|
+
const result = await this.api.register({
|
|
42
|
+
platform: "web",
|
|
43
|
+
push_token: options.pushToken ?? this.installationId(),
|
|
44
|
+
sdk_version: SDK_VERSION,
|
|
45
|
+
...this.deviceFields(options),
|
|
46
|
+
...this.environmentFields(options),
|
|
47
|
+
});
|
|
48
|
+
this.store.set("registration", { deviceId: result.data.id, deviceToken: result.device_token });
|
|
49
|
+
if (this.options.autoConnect !== false) {
|
|
50
|
+
this.connect();
|
|
51
|
+
}
|
|
52
|
+
return result.data;
|
|
53
|
+
}
|
|
54
|
+
/** Update the external user id, tags (merged) or locale of this device. */
|
|
55
|
+
async update(options) {
|
|
56
|
+
const registration = this.requireRegistration();
|
|
57
|
+
return this.withToken(() => this.api.update(registration.deviceId, registration.deviceToken, this.deviceFields(options)));
|
|
58
|
+
}
|
|
59
|
+
setTags(tags) {
|
|
60
|
+
return this.update({ tags });
|
|
61
|
+
}
|
|
62
|
+
setExternalUserId(externalUserId) {
|
|
63
|
+
return this.update({ externalUserId });
|
|
64
|
+
}
|
|
65
|
+
/** Stop receiving notifications; call `register()` to subscribe again. */
|
|
66
|
+
async unsubscribe() {
|
|
67
|
+
const registration = this.requireRegistration();
|
|
68
|
+
this.disconnect();
|
|
69
|
+
return this.withToken(() => this.api.unsubscribe(registration.deviceId, registration.deviceToken));
|
|
70
|
+
}
|
|
71
|
+
/** Open the Gateway socket (done by `register()` unless `autoConnect: false`). */
|
|
72
|
+
connect() {
|
|
73
|
+
const registration = this.requireRegistration();
|
|
74
|
+
const WebSocketImpl = this.options.WebSocket ?? globalThis.WebSocket;
|
|
75
|
+
if (this.gateway !== null || WebSocketImpl === undefined) {
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
this.gateway = new GatewayConnection({
|
|
79
|
+
url: this.options.gatewayUrl ?? "wss://gw.ialert.ir/v1/connect",
|
|
80
|
+
deviceToken: registration.deviceToken,
|
|
81
|
+
WebSocket: WebSocketImpl,
|
|
82
|
+
handlers: {
|
|
83
|
+
onReady: () => {
|
|
84
|
+
void this.syncInbox().catch(() => undefined);
|
|
85
|
+
},
|
|
86
|
+
onMessage: (message) => this.receive(this.fromGateway(message)),
|
|
87
|
+
onUnauthorized: () => {
|
|
88
|
+
this.gateway = null;
|
|
89
|
+
this.store.remove("registration");
|
|
90
|
+
this.emitState("closed");
|
|
91
|
+
},
|
|
92
|
+
onStateChange: (state) => this.emitState(state),
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
this.gateway.start();
|
|
96
|
+
}
|
|
97
|
+
disconnect() {
|
|
98
|
+
this.gateway?.stop();
|
|
99
|
+
this.gateway = null;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Pull Inbox entries not yet delivered here (missed while the page was closed)
|
|
103
|
+
* and hand the new ones to listeners. Concurrent calls share one request.
|
|
104
|
+
*/
|
|
105
|
+
syncInbox() {
|
|
106
|
+
this.syncing ??= this.pullInbox().finally(() => {
|
|
107
|
+
this.syncing = null;
|
|
108
|
+
});
|
|
109
|
+
return this.syncing;
|
|
110
|
+
}
|
|
111
|
+
/** Report that the user read or clicked notifications (by notification id). */
|
|
112
|
+
async ack(ids, event) {
|
|
113
|
+
if (ids.length === 0) {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
const registration = this.requireRegistration();
|
|
117
|
+
if (this.gateway?.isReady) {
|
|
118
|
+
this.gateway.ack(ids, event);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
await this.withToken(() => this.api.ack(registration.deviceId, registration.deviceToken, ids, event));
|
|
122
|
+
}
|
|
123
|
+
/** Listen for notifications; returns a function that removes the listener. */
|
|
124
|
+
onMessage(listener) {
|
|
125
|
+
this.messageListeners.add(listener);
|
|
126
|
+
return () => this.messageListeners.delete(listener);
|
|
127
|
+
}
|
|
128
|
+
onConnectionStateChange(listener) {
|
|
129
|
+
this.stateListeners.add(listener);
|
|
130
|
+
return () => this.stateListeners.delete(listener);
|
|
131
|
+
}
|
|
132
|
+
async pullInbox() {
|
|
133
|
+
const registration = this.requireRegistration();
|
|
134
|
+
const entries = await this.withToken(() => this.api.inbox(registration.deviceId, registration.deviceToken, true));
|
|
135
|
+
// Oldest first, so listeners see messages in the order they were sent.
|
|
136
|
+
const received = [...entries]
|
|
137
|
+
.reverse()
|
|
138
|
+
.map((entry) => this.fromInbox(entry))
|
|
139
|
+
.filter((message) => this.receive(message, false));
|
|
140
|
+
if (this.options.autoAckDelivered !== false) {
|
|
141
|
+
const undelivered = entries.filter((entry) => entry.delivered_at === null).map((entry) => entry.id);
|
|
142
|
+
await this.ack(undelivered, "delivered").catch(() => undefined);
|
|
143
|
+
}
|
|
144
|
+
return received;
|
|
145
|
+
}
|
|
146
|
+
/** Dedupe by notification id across Gateway, Inbox and page loads. */
|
|
147
|
+
receive(message, ack = true) {
|
|
148
|
+
if (this.hasSeen(message.id)) {
|
|
149
|
+
return false;
|
|
150
|
+
}
|
|
151
|
+
this.seen.push(message.id);
|
|
152
|
+
this.seen = this.seen.slice(-SEEN_LIMIT);
|
|
153
|
+
this.store.set("seen", this.seen);
|
|
154
|
+
for (const listener of this.messageListeners) {
|
|
155
|
+
try {
|
|
156
|
+
listener(message);
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
queueMicrotask(() => {
|
|
160
|
+
throw error;
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (ack && this.options.autoAckDelivered !== false) {
|
|
165
|
+
void this.ack([message.id], "delivered").catch(() => undefined);
|
|
166
|
+
}
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
hasSeen(id) {
|
|
170
|
+
return this.seen.includes(id);
|
|
171
|
+
}
|
|
172
|
+
fromGateway(message) {
|
|
173
|
+
const text = (value) => (typeof value === "string" ? value : null);
|
|
174
|
+
return {
|
|
175
|
+
id: String(message.id),
|
|
176
|
+
title: text(message.title),
|
|
177
|
+
body: text(message.body),
|
|
178
|
+
image: text(message.image),
|
|
179
|
+
data: message.data !== null && typeof message.data === "object" && !Array.isArray(message.data) ? message.data : {},
|
|
180
|
+
collapse_id: text(message.collapse_id),
|
|
181
|
+
created_at: text(message.created_at),
|
|
182
|
+
source: "gateway",
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
fromInbox(entry) {
|
|
186
|
+
const data = entry.content.data;
|
|
187
|
+
return {
|
|
188
|
+
id: entry.id,
|
|
189
|
+
title: entry.content.title,
|
|
190
|
+
body: entry.content.body,
|
|
191
|
+
image: entry.content.image,
|
|
192
|
+
data: data !== null && !Array.isArray(data) ? data : {},
|
|
193
|
+
collapse_id: entry.collapse_id,
|
|
194
|
+
created_at: entry.created_at,
|
|
195
|
+
source: "inbox",
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
deviceFields(options) {
|
|
199
|
+
const fields = {};
|
|
200
|
+
if (options.externalUserId !== undefined) {
|
|
201
|
+
fields.external_user_id = options.externalUserId;
|
|
202
|
+
}
|
|
203
|
+
if (options.tags !== undefined) {
|
|
204
|
+
const invalid = Object.keys(options.tags).filter((key) => !TAG_KEY.test(key));
|
|
205
|
+
if (invalid.length > 0) {
|
|
206
|
+
throw new IAlertError(0, "invalid_tag_key", `Tag keys must match [A-Za-z0-9_.:-]{1,64}: ${invalid.join(", ")}`);
|
|
207
|
+
}
|
|
208
|
+
fields.tags = options.tags;
|
|
209
|
+
}
|
|
210
|
+
if (options.locale !== undefined) {
|
|
211
|
+
fields.locale = options.locale;
|
|
212
|
+
}
|
|
213
|
+
if (options.timezone !== undefined) {
|
|
214
|
+
fields.timezone = options.timezone;
|
|
215
|
+
}
|
|
216
|
+
if (options.appVersion !== undefined) {
|
|
217
|
+
fields.app_version = options.appVersion;
|
|
218
|
+
}
|
|
219
|
+
return fields;
|
|
220
|
+
}
|
|
221
|
+
/** Locale, timezone and browser details detected when the caller does not set them. */
|
|
222
|
+
environmentFields(options) {
|
|
223
|
+
const fields = {};
|
|
224
|
+
const navigatorInfo = globalThis.navigator;
|
|
225
|
+
if (options.locale === undefined && navigatorInfo?.language) {
|
|
226
|
+
fields.locale = navigatorInfo.language;
|
|
227
|
+
}
|
|
228
|
+
if (options.timezone === undefined) {
|
|
229
|
+
try {
|
|
230
|
+
fields.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
// ignore
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
const userAgent = navigatorInfo?.userAgent;
|
|
237
|
+
if (userAgent) {
|
|
238
|
+
fields.device_model = detectBrowser(userAgent);
|
|
239
|
+
fields.os_version = navigatorInfo?.userAgentData?.platform ?? detectOs(userAgent);
|
|
240
|
+
}
|
|
241
|
+
return Object.fromEntries(Object.entries(fields).filter(([, value]) => typeof value === "string" && value !== ""));
|
|
242
|
+
}
|
|
243
|
+
installationId() {
|
|
244
|
+
let id = this.store.get("installation");
|
|
245
|
+
if (id === null) {
|
|
246
|
+
id = `ia_web_${globalThis.crypto.randomUUID()}`;
|
|
247
|
+
this.store.set("installation", id);
|
|
248
|
+
}
|
|
249
|
+
return id;
|
|
250
|
+
}
|
|
251
|
+
registration() {
|
|
252
|
+
return this.store.get("registration");
|
|
253
|
+
}
|
|
254
|
+
requireRegistration() {
|
|
255
|
+
const registration = this.registration();
|
|
256
|
+
if (registration === null) {
|
|
257
|
+
throw new IAlertError(0, "not_registered", "Call register() first.");
|
|
258
|
+
}
|
|
259
|
+
return registration;
|
|
260
|
+
}
|
|
261
|
+
/** A rejected device token means the device was deleted or unsubscribed elsewhere. */
|
|
262
|
+
async withToken(call) {
|
|
263
|
+
try {
|
|
264
|
+
return await call();
|
|
265
|
+
}
|
|
266
|
+
catch (error) {
|
|
267
|
+
if (error instanceof IAlertError && (error.code === "device_token_invalid" || error.status === 404)) {
|
|
268
|
+
this.disconnect();
|
|
269
|
+
this.store.remove("registration");
|
|
270
|
+
}
|
|
271
|
+
throw error;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
emitState(state) {
|
|
275
|
+
for (const listener of this.stateListeners) {
|
|
276
|
+
listener(state);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
function detectBrowser(userAgent) {
|
|
281
|
+
const match = /(Edg|OPR|SamsungBrowser|Firefox|Chrome|Safari)\/(\d+)/.exec(userAgent);
|
|
282
|
+
if (match === null) {
|
|
283
|
+
return "Browser";
|
|
284
|
+
}
|
|
285
|
+
const names = { Edg: "Edge", OPR: "Opera", SamsungBrowser: "Samsung Internet" };
|
|
286
|
+
return `${names[match[1] ?? ""] ?? match[1]} ${match[2]}`;
|
|
287
|
+
}
|
|
288
|
+
function detectOs(userAgent) {
|
|
289
|
+
for (const [pattern, name] of [
|
|
290
|
+
[/Android/, "Android"],
|
|
291
|
+
[/iPhone|iPad|iPod/, "iOS"],
|
|
292
|
+
[/Windows/, "Windows"],
|
|
293
|
+
[/Mac OS X/, "macOS"],
|
|
294
|
+
[/Linux/, "Linux"],
|
|
295
|
+
]) {
|
|
296
|
+
if (pattern.test(userAgent)) {
|
|
297
|
+
return name;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return "Unknown";
|
|
301
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { IAlert, SDK_VERSION, type IAlertOptions } from "./ialert.ts";
|
|
2
|
+
export { IAlertError } from "./errors.ts";
|
|
3
|
+
export { MemoryStorage } from "./storage.ts";
|
|
4
|
+
export type { AckEvent, ConnectionState, Device, IAlertMessage, KeyValueStorage, RegisterOptions, TagValue, UpdateOptions } from "./types.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { KeyValueStorage } from "./types.ts";
|
|
2
|
+
/** In-memory storage for environments without localStorage (private mode, workers, tests). */
|
|
3
|
+
export declare class MemoryStorage implements KeyValueStorage {
|
|
4
|
+
private readonly items;
|
|
5
|
+
getItem(key: string): string | null;
|
|
6
|
+
setItem(key: string, value: string): void;
|
|
7
|
+
removeItem(key: string): void;
|
|
8
|
+
}
|
|
9
|
+
/** localStorage when it works, otherwise memory (it throws in some private windows). */
|
|
10
|
+
export declare function defaultStorage(): KeyValueStorage;
|
|
11
|
+
/** Namespaced JSON helpers over a KeyValueStorage; never throws. */
|
|
12
|
+
export declare class Store {
|
|
13
|
+
private readonly storage;
|
|
14
|
+
private readonly prefix;
|
|
15
|
+
constructor(storage: KeyValueStorage, namespace: string);
|
|
16
|
+
get<T>(key: string): T | null;
|
|
17
|
+
set(key: string, value: unknown): void;
|
|
18
|
+
remove(key: string): void;
|
|
19
|
+
}
|
package/dist/storage.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/** In-memory storage for environments without localStorage (private mode, workers, tests). */
|
|
2
|
+
export class MemoryStorage {
|
|
3
|
+
items = new Map();
|
|
4
|
+
getItem(key) {
|
|
5
|
+
return this.items.get(key) ?? null;
|
|
6
|
+
}
|
|
7
|
+
setItem(key, value) {
|
|
8
|
+
this.items.set(key, value);
|
|
9
|
+
}
|
|
10
|
+
removeItem(key) {
|
|
11
|
+
this.items.delete(key);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** localStorage when it works, otherwise memory (it throws in some private windows). */
|
|
15
|
+
export function defaultStorage() {
|
|
16
|
+
try {
|
|
17
|
+
const storage = globalThis.localStorage;
|
|
18
|
+
const probe = "__ialert_probe__";
|
|
19
|
+
storage.setItem(probe, "1");
|
|
20
|
+
storage.removeItem(probe);
|
|
21
|
+
return storage;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return new MemoryStorage();
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** Namespaced JSON helpers over a KeyValueStorage; never throws. */
|
|
28
|
+
export class Store {
|
|
29
|
+
storage;
|
|
30
|
+
prefix;
|
|
31
|
+
constructor(storage, namespace) {
|
|
32
|
+
this.storage = storage;
|
|
33
|
+
this.prefix = `ialert:${namespace}:`;
|
|
34
|
+
}
|
|
35
|
+
get(key) {
|
|
36
|
+
try {
|
|
37
|
+
const raw = this.storage.getItem(this.prefix + key);
|
|
38
|
+
return raw === null ? null : JSON.parse(raw);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
set(key, value) {
|
|
45
|
+
try {
|
|
46
|
+
this.storage.setItem(this.prefix + key, JSON.stringify(value));
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
// Storage full or blocked: the SDK keeps working for this page load.
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
remove(key) {
|
|
53
|
+
try {
|
|
54
|
+
this.storage.removeItem(this.prefix + key);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
// ignore
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
export type TagValue = string | number | boolean;
|
|
2
|
+
/** Device as returned by the iAlert API (the push token itself is never returned). */
|
|
3
|
+
export interface Device {
|
|
4
|
+
id: string;
|
|
5
|
+
platform: "android" | "ios" | "web";
|
|
6
|
+
push_token_suffix: string;
|
|
7
|
+
external_user_id: string | null;
|
|
8
|
+
tags: Record<string, TagValue>;
|
|
9
|
+
locale: string | null;
|
|
10
|
+
timezone: string | null;
|
|
11
|
+
app_version: string | null;
|
|
12
|
+
sdk_version: string | null;
|
|
13
|
+
device_model: string | null;
|
|
14
|
+
os_version: string | null;
|
|
15
|
+
subscribed: boolean;
|
|
16
|
+
unsubscribed_at: string | null;
|
|
17
|
+
last_seen_at: string | null;
|
|
18
|
+
created_at: string;
|
|
19
|
+
updated_at: string;
|
|
20
|
+
}
|
|
21
|
+
/** A notification as received from the Gateway or the Inbox; `id` is the notification id. */
|
|
22
|
+
export interface IAlertMessage {
|
|
23
|
+
id: string;
|
|
24
|
+
title: string | null;
|
|
25
|
+
body: string | null;
|
|
26
|
+
image: string | null;
|
|
27
|
+
data: Record<string, unknown>;
|
|
28
|
+
collapse_id: string | null;
|
|
29
|
+
created_at: string | null;
|
|
30
|
+
/** Where the SDK got it first. */
|
|
31
|
+
source: "gateway" | "inbox";
|
|
32
|
+
}
|
|
33
|
+
export type AckEvent = "delivered" | "read" | "clicked";
|
|
34
|
+
export interface RegisterOptions {
|
|
35
|
+
externalUserId?: string | null;
|
|
36
|
+
/** Merged into existing tags; `null` removes a tag. */
|
|
37
|
+
tags?: Record<string, TagValue | null>;
|
|
38
|
+
locale?: string;
|
|
39
|
+
timezone?: string;
|
|
40
|
+
appVersion?: string;
|
|
41
|
+
/** Web Push subscription JSON once Web Push is enabled; defaults to a stable per-browser installation id. */
|
|
42
|
+
pushToken?: string;
|
|
43
|
+
}
|
|
44
|
+
export interface UpdateOptions {
|
|
45
|
+
externalUserId?: string | null;
|
|
46
|
+
tags?: Record<string, TagValue | null>;
|
|
47
|
+
locale?: string;
|
|
48
|
+
timezone?: string;
|
|
49
|
+
appVersion?: string;
|
|
50
|
+
}
|
|
51
|
+
/** Minimal key/value storage; `localStorage` matches it. */
|
|
52
|
+
export interface KeyValueStorage {
|
|
53
|
+
getItem(key: string): string | null;
|
|
54
|
+
setItem(key: string, value: string): void;
|
|
55
|
+
removeItem(key: string): void;
|
|
56
|
+
}
|
|
57
|
+
export type ConnectionState = "idle" | "connecting" | "ready" | "closed";
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ialert-web",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "iAlert Web SDK: register browsers and receive notifications over the iAlert Gateway and Inbox.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"ialert",
|
|
7
|
+
"push",
|
|
8
|
+
"push-notifications",
|
|
9
|
+
"notifications",
|
|
10
|
+
"websocket",
|
|
11
|
+
"web-push"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://github.com/iAlert-ai/ialert-web#readme",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/iAlert-ai/ialert-web/issues"
|
|
16
|
+
},
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/iAlert-ai/ialert-web.git"
|
|
20
|
+
},
|
|
21
|
+
"license": "Apache-2.0",
|
|
22
|
+
"type": "module",
|
|
23
|
+
"main": "./dist/index.js",
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"import": "./dist/index.js"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"dist",
|
|
33
|
+
"NOTICE"
|
|
34
|
+
],
|
|
35
|
+
"sideEffects": false,
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=22"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsc -p tsconfig.build.json",
|
|
41
|
+
"typecheck": "tsc --noEmit",
|
|
42
|
+
"test": "node --test test/*.test.ts"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@types/node": "^22.20.5",
|
|
46
|
+
"typescript": "^5.9.3"
|
|
47
|
+
}
|
|
48
|
+
}
|