-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
app.js
285 lines (234 loc) · 8.27 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
"use strict";
/* eslint-env browser */
/* global EventSourcePolyfill */
(function () {
const origin = window.location.origin;
const defaultTopic = document.URL + "demo/books/1.jsonld";
const placeholderTopic = "https://example.com/my-private-topic";
const defaultJwt =
"eyJhbGciOiJIUzI1NiJ9.eyJtZXJjdXJlIjp7InB1Ymxpc2giOlsiKiJdLCJzdWJzY3JpYmUiOlsiaHR0cHM6Ly9leGFtcGxlLmNvbS9teS1wcml2YXRlLXRvcGljIiwie3NjaGVtZX06Ly97K2hvc3R9L2RlbW8vYm9va3Mve2lkfS5qc29ubGQiLCIvLndlbGwta25vd24vbWVyY3VyZS9zdWJzY3JpcHRpb25zey90b3BpY317L3N1YnNjcmliZXJ9Il0sInBheWxvYWQiOnsidXNlciI6Imh0dHBzOi8vZXhhbXBsZS5jb20vdXNlcnMvZHVuZ2xhcyIsInJlbW90ZUFkZHIiOiIxMjcuMC4wLjEifX19.KKPIikwUzRuB3DTpVw6ajzwSChwFw5omBMmMcWKiDcM";
const $updates = document.getElementById("updates");
const $subscriptions = document.getElementById("subscriptions");
const $settingsForm = document.forms.settings;
const $discoverForm = document.forms.discover;
const $subscribeForm = document.forms.subscribe;
const $publishForm = document.forms.publish;
const $subscriptionsForm = document.forms.subscriptions;
const error = (e) => {
if (!e.error || e.error.message?.includes?.("Reconnecting")) {
// Silent reconnecting messages from the polyfill
console.log("Connection closed, reconnecting...", e);
return;
}
console.log(e);
if (e.toString !== Object.prototype.toString) {
// Display relevant error message
alert(e.toString());
return;
}
if (e.statusText) {
// Special handling of errors from the polyfill
alert(e.statusText);
return;
}
alert("An error occured, details have been logged.");
};
const getHubUrl = (resp) => {
const link = resp.headers.get("Link");
if (!link) {
error('No rel="mercure" Link header provided.');
}
const match = link.match(/<(.*)>.*rel="mercure".*/);
if (match && match[1]) return match[1];
};
// Set default values
document.addEventListener("DOMContentLoaded", () => {
$settingsForm.hubUrl.value = origin + "/.well-known/mercure";
$settingsForm.jwt.value = defaultJwt;
$discoverForm.topic.value = defaultTopic;
$discoverForm.body.value = JSON.stringify(
{
"@id": defaultTopic,
availability: "https://schema.org/InStock",
},
null,
2,
);
$publishForm.data.value = JSON.stringify(
{
"@id": defaultTopic,
availability: "https://schema.org/OutOfStock",
},
null,
2,
);
document.getElementById("subscribeTopicsExamples").textContent =
`${document.URL}demo/novels/{id}.jsonld
${defaultTopic}
foo`;
});
// Discover
$discoverForm.onsubmit = async function (e) {
e.preventDefault();
const {
elements: { topic, body },
} = this;
const jwt = $settingsForm.jwt.value;
const url = new URL(topic.value);
if (body.value) url.searchParams.append("body", body.value);
if (jwt) url.searchParams.append("jwt", jwt);
try {
const resp = await fetch(url);
if (!resp.ok) throw new Error(resp.statusText);
// Set hub default
const hubUrl = getHubUrl(resp);
if (hubUrl) $settingsForm.hubUrl.value = new URL(hubUrl, topic.value);
const subscribeTopics = $subscribeForm.topics;
if (subscribeTopics.value === placeholderTopic) {
subscribeTopics.value = topic.value;
}
// Set publish default values
const publishTopics = $publishForm.topics;
if (publishTopics.value === placeholderTopic) {
publishTopics.value = topic.value;
}
const text = await resp.text();
body.value = text;
} catch (e) {
error(e);
}
};
// Subscribe
const $updateTemplate = document.getElementById("update");
let updateEventSource;
$subscribeForm.onsubmit = function (e) {
e.preventDefault();
updateEventSource && updateEventSource.close();
$updates.textContent = "No updates pushed yet.";
const {
elements: { topics, lastEventId },
} = this;
const topicList = topics.value.split("\n");
const u = new URL($settingsForm.hubUrl.value);
topicList.forEach((topic) => u.searchParams.append("topic", topic));
if (lastEventId.value) {
u.searchParams.append("lastEventID", lastEventId.value);
}
let ol = null;
if ($settingsForm.authorization.value === "header") {
updateEventSource = new EventSourcePolyfill(u, {
headers: {
Authorization: `Bearer ${$settingsForm.jwt.value}`,
},
});
} else updateEventSource = new EventSource(u);
updateEventSource.onmessage = function (e) {
if (!ol) {
ol = document.createElement("ol");
ol.reversed = true;
$updates.textContent = "";
$updates.appendChild(ol);
}
const li = document.importNode($updateTemplate.content, true);
li.querySelector("h2").textContent = e.lastEventId;
li.querySelector("pre").textContent = e.data;
ol.firstChild ? ol.insertBefore(li, ol.firstChild) : ol.appendChild(li);
};
updateEventSource.onerror = error;
this.elements.unsubscribe.disabled = false;
};
$subscribeForm.elements.unsubscribe.onclick = function (e) {
e.preventDefault();
updateEventSource && updateEventSource.close();
this.disabled = true;
$updates.textContent = "Unsubscribed.";
};
// Publish
$publishForm.onsubmit = async function (e) {
e.preventDefault();
const {
elements: { topics, data, priv, id, type, retry },
} = this;
const body = new URLSearchParams({
data: data.value,
id: id.value,
type: type.value,
retry: retry.value,
});
topics.value.split("\n").forEach((topic) => body.append("topic", topic));
priv.checked && body.append("private", "on");
const opt = { method: "POST", body };
if ($settingsForm.authorization.value === "header") {
opt.headers = { Authorization: `Bearer ${$settingsForm.jwt.value}` };
}
try {
const resp = await fetch($settingsForm.hubUrl.value, opt);
if (!resp.ok) throw new Error(resp.statusText);
} catch (e) {
error(e);
}
};
// Subscriptions
const $subscriptionTemplate = document.getElementById("subscription");
let subscriptionEventSource;
const addSubscription = (s) => {
const subscription = document.importNode(
$subscriptionTemplate.content,
true,
);
subscription.querySelector("div").setAttribute("id", s.id);
subscription.querySelector(".card-header-title").textContent = s.id;
subscription.querySelector(".topic").textContent = s.topic;
subscription.querySelector(".subscriber").textContent = s.subscriber;
subscription.querySelector("code").textContent = JSON.stringify(
s.payload,
null,
2,
);
$subscriptions.appendChild(subscription);
};
$subscriptionsForm.onsubmit = async (e) => {
e.preventDefault();
subscriptionEventSource && subscriptionEventSource.close();
$subscriptions.textContent = "";
try {
const opt =
$settingsForm.authorization.value === "header"
? { headers: { Authorization: `Bearer ${$settingsForm.jwt.value}` } }
: undefined;
const resp = await fetch(
`${$settingsForm.hubUrl.value}/subscriptions`,
opt,
);
if (!resp.ok) throw new Error(resp.statusText);
const json = await resp.json();
json.subscriptions.forEach(addSubscription);
const u = new URL($settingsForm.hubUrl.value);
u.searchParams.append(
"topic",
"/.well-known/mercure/subscriptions{/topic}{/subscriber}",
);
u.searchParams.append("lastEventID", json.lastEventID);
if (opt) subscriptionEventSource = new EventSourcePolyfill(u, opt);
else subscriptionEventSource = new EventSource(u);
subscriptionEventSource.onmessage = function (e) {
const s = JSON.parse(e.data);
if (s.active) {
addSubscription(s);
return;
}
document.getElementById(s.id).remove();
};
subscriptionEventSource.onerror = error;
$subscriptionsForm.elements.unsubscribe.disabled = false;
} catch (e) {
error(e);
}
};
$subscriptionsForm.elements.unsubscribe.onclick = function (e) {
e.preventDefault();
subscriptionEventSource.close();
this.disabled = true;
$subscriptions.textContent = "";
};
})();