@meldgrove/ui 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.
Files changed (139) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +204 -2
  3. package/dist/components/alert-dialog.d.ts +18 -0
  4. package/dist/components/alert-dialog.js +44 -0
  5. package/dist/components/alert.d.ts +9 -0
  6. package/dist/components/alert.js +25 -0
  7. package/dist/components/avatar.d.ts +11 -0
  8. package/dist/components/avatar.js +24 -0
  9. package/dist/components/badge.d.ts +9 -0
  10. package/dist/components/badge.js +25 -0
  11. package/dist/components/breadcrumb.d.ts +11 -0
  12. package/dist/components/breadcrumb.js +28 -0
  13. package/dist/components/button-group.d.ts +11 -0
  14. package/dist/components/button-group.js +27 -0
  15. package/dist/components/button.d.ts +10 -0
  16. package/dist/components/button.js +36 -0
  17. package/dist/components/calendar.d.ts +8 -0
  18. package/dist/components/calendar.js +73 -0
  19. package/dist/components/card.d.ts +9 -0
  20. package/dist/components/card.js +25 -0
  21. package/dist/components/chart.d.ts +44 -0
  22. package/dist/components/chart.js +117 -0
  23. package/dist/components/checkbox.d.ts +4 -0
  24. package/dist/components/checkbox.js +10 -0
  25. package/dist/components/collapsible.d.ts +5 -0
  26. package/dist/components/collapsible.js +13 -0
  27. package/dist/components/command.d.ts +18 -0
  28. package/dist/components/command.js +35 -0
  29. package/dist/components/confirm-dialog.d.ts +15 -0
  30. package/dist/components/confirm-dialog.js +26 -0
  31. package/dist/components/copy-button.d.ts +6 -0
  32. package/dist/components/copy-button.js +23 -0
  33. package/dist/components/dialog.d.ts +17 -0
  34. package/dist/components/dialog.js +39 -0
  35. package/dist/components/dropdown-menu.d.ts +25 -0
  36. package/dist/components/dropdown-menu.js +53 -0
  37. package/dist/components/empty.d.ts +11 -0
  38. package/dist/components/empty.js +33 -0
  39. package/dist/components/field.d.ts +24 -0
  40. package/dist/components/field.js +74 -0
  41. package/dist/components/hover-card.d.ts +6 -0
  42. package/dist/components/hover-card.js +16 -0
  43. package/dist/components/input-group.d.ts +16 -0
  44. package/dist/components/input-group.js +64 -0
  45. package/dist/components/input.d.ts +3 -0
  46. package/dist/components/input.js +7 -0
  47. package/dist/components/item.d.ts +23 -0
  48. package/dist/components/item.js +67 -0
  49. package/dist/components/kbd.d.ts +3 -0
  50. package/dist/components/kbd.js +11 -0
  51. package/dist/components/label.d.ts +4 -0
  52. package/dist/components/label.js +9 -0
  53. package/dist/components/native-select.d.ts +8 -0
  54. package/dist/components/native-select.js +14 -0
  55. package/dist/components/pager.d.ts +7 -0
  56. package/dist/components/pager.js +11 -0
  57. package/dist/components/pagination.d.ts +13 -0
  58. package/dist/components/pagination.js +30 -0
  59. package/dist/components/popover.d.ts +10 -0
  60. package/dist/components/popover.js +28 -0
  61. package/dist/components/progress.d.ts +4 -0
  62. package/dist/components/progress.js +9 -0
  63. package/dist/components/radio-group.d.ts +5 -0
  64. package/dist/components/radio-group.js +13 -0
  65. package/dist/components/scroll-area.d.ts +5 -0
  66. package/dist/components/scroll-area.js +12 -0
  67. package/dist/components/secret-field.d.ts +23 -0
  68. package/dist/components/secret-field.js +47 -0
  69. package/dist/components/select.d.ts +15 -0
  70. package/dist/components/select.js +40 -0
  71. package/dist/components/separator.d.ts +4 -0
  72. package/dist/components/separator.js +9 -0
  73. package/dist/components/sheet.d.ts +14 -0
  74. package/dist/components/sheet.js +42 -0
  75. package/dist/components/sidebar.d.ts +70 -0
  76. package/dist/components/sidebar.js +212 -0
  77. package/dist/components/skeleton.d.ts +2 -0
  78. package/dist/components/skeleton.js +6 -0
  79. package/dist/components/sonner.d.ts +5 -0
  80. package/dist/components/sonner.js +14 -0
  81. package/dist/components/spinner.d.ts +2 -0
  82. package/dist/components/spinner.js +7 -0
  83. package/dist/components/states.d.ts +14 -0
  84. package/dist/components/states.js +18 -0
  85. package/dist/components/switch.d.ts +6 -0
  86. package/dist/components/switch.js +9 -0
  87. package/dist/components/table.d.ts +17 -0
  88. package/dist/components/table.js +34 -0
  89. package/dist/components/tabs.d.ts +11 -0
  90. package/dist/components/tabs.js +30 -0
  91. package/dist/components/textarea.d.ts +3 -0
  92. package/dist/components/textarea.js +7 -0
  93. package/dist/components/toggle-group.d.ts +9 -0
  94. package/dist/components/toggle-group.js +23 -0
  95. package/dist/components/toggle.d.ts +9 -0
  96. package/dist/components/toggle.js +27 -0
  97. package/dist/components/tooltip.d.ts +7 -0
  98. package/dist/components/tooltip.js +19 -0
  99. package/dist/hooks/use-mobile.d.ts +2 -0
  100. package/dist/hooks/use-mobile.js +13 -0
  101. package/dist/lib/format.d.ts +8 -0
  102. package/dist/lib/format.js +38 -0
  103. package/dist/lib/i18n-core.d.ts +38 -0
  104. package/dist/lib/i18n-core.js +61 -0
  105. package/dist/lib/i18n.d.ts +11 -0
  106. package/dist/lib/i18n.js +19 -0
  107. package/dist/lib/portal.d.ts +13 -0
  108. package/dist/lib/portal.js +17 -0
  109. package/dist/lib/theme.d.ts +5 -0
  110. package/dist/lib/theme.js +17 -0
  111. package/dist/lib/utils.d.ts +2 -0
  112. package/dist/lib/utils.js +5 -0
  113. package/dist/standalone/meldgrove-updates.js +57 -0
  114. package/dist/styles.css +11 -0
  115. package/dist/theme.css +62 -0
  116. package/dist/tokens.css +94 -0
  117. package/dist/updates/controller.d.ts +210 -0
  118. package/dist/updates/controller.js +592 -0
  119. package/dist/updates/core.d.ts +10 -0
  120. package/dist/updates/core.js +10 -0
  121. package/dist/updates/index.d.ts +15 -0
  122. package/dist/updates/index.js +15 -0
  123. package/dist/updates/messages.d.ts +92 -0
  124. package/dist/updates/messages.js +182 -0
  125. package/dist/updates/notice.d.ts +3 -0
  126. package/dist/updates/notice.js +6 -0
  127. package/dist/updates/react.d.ts +56 -0
  128. package/dist/updates/react.js +72 -0
  129. package/dist/updates/state.d.ts +214 -0
  130. package/dist/updates/state.js +396 -0
  131. package/dist/updates/transport.d.ts +50 -0
  132. package/dist/updates/transport.js +76 -0
  133. package/dist/updates/types.d.ts +77 -0
  134. package/dist/updates/types.js +68 -0
  135. package/dist/updates/update-button.d.ts +9 -0
  136. package/dist/updates/update-button.js +161 -0
  137. package/dist/updates/updates-settings.d.ts +17 -0
  138. package/dist/updates/updates-settings.js +97 -0
  139. package/package.json +159 -4
@@ -0,0 +1,396 @@
1
+ export const SLOW_AFTER_MS = 15 * 60_000;
2
+ /** How long an unconfirmed attempt is reconciled with the status, from its start, before it is forgotten. */
3
+ export const RECONCILE_MS = 60_000;
4
+ /** A page that starts with an unconfirmed attempt asks the update service at least this long before it ends it. */
5
+ export const PAGE_GRACE_MS = 10_000;
6
+ const FAILED_RESULTS = new Set(["failed", "rolled-back"]);
7
+ function offersOf(status) {
8
+ return [status.available, status.attention].filter((update) => update !== null);
9
+ }
10
+ /**
11
+ * The failure to show: that of an installation this tab followed (`recent`,
12
+ * while it is still the updater's latest result) unless a newer version is
13
+ * offered (see `replacedFailure`), else the latest result when it failed and
14
+ * the update is marked failed.
15
+ */
16
+ export function failureOf(response, recent = null) {
17
+ const status = response?.updater;
18
+ const last = status?.last;
19
+ if (!status || !last || !FAILED_RESULTS.has(last.result))
20
+ return null;
21
+ if (recent && recent.version === last.version && recent.finishedAt === last.finishedAt) {
22
+ const offers = offersOf(status);
23
+ const offer = offers.find((update) => update.version === last.version) ?? null;
24
+ if (!offer && offers.length > 0)
25
+ return null;
26
+ return { version: last.version, message: last.message ?? offer?.failed ?? null, offer };
27
+ }
28
+ if (status.available?.failed) {
29
+ return { version: status.available.version, message: status.available.failed, offer: status.available };
30
+ }
31
+ if (status.attention && status.attention.version === last.version) {
32
+ return {
33
+ version: last.version,
34
+ message: status.attention.failed ?? last.message,
35
+ offer: status.attention,
36
+ };
37
+ }
38
+ return null;
39
+ }
40
+ /**
41
+ * A failed latest result that the popover shows as a line in an offer
42
+ * ("0.2.1 failed: …"): a newer offer took its place, or the updater offers the
43
+ * same version again without marking it failed (Updater 0.2 does so when the
44
+ * deploy link failed or no host took or finished the installation), so the
45
+ * reason stays visible after a reload.
46
+ */
47
+ export function replacedFailure(response, recent = null) {
48
+ const status = response?.updater;
49
+ const last = status?.last;
50
+ if (!status || !last || !FAILED_RESULTS.has(last.result) || failureOf(response, recent))
51
+ return null;
52
+ if (offersOf(status).length === 0)
53
+ return null;
54
+ return { version: last.version, message: last.message };
55
+ }
56
+ /** What the popover shows: the button's state, but a running check does not hide the result before it. */
57
+ export function panelState(response, pending, recent = null) {
58
+ if (pending)
59
+ return "installing";
60
+ if (!response)
61
+ return "loading";
62
+ const status = response.updater;
63
+ if (!response.reachable || !status)
64
+ return "unreachable";
65
+ if (status.installing)
66
+ return "installing";
67
+ if (failureOf(response, recent))
68
+ return "failed";
69
+ if (status.available)
70
+ return "available";
71
+ if (status.attention)
72
+ return "attention";
73
+ // Mode off still shows what is new (without installing); "off" only when nothing is.
74
+ return status.mode === "off" ? "off" : "current";
75
+ }
76
+ /** The state of the button: the first that applies. */
77
+ export function buttonState(response, options) {
78
+ const shown = panelState(response, options.pending, options.recent ?? null);
79
+ if (shown === "loading" || shown === "unreachable" || shown === "installing")
80
+ return shown;
81
+ return options.checking || response?.updater?.checking ? "checking" : shown;
82
+ }
83
+ /**
84
+ * Whether a click opens the popover (else it checks): there is something to
85
+ * show. A followed installation always has one, for its progress and the
86
+ * warning after 15 minutes, also while the app or its update service restarts.
87
+ */
88
+ export function hasPanel(state, response, pending = null) {
89
+ if (pending)
90
+ return true;
91
+ if (!response?.updater)
92
+ return false;
93
+ return state === "available" || state === "attention" || state === "failed" || state === "installing";
94
+ }
95
+ /** Whether an Update can be installed from the popover: not in mode off, and an attention offer only while the channel is not locked. */
96
+ export function canInstall(status, update) {
97
+ if (status.mode === "off")
98
+ return false;
99
+ return update !== status.attention || status.channelLocked === null;
100
+ }
101
+ /**
102
+ * An attempt to install `version`, remembered before the request; unconfirmed
103
+ * until the updater accepts it. `before`: the newest status, whose `last` is
104
+ * the earlier result.
105
+ */
106
+ export function startAttempt(version, before, now) {
107
+ return {
108
+ version,
109
+ from: before?.app.version ?? null,
110
+ startedAt: now,
111
+ confirmed: false,
112
+ earlier: before?.updater?.last ?? null,
113
+ installStartedAt: null,
114
+ answeredAt: null,
115
+ reason: null,
116
+ lastError: null,
117
+ unreported: false,
118
+ outage: false,
119
+ };
120
+ }
121
+ /** Follows an installation that a status reports (another administrator's, an automatic one, or a retry). */
122
+ export function adoptInstall(installing, response, now) {
123
+ return {
124
+ ...startAttempt(installing.version, response, now),
125
+ confirmed: true,
126
+ installStartedAt: installing.startedAt,
127
+ };
128
+ }
129
+ /** What "Stop waiting" leaves alone from then on: the identity stored on the attempt, not the latest status. */
130
+ export function ignoreInstall(pending) {
131
+ return {
132
+ version: pending.version,
133
+ installStartedAt: pending.installStartedAt,
134
+ startedAt: pending.startedAt,
135
+ };
136
+ }
137
+ /** The updater writes whole seconds: an epoch time of this browser cut to its second. */
138
+ function wholeSecond(ms) {
139
+ return Math.floor(ms / 1000) * 1000;
140
+ }
141
+ /** Whether a reported installation is the one the administrator stopped waiting for. */
142
+ export function isIgnored(installing, ignored) {
143
+ if (!ignored || installing.version !== ignored.version)
144
+ return false;
145
+ if (ignored.installStartedAt !== null)
146
+ return installing.startedAt === ignored.installStartedAt;
147
+ return Date.parse(installing.startedAt) >= wholeSecond(ignored.startedAt);
148
+ }
149
+ function sameResult(a, b) {
150
+ return a.version === b.version && a.result === b.result && a.finishedAt === b.finishedAt;
151
+ }
152
+ /**
153
+ * The result of the followed installation in `last` (fresh): its version, not
154
+ * the earlier result, and finished at or after the installation started: at
155
+ * `installing.startedAt` when a status reported it (the updater's clock),
156
+ * else at the attempt's start cut to whole seconds.
157
+ */
158
+ function freshLast(pending, status) {
159
+ const last = status?.last;
160
+ if (!last || last.version !== pending.version)
161
+ return null;
162
+ if (pending.earlier && sameResult(last, pending.earlier))
163
+ return null;
164
+ const since = pending.installStartedAt !== null ? Date.parse(pending.installStartedAt) : wholeSecond(pending.startedAt);
165
+ return Date.parse(last.finishedAt) >= since ? last : null;
166
+ }
167
+ /**
168
+ * Takes a fresh status into the followed installation: confirms an attempt
169
+ * the status reports (running or finished), and adopts a reported
170
+ * installation when this tab follows none, or in place of an unconfirmed
171
+ * attempt (another administrator or an automatic install was faster).
172
+ * A reachable status that reports neither marks an unconfirmed attempt as
173
+ * unreported, but only one requested after the install request answered
174
+ * (`sentAt`, epoch ms): an earlier one cannot know of it. An answer without
175
+ * status (`reachable: false`) is an observed outage. `ignored`: an
176
+ * installation this tab stopped waiting for.
177
+ */
178
+ export function followStatus(pending, response, now, ignored = null, sentAt = now) {
179
+ const status = response.updater;
180
+ const installing = status?.installing ?? null;
181
+ const adoptable = installing !== null && !isIgnored(installing, ignored);
182
+ if (!pending)
183
+ return adoptable ? adoptInstall(installing, response, now) : null;
184
+ if (!status)
185
+ return noteOutage(pending, response.error);
186
+ if (installing && installing.version === pending.version) {
187
+ if (pending.confirmed && pending.installStartedAt === installing.startedAt)
188
+ return pending;
189
+ return { ...pending, confirmed: true, installStartedAt: installing.startedAt };
190
+ }
191
+ if (pending.confirmed)
192
+ return pending;
193
+ if (adoptable)
194
+ return adoptInstall(installing, response, now);
195
+ if (freshLast(pending, status))
196
+ return { ...pending, confirmed: true };
197
+ const afterAnswer = pending.answeredAt !== null && sentAt >= pending.answeredAt;
198
+ return pending.unreported || !afterAnswer ? pending : { ...pending, unreported: true };
199
+ }
200
+ /**
201
+ * A status request failed (network error, timeout, 5xx) or the update service
202
+ * did not answer (`reachable: false`) while following: an observed outage,
203
+ * with its error for the attempt's reconciliation.
204
+ */
205
+ export function noteOutage(pending, error) {
206
+ const lastError = error ?? pending.lastError;
207
+ return pending.outage && pending.lastError === lastError
208
+ ? pending
209
+ : { ...pending, outage: true, lastError };
210
+ }
211
+ /**
212
+ * What an answer to the install request does with the attempt: accepted
213
+ * confirms it (also without a readable status); a refusal forgets it (and
214
+ * returns the error), unless its status reports a running installation, which
215
+ * is followed instead; an unclear answer keeps it, to reconcile with the
216
+ * status until `reconcileDeadline`.
217
+ */
218
+ export function answerInstall(attempt, answer, now) {
219
+ const answered = { ...attempt, answeredAt: now };
220
+ if (answer.kind === "accepted") {
221
+ const followed = answer.response?.updater ? followStatus(answered, answer.response, now) : answered;
222
+ return { pending: { ...(followed ?? answered), confirmed: true }, error: null };
223
+ }
224
+ if (answer.kind === "unclear") {
225
+ return {
226
+ pending: { ...answered, reason: answer.error, lastError: answer.error ?? attempt.lastError },
227
+ error: null,
228
+ };
229
+ }
230
+ const installing = answer.response?.updater?.installing;
231
+ if (!answer.response || !installing)
232
+ return { pending: null, error: answer.error };
233
+ return { pending: followStatus({ ...answered, confirmed: false }, answer.response, now), error: null };
234
+ }
235
+ /**
236
+ * Where the followed installation stands after `response`, a status answer
237
+ * received after it started (undefined: none, or the app did not answer).
238
+ * The first that applies:
239
+ * 1. `last` reports it failed or rolled back: failed.
240
+ * 2. The updater still installs it: waiting, also when the app already runs
241
+ * the version (on a server it may still roll back).
242
+ * 3. `last` reports it installed: done.
243
+ * 4. `last` reports the platform accepted it: done once the app runs the
244
+ * version, or, where the app's version cannot tell (none, or a digest),
245
+ * once it changed or the app answered again after an outage.
246
+ * 5. Nothing reports it any more and the app runs the version: done.
247
+ * Otherwise it turns slow after 15 minutes. (An unconfirmed attempt ends
248
+ * earlier, at `reconcileDeadline`, on a timer of its own.)
249
+ */
250
+ export function installOutcome(pending, response, now) {
251
+ const status = response?.updater ?? null;
252
+ if (response && status) {
253
+ const last = freshLast(pending, status);
254
+ const version = response.app.version;
255
+ if (last && FAILED_RESULTS.has(last.result))
256
+ return "failed";
257
+ if (status.installing?.version !== pending.version) {
258
+ if (last?.result === "installed")
259
+ return "done";
260
+ if (last?.result === "accepted") {
261
+ if (version === pending.version)
262
+ return "done";
263
+ const comparable = version !== null && !pending.version.startsWith("sha256:");
264
+ const changed = version !== null && pending.from !== null && version !== pending.from;
265
+ if (!comparable && (pending.outage || changed))
266
+ return "done";
267
+ }
268
+ else if (version === pending.version)
269
+ return "done";
270
+ }
271
+ }
272
+ return now - pending.startedAt > SLOW_AFTER_MS ? "slow" : "waiting";
273
+ }
274
+ /** How long a status request may take. */
275
+ export const STATUS_TIMEOUT_MS = 10_000;
276
+ /**
277
+ * The timeout of a status request: never past the reconciliation deadline
278
+ * (epoch ms) of an unconfirmed attempt; a request after it is a normal one.
279
+ */
280
+ export function statusTimeout(deadline, now) {
281
+ const left = deadline === null ? STATUS_TIMEOUT_MS : deadline - now;
282
+ return left > 0 ? Math.min(STATUS_TIMEOUT_MS, left) : STATUS_TIMEOUT_MS;
283
+ }
284
+ /**
285
+ * When the wait for an unconfirmed attempt ends (epoch ms): 60 s after it
286
+ * started, but not before 10 s after this page started (`pageStart`), so that
287
+ * a page loaded after the deadline (after a sign-in) asks the update service
288
+ * once first; null: confirmed, no deadline.
289
+ */
290
+ export function reconcileDeadline(pending, pageStart) {
291
+ if (!pending || pending.confirmed)
292
+ return null;
293
+ return Math.max(pending.startedAt + RECONCILE_MS, pageStart + PAGE_GRACE_MS);
294
+ }
295
+ /**
296
+ * Why an unconfirmed attempt ended at its deadline: it did not start, with
297
+ * the reason of the unclear answer, when a reachable status answered without
298
+ * it; otherwise it could not be confirmed, with the latest error.
299
+ */
300
+ export function unconfirmedEnd(pending) {
301
+ return pending.unreported
302
+ ? { message: "notStarted", detail: pending.reason ?? pending.lastError }
303
+ : { message: "notConfirmed", detail: pending.lastError ?? pending.reason };
304
+ }
305
+ /**
306
+ * Where a tab keeps its followed installation and the one it stopped waiting
307
+ * for (sessionStorage, so a reload during the restart keeps following).
308
+ * `prefix`: one per app, e.g. "meldgrove.updates.handbook".
309
+ */
310
+ export function installStorage(prefix) {
311
+ const pendingKey = `${prefix}.install`;
312
+ const ignoredKey = `${prefix}.ignored`;
313
+ return {
314
+ loadPending() {
315
+ try {
316
+ const value = JSON.parse(sessionStorage.getItem(pendingKey) ?? "null");
317
+ if (!value || typeof value.version !== "string" || typeof value.startedAt !== "number")
318
+ return null;
319
+ return { ...startAttempt(value.version, undefined, value.startedAt), ...value };
320
+ }
321
+ catch {
322
+ return null;
323
+ }
324
+ },
325
+ savePending(pending) {
326
+ try {
327
+ if (pending)
328
+ sessionStorage.setItem(pendingKey, JSON.stringify(pending));
329
+ else
330
+ sessionStorage.removeItem(pendingKey);
331
+ }
332
+ catch {
333
+ // Without storage, a reload during the restart stops waiting; nothing else breaks.
334
+ }
335
+ },
336
+ loadIgnored() {
337
+ try {
338
+ const value = JSON.parse(sessionStorage.getItem(ignoredKey) ?? "null");
339
+ if (!value || typeof value.version !== "string" || typeof value.startedAt !== "number")
340
+ return null;
341
+ return {
342
+ version: value.version,
343
+ installStartedAt: value.installStartedAt ?? null,
344
+ startedAt: value.startedAt,
345
+ };
346
+ }
347
+ catch {
348
+ return null;
349
+ }
350
+ },
351
+ saveIgnored(ignored) {
352
+ try {
353
+ if (ignored)
354
+ sessionStorage.setItem(ignoredKey, JSON.stringify(ignored));
355
+ else
356
+ sessionStorage.removeItem(ignoredKey);
357
+ }
358
+ catch {
359
+ // Without storage, a reload follows that installation again.
360
+ }
361
+ },
362
+ };
363
+ }
364
+ /** "3d", "12h", "30m", "45s" or seconds ("3600") as a count and unit; null for none or unknown. */
365
+ export function cooldownParts(cooldown) {
366
+ const match = cooldown?.trim().match(/^(\d+)\s*([dhms]?)$/);
367
+ if (!match)
368
+ return null;
369
+ const count = Number(match[1]);
370
+ if (count === 0)
371
+ return null;
372
+ if (match[2] === "d")
373
+ return { unit: "days", count };
374
+ if (match[2] === "h")
375
+ return { unit: "hours", count };
376
+ if (match[2] === "m")
377
+ return { unit: "minutes", count };
378
+ if (match[2] === "s" || count % 60 !== 0)
379
+ return { unit: "seconds", count };
380
+ if (count % 86_400 === 0)
381
+ return { unit: "days", count: count / 86_400 };
382
+ if (count % 3600 === 0)
383
+ return { unit: "hours", count: count / 3600 };
384
+ return { unit: "minutes", count: count / 60 };
385
+ }
386
+ /** "02:00-05:00" as its start and end. */
387
+ export function windowParts(window) {
388
+ const match = window?.trim().match(/^(\d{1,2}:\d{2})\s*-\s*(\d{1,2}:\d{2})$/);
389
+ return match ? { start: match[1], end: match[2] } : null;
390
+ }
391
+ /** How many notes the popover lists, and how many changes it leaves out. */
392
+ export const MAX_NOTES = 8;
393
+ export function noteSummary(update) {
394
+ const notes = update.notes.slice(0, MAX_NOTES);
395
+ return { notes, more: Math.max(update.changes, update.notes.length) - notes.length };
396
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * How the update button reaches the app's four update routes. Apps with their
3
+ * own API helper pass a transport of their own; `fetchTransport` covers the
4
+ * usual case.
5
+ */
6
+ export type UpdatesAction = "status" | "check" | "install" | "channel";
7
+ export type UpdatesRequest = {
8
+ action: UpdatesAction;
9
+ /** JSON body of a POST (`check`, `install`, `channel`); none for `status`. */
10
+ body?: unknown;
11
+ signal?: AbortSignal;
12
+ };
13
+ /** The status code and the JSON body of an answer (null: none, or not JSON). */
14
+ export type UpdatesAnswer = {
15
+ status: number;
16
+ data: unknown;
17
+ };
18
+ export type UpdatesTransport = {
19
+ /**
20
+ * Sends one request. Resolves with every answer the route gave, errors
21
+ * included. Throws `SignedOutError` when a sign-in page answered in place
22
+ * of the route (a redirect, or a web page instead of JSON), and whatever a
23
+ * failed request throws (network errors, aborts).
24
+ */
25
+ request(request: UpdatesRequest): Promise<UpdatesAnswer>;
26
+ };
27
+ /** A sign-in page answered in place of the route: the session ended. */
28
+ export declare class SignedOutError extends Error {
29
+ constructor(message?: string);
30
+ }
31
+ export type FetchTransportOptions = {
32
+ /**
33
+ * The status route; the others are `<url>/check`, `<url>/install` and
34
+ * `<url>/channel`. Example: "/api/admin/updates", or "/admin/updates/" for
35
+ * Django (a trailing slash carries over to every route).
36
+ */
37
+ url: string;
38
+ /** Extra headers of every request, e.g. a CSRF token. */
39
+ headers?: () => Record<string, string>;
40
+ };
41
+ /** The URL of an action: `url` for status, else `url/<action>`, keeping a trailing slash. */
42
+ export declare function actionUrl(url: string, action: UpdatesAction): string;
43
+ /**
44
+ * Calls the routes with `fetch` on the page's own origin and session, without
45
+ * following redirects (a redirect means a sign-in page). A 202 keeps its status
46
+ * when its body fails; a 200 that is a web page is a sign-in page.
47
+ */
48
+ export declare function fetchTransport(options: FetchTransportOptions): UpdatesTransport;
49
+ /** The value of a cookie of the page, e.g. Django's `csrftoken`; null when it is not set. */
50
+ export declare function readCookie(name: string): string | null;
@@ -0,0 +1,76 @@
1
+ /**
2
+ * How the update button reaches the app's four update routes. Apps with their
3
+ * own API helper pass a transport of their own; `fetchTransport` covers the
4
+ * usual case.
5
+ */
6
+ /** A sign-in page answered in place of the route: the session ended. */
7
+ export class SignedOutError extends Error {
8
+ constructor(message = "Sign in again to continue.") {
9
+ super(message);
10
+ this.name = "SignedOutError";
11
+ }
12
+ }
13
+ /** The URL of an action: `url` for status, else `url/<action>`, keeping a trailing slash. */
14
+ export function actionUrl(url, action) {
15
+ if (action === "status")
16
+ return url;
17
+ const slash = url.endsWith("/");
18
+ return `${slash ? url.slice(0, -1) : url}/${action}${slash ? "/" : ""}`;
19
+ }
20
+ async function readJson(response) {
21
+ const text = await response.text();
22
+ try {
23
+ return { text, data: text ? JSON.parse(text) : null };
24
+ }
25
+ catch {
26
+ return { text, data: null };
27
+ }
28
+ }
29
+ /**
30
+ * Calls the routes with `fetch` on the page's own origin and session, without
31
+ * following redirects (a redirect means a sign-in page). A 202 keeps its status
32
+ * when its body fails; a 200 that is a web page is a sign-in page.
33
+ */
34
+ export function fetchTransport(options) {
35
+ return {
36
+ async request({ action, body, signal }) {
37
+ const response = await fetch(actionUrl(options.url, action), {
38
+ method: action === "status" ? "GET" : "POST",
39
+ credentials: "same-origin",
40
+ headers: {
41
+ accept: "application/json",
42
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
43
+ ...options.headers?.(),
44
+ },
45
+ body: body === undefined ? undefined : JSON.stringify(body),
46
+ redirect: "manual",
47
+ signal,
48
+ });
49
+ if (response.type === "opaqueredirect" ||
50
+ response.redirected ||
51
+ (response.status >= 300 && response.status < 400)) {
52
+ throw new SignedOutError();
53
+ }
54
+ // A 202 took the request, whatever happens to its body; any other answer whose body fails
55
+ // throws that error (a timeout stays a timeout).
56
+ const { text, data } = await readJson(response).catch((error) => {
57
+ if (response.status !== 202)
58
+ throw error;
59
+ return { text: "", data: null };
60
+ });
61
+ const html = /html/i.test(response.headers.get("content-type") ?? "") || /^\s*</.test(text);
62
+ if (response.status === 200 && data === null && html)
63
+ throw new SignedOutError();
64
+ return { status: response.status, data };
65
+ },
66
+ };
67
+ }
68
+ /** The value of a cookie of the page, e.g. Django's `csrftoken`; null when it is not set. */
69
+ export function readCookie(name) {
70
+ for (const part of document.cookie.split(";")) {
71
+ const [key, ...value] = part.trim().split("=");
72
+ if (key === name)
73
+ return decodeURIComponent(value.join("="));
74
+ }
75
+ return null;
76
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * What an app's update routes answer: the status of the Meldgrove Updater
3
+ * (the `updater` service of the app's compose.yaml), passed on to the app's
4
+ * admins. The contract is the updater's README
5
+ * (https://github.com/meldgrove/updater#the-apps-update-button).
6
+ */
7
+ export declare const UPDATE_CHANNELS: readonly ["stable", "preview"];
8
+ export type UpdateChannel = (typeof UPDATE_CHANNELS)[number];
9
+ /** A release (`0.2.1`), a preview (`0.2.1-preview.3`) or an image without version (`sha256:<12 hex>`). */
10
+ export declare const UPDATE_VERSION_PATTERN: RegExp;
11
+ export type Update = {
12
+ version: string;
13
+ preview: boolean;
14
+ publishedAt: string | null;
15
+ /** Release notes, or the compare view of a preview. */
16
+ url: string | null;
17
+ /** Change titles, newest release first, at most 15. */
18
+ notes: string[];
19
+ /** All changes, when more than `notes`. */
20
+ changes: number;
21
+ /** When it installs automatically; null: not automatically. */
22
+ installsAt: string | null;
23
+ /** Message of an earlier failed installation of this version. */
24
+ failed: string | null;
25
+ };
26
+ export type InstallStage = "requested" | "pulling" | "starting" | "rolling-back" | "deploying";
27
+ export type InstallResult = "installed" | "failed" | "rolled-back" | "accepted";
28
+ export type UpdaterStatus = {
29
+ /** Version of the updater, e.g. "0.2.0". */
30
+ updater: string;
31
+ mode: "host" | "platform" | "off";
32
+ channel: UpdateChannel;
33
+ /** Why admins cannot switch the channel; null: they can. */
34
+ channelLocked: string | null;
35
+ /** The installed version; null: unknown. */
36
+ installed: string | null;
37
+ available: Update | null;
38
+ /** A release of a newer series that needs upgrade steps (Stable only). */
39
+ attention: Update | null;
40
+ installing: {
41
+ version: string;
42
+ startedAt: string;
43
+ manual: boolean;
44
+ stage: InstallStage;
45
+ } | null;
46
+ last: {
47
+ version: string;
48
+ result: InstallResult;
49
+ message: string | null;
50
+ finishedAt: string;
51
+ } | null;
52
+ checking: boolean;
53
+ /** The last successful check. */
54
+ checkedAt: string | null;
55
+ /** The last check's error. */
56
+ error: string | null;
57
+ /** False when the updater installs nothing (mode off). */
58
+ automatic: boolean;
59
+ /** How long a release must be out before it installs, e.g. "3d"; null: no wait. */
60
+ cooldown: string | null;
61
+ /** Automatic installs only between these times of day, e.g. "02:00-05:00". */
62
+ window: string | null;
63
+ timezone: string;
64
+ };
65
+ export type UpdatesResponse = {
66
+ /** The running app; `version` is null for images built from source and in development. */
67
+ app: {
68
+ version: string | null;
69
+ };
70
+ /** False: no updater answers at UPDATER_URL, or UPDATER_URL is empty. */
71
+ reachable: boolean;
72
+ updater: UpdaterStatus | null;
73
+ /** Why the updater refused or could not be reached. */
74
+ error: string | null;
75
+ };
76
+ /** The answer of an update route when it has the expected shape; null otherwise. */
77
+ export declare function parseUpdatesResponse(data: unknown): UpdatesResponse | null;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * What an app's update routes answer: the status of the Meldgrove Updater
3
+ * (the `updater` service of the app's compose.yaml), passed on to the app's
4
+ * admins. The contract is the updater's README
5
+ * (https://github.com/meldgrove/updater#the-apps-update-button).
6
+ */
7
+ export const UPDATE_CHANNELS = ["stable", "preview"];
8
+ /** A release (`0.2.1`), a preview (`0.2.1-preview.3`) or an image without version (`sha256:<12 hex>`). */
9
+ export const UPDATE_VERSION_PATTERN = /^(?:[0-9]+\.[0-9]+\.[0-9]+(?:-preview\.[0-9]+)?|sha256:[0-9a-f]{12})$/;
10
+ const isString = (value) => typeof value === "string";
11
+ const isBoolean = (value) => typeof value === "boolean";
12
+ const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
13
+ const nullable = (check) => (value) => value === null || check(value);
14
+ const oneOf = (...values) => (value) => typeof value === "string" && values.includes(value);
15
+ const object = (shape) => (value) => typeof value === "object" &&
16
+ value !== null &&
17
+ !Array.isArray(value) &&
18
+ Object.entries(shape).every(([key, check]) => check(value[key]));
19
+ const isUpdate = object({
20
+ version: isString,
21
+ preview: isBoolean,
22
+ publishedAt: nullable(isString),
23
+ url: nullable(isString),
24
+ notes: (value) => Array.isArray(value) && value.every(isString),
25
+ changes: isNumber,
26
+ installsAt: nullable(isString),
27
+ failed: nullable(isString),
28
+ });
29
+ // Values a newer updater may add (a mode, a stage, a result) keep the answer valid: the
30
+ // views show what they know and ignore the rest.
31
+ const isStatus = object({
32
+ updater: isString,
33
+ mode: isString,
34
+ channel: oneOf(...UPDATE_CHANNELS),
35
+ channelLocked: nullable(isString),
36
+ installed: nullable(isString),
37
+ available: nullable(isUpdate),
38
+ attention: nullable(isUpdate),
39
+ installing: nullable(object({
40
+ version: isString,
41
+ startedAt: isString,
42
+ manual: isBoolean,
43
+ stage: isString,
44
+ })),
45
+ last: nullable(object({
46
+ version: isString,
47
+ result: isString,
48
+ message: nullable(isString),
49
+ finishedAt: isString,
50
+ })),
51
+ checking: isBoolean,
52
+ checkedAt: nullable(isString),
53
+ error: nullable(isString),
54
+ automatic: isBoolean,
55
+ cooldown: nullable(isString),
56
+ window: nullable(isString),
57
+ timezone: isString,
58
+ });
59
+ const isResponse = object({
60
+ app: object({ version: nullable(isString) }),
61
+ reachable: isBoolean,
62
+ updater: nullable(isStatus),
63
+ error: nullable(isString),
64
+ });
65
+ /** The answer of an update route when it has the expected shape; null otherwise. */
66
+ export function parseUpdatesResponse(data) {
67
+ return isResponse(data) ? data : null;
68
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The update button for the app's top bar (render it for admins only): shows
3
+ * whether an update is available, checks on click, installs on request,
4
+ * follows the installation through the restart and reloads the page when the
5
+ * new version answers. Needs `UpdatesProvider` above it.
6
+ */
7
+ export declare function UpdateButton({ className }: {
8
+ className?: string;
9
+ }): import("react").JSX.Element;