@almateam/app-sdk 0.9.0 → 0.11.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/README.md +174 -45
- package/app.d.ts +297 -0
- package/cli.js +2 -2
- package/files.d.ts +25 -0
- package/generated/apiTypes.d.ts +31 -0
- package/index.d.ts +85 -11
- package/index.js +591 -238
- package/navigation.d.ts +44 -2
- package/package.json +1 -1
- package/siteRuntime.d.ts +42 -14
- package/site.d.ts +0 -267
package/index.js
CHANGED
|
@@ -32,6 +32,19 @@ class AppCallError extends Error {
|
|
|
32
32
|
}
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
// src/files.ts
|
|
36
|
+
var APP_FILE_QUESTION = "getAppFile";
|
|
37
|
+
var FILE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
38
|
+
function isAppFileName(name) {
|
|
39
|
+
return typeof name === "string" && FILE_NAME.test(name) && !name.includes("..");
|
|
40
|
+
}
|
|
41
|
+
function appFileNameOf(address) {
|
|
42
|
+
if (!address.startsWith("/_files/"))
|
|
43
|
+
return null;
|
|
44
|
+
const name = address.slice("/_files/".length);
|
|
45
|
+
return isAppFileName(name) ? name : null;
|
|
46
|
+
}
|
|
47
|
+
|
|
35
48
|
// src/navigation.ts
|
|
36
49
|
function applicationPath(value) {
|
|
37
50
|
if (typeof value !== "string" || value.length > 2048 || !value.startsWith("/") || value.startsWith("//") || /[\\?#]/.test(value) || [...value].some((character) => character.charCodeAt(0) < 32))
|
|
@@ -39,6 +52,22 @@ function applicationPath(value) {
|
|
|
39
52
|
const parsed = new URL(value, "https://application.invalid");
|
|
40
53
|
return parsed.origin === "https://application.invalid" && parsed.pathname === value ? value : null;
|
|
41
54
|
}
|
|
55
|
+
var OPEN_URL_MESSAGE = "alma:open-url";
|
|
56
|
+
var OPEN_FILE_MESSAGE = "alma:open-file";
|
|
57
|
+
var OPEN_FILE_TEXT_LIMIT = 5000000;
|
|
58
|
+
var OUTSIDE_PROTOCOLS = new Set(["https:", "http:", "mailto:", "tel:"]);
|
|
59
|
+
function outsideUrl(value) {
|
|
60
|
+
if (typeof value !== "string" || value.length > 2048)
|
|
61
|
+
return null;
|
|
62
|
+
if (!URL.canParse(value))
|
|
63
|
+
return null;
|
|
64
|
+
const url = new URL(value);
|
|
65
|
+
if (!OUTSIDE_PROTOCOLS.has(url.protocol))
|
|
66
|
+
return null;
|
|
67
|
+
if (url.username !== "" || url.password !== "")
|
|
68
|
+
return null;
|
|
69
|
+
return url.href;
|
|
70
|
+
}
|
|
42
71
|
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
43
72
|
function parseAppHostEvent(told) {
|
|
44
73
|
if (typeof told !== "object" || told === null)
|
|
@@ -115,11 +144,37 @@ function hostNavigation() {
|
|
|
115
144
|
listeners.add(listener);
|
|
116
145
|
return () => listeners.delete(listener);
|
|
117
146
|
},
|
|
118
|
-
navigate: (next) => {
|
|
147
|
+
navigate: (next, options = {}) => {
|
|
119
148
|
if (applicationPath(next) === null)
|
|
120
149
|
throw new Error("App navigation requires a relative path");
|
|
121
150
|
reported += 1;
|
|
122
|
-
line.post({
|
|
151
|
+
line.post({
|
|
152
|
+
type: "alma:navigate",
|
|
153
|
+
path: next,
|
|
154
|
+
seq: reported,
|
|
155
|
+
...options.replace ? { replace: true } : {}
|
|
156
|
+
});
|
|
157
|
+
},
|
|
158
|
+
openUrl: (url) => {
|
|
159
|
+
const outside = outsideUrl(url);
|
|
160
|
+
if (outside === null)
|
|
161
|
+
throw new Error("Only an http, https, mail or phone address opens");
|
|
162
|
+
line.post({ type: OPEN_URL_MESSAGE, url: outside });
|
|
163
|
+
},
|
|
164
|
+
openFile: (file) => {
|
|
165
|
+
if ("text" in file) {
|
|
166
|
+
if (file.text.length > OPEN_FILE_TEXT_LIMIT)
|
|
167
|
+
throw new Error("This file is too long to save from Alma");
|
|
168
|
+
line.post({
|
|
169
|
+
type: OPEN_FILE_MESSAGE,
|
|
170
|
+
name: file.name,
|
|
171
|
+
text: file.text
|
|
172
|
+
});
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
if (!isAppFileName(file.name))
|
|
176
|
+
throw new Error(`"${file.name}" is not a file name`);
|
|
177
|
+
line.post({ type: OPEN_FILE_MESSAGE, name: file.name });
|
|
123
178
|
},
|
|
124
179
|
openApps: () => line.post({ type: "alma:leave" }),
|
|
125
180
|
openTasks: (taskId) => {
|
|
@@ -137,20 +192,349 @@ function hostNavigation() {
|
|
|
137
192
|
}
|
|
138
193
|
};
|
|
139
194
|
}
|
|
140
|
-
|
|
195
|
+
|
|
196
|
+
// src/siteRuntime.ts
|
|
197
|
+
function isOwnEntry(value) {
|
|
198
|
+
if (typeof value !== "object" || value === null)
|
|
199
|
+
return false;
|
|
200
|
+
const entry = value;
|
|
201
|
+
return typeof entry["type"] === "string" && typeof entry["record"] === "object" && entry["record"] !== null;
|
|
202
|
+
}
|
|
203
|
+
var PUBLIC_RECORD_SHAPE = [
|
|
204
|
+
"id",
|
|
205
|
+
"name",
|
|
206
|
+
"type.key",
|
|
207
|
+
"values",
|
|
208
|
+
"created_at"
|
|
209
|
+
];
|
|
210
|
+
function asTopicRecord(record, type) {
|
|
211
|
+
const values = {};
|
|
212
|
+
for (const [key, held] of Object.entries(record.values))
|
|
213
|
+
values[key] = held.map((value) => ({ ...value, ref: null }));
|
|
214
|
+
return {
|
|
215
|
+
id: record.id,
|
|
216
|
+
name: record.name ?? "",
|
|
217
|
+
slug: "",
|
|
218
|
+
icon: null,
|
|
219
|
+
status: "active",
|
|
220
|
+
type: { key: type, name: type, icon: null },
|
|
221
|
+
values,
|
|
222
|
+
revisions: {},
|
|
223
|
+
unverified_value_count: 0,
|
|
224
|
+
can_edit: false,
|
|
225
|
+
created_at: record.created_at,
|
|
226
|
+
updated_at: record.created_at
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
function asAppTopicRecord(record) {
|
|
230
|
+
return {
|
|
231
|
+
topic: { id: record.id, name: record.name ?? "" },
|
|
232
|
+
record: {
|
|
233
|
+
template: null,
|
|
234
|
+
sections: [],
|
|
235
|
+
updates: [],
|
|
236
|
+
updating: false,
|
|
237
|
+
viewer_can_edit: false
|
|
238
|
+
},
|
|
239
|
+
facts: Object.entries(record.values).flatMap(([key, held]) => held.map((value, at) => ({
|
|
240
|
+
id: `${record.id}:${key}:${at}`,
|
|
241
|
+
field_key: key,
|
|
242
|
+
value: { ...value, ref: null },
|
|
243
|
+
verified_at: null
|
|
244
|
+
}))),
|
|
245
|
+
revisions: {}
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
class SiteRefusalError extends AppCallError {
|
|
250
|
+
retryAfterSeconds;
|
|
251
|
+
constructor(message, code, retryAfterSeconds) {
|
|
252
|
+
super(message, { code });
|
|
253
|
+
this.name = "SiteRefusalError";
|
|
254
|
+
this.retryAfterSeconds = retryAfterSeconds;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
function isSiteRefusal(error) {
|
|
258
|
+
return error instanceof SiteRefusalError;
|
|
259
|
+
}
|
|
260
|
+
var PUBLISHED_SITE_ATTRIBUTE = "data-alma-site";
|
|
261
|
+
function publishedSite() {
|
|
262
|
+
if (typeof document === "undefined")
|
|
263
|
+
return null;
|
|
264
|
+
return document.documentElement.hasAttribute(PUBLISHED_SITE_ATTRIBUTE) ? { origin: location.origin } : null;
|
|
265
|
+
}
|
|
266
|
+
function appPlace() {
|
|
267
|
+
return publishedSite() ? "public" : "frame";
|
|
268
|
+
}
|
|
269
|
+
var RESULT_TOKEN = /^[A-Za-z0-9_-]{16,512}$/;
|
|
270
|
+
var DOOR_PAGE_MAX = 50;
|
|
271
|
+
function readResultToken(hash = typeof location === "undefined" ? "" : location.hash) {
|
|
272
|
+
const fragment = hash.startsWith("#") ? hash.slice(1) : hash;
|
|
273
|
+
const token = fragment.includes("=") ? new URLSearchParams(fragment).get("token") : fragment;
|
|
274
|
+
return token && RESULT_TOKEN.test(token) ? token : null;
|
|
275
|
+
}
|
|
276
|
+
var LEAVES_ALMA = "A site published to the web has no Alma around it to open.";
|
|
277
|
+
function siteNavigation() {
|
|
278
|
+
const listeners = new Set;
|
|
279
|
+
const current = () => applicationPath(location.pathname) ?? "/";
|
|
280
|
+
window.addEventListener("popstate", () => {
|
|
281
|
+
const path = current();
|
|
282
|
+
for (const listener of listeners)
|
|
283
|
+
listener(path, null);
|
|
284
|
+
});
|
|
285
|
+
return {
|
|
286
|
+
getPath: current,
|
|
287
|
+
subscribe: (listener) => {
|
|
288
|
+
listeners.add(listener);
|
|
289
|
+
return () => listeners.delete(listener);
|
|
290
|
+
},
|
|
291
|
+
navigate: (path, options = {}) => {
|
|
292
|
+
if (applicationPath(path) === null)
|
|
293
|
+
throw new Error("Site navigation requires a path on this site");
|
|
294
|
+
const hash = options.hash ?? "";
|
|
295
|
+
if (/[\s#]/.test(hash))
|
|
296
|
+
throw new Error("A fragment holds no space or #");
|
|
297
|
+
const url = hash ? `${path}#${hash}` : path;
|
|
298
|
+
if (options.replace)
|
|
299
|
+
history.replaceState(null, "", url);
|
|
300
|
+
else
|
|
301
|
+
history.pushState(null, "", url);
|
|
302
|
+
for (const listener of listeners)
|
|
303
|
+
listener(path, "latest");
|
|
304
|
+
},
|
|
305
|
+
openUrl: (url) => {
|
|
306
|
+
const outside = outsideUrl(url);
|
|
307
|
+
if (outside === null)
|
|
308
|
+
throw new Error("Only an http, https, mail or phone address opens");
|
|
309
|
+
window.open(outside, "_blank", "noopener,noreferrer");
|
|
310
|
+
},
|
|
311
|
+
openFile: (file) => {
|
|
312
|
+
if ("address" in file) {
|
|
313
|
+
if (applicationPath(file.address) === null)
|
|
314
|
+
throw new Error("A declared file is opened by its address");
|
|
315
|
+
window.open(file.address, "_blank", "noopener,noreferrer");
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
if (!isAppFileName(file.name))
|
|
319
|
+
throw new Error(`"${file.name}" is not a file name`);
|
|
320
|
+
window.open(`/_files/${file.name}`, "_blank", "noopener,noreferrer");
|
|
321
|
+
},
|
|
322
|
+
openApps: () => {
|
|
323
|
+
throw new Error(LEAVES_ALMA);
|
|
324
|
+
},
|
|
325
|
+
openTasks: () => {
|
|
326
|
+
throw new Error(LEAVES_ALMA);
|
|
327
|
+
},
|
|
328
|
+
openTopic: () => {
|
|
329
|
+
throw new Error(LEAVES_ALMA);
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
var NO_VIEWER = "A site published to the web has no signed-in viewer, so it can only add, list and read the entries its app's public offers, and raise the events it declares.";
|
|
334
|
+
var noViewer = (message = NO_VIEWER) => Promise.reject(new AppCallError(message, { code: "site.no_viewer" }));
|
|
335
|
+
var UNLISTED_QUERY = ["schema", "filter", "sort", "updated_after"];
|
|
336
|
+
function retryAfter(response) {
|
|
337
|
+
const header = response.headers.get("retry-after");
|
|
338
|
+
if (header === null)
|
|
339
|
+
return null;
|
|
340
|
+
const seconds = Number(header);
|
|
341
|
+
if (Number.isFinite(seconds) && seconds >= 0)
|
|
342
|
+
return Math.ceil(seconds);
|
|
343
|
+
const at = Date.parse(header);
|
|
344
|
+
return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - Date.now()) / 1000));
|
|
345
|
+
}
|
|
346
|
+
async function refusal(response) {
|
|
347
|
+
let said = {};
|
|
348
|
+
try {
|
|
349
|
+
said = await response.json();
|
|
350
|
+
} catch {}
|
|
351
|
+
const message = typeof said.error === "string" ? said.error : `The site refused the request (${response.status}).`;
|
|
352
|
+
const code = typeof said.code === "string" ? said.code : undefined;
|
|
353
|
+
if (code === "visitor.rate_limited" || code === "site.paused")
|
|
354
|
+
return new SiteRefusalError(message, code, retryAfter(response));
|
|
355
|
+
return new AppCallError(message, code ? { code } : {});
|
|
356
|
+
}
|
|
357
|
+
var GATEWAY_ERRORS = new Set([502, 503, 504]);
|
|
358
|
+
function siteTransport(options = {}) {
|
|
359
|
+
const base = options.base ?? "";
|
|
360
|
+
const send = options.fetch ?? ((input, init) => fetch(input, init));
|
|
361
|
+
const delays = options.retryDelaysMs ?? [1000, 2000];
|
|
362
|
+
const post = async (path, body) => {
|
|
363
|
+
for (let attempt = 0;; attempt += 1) {
|
|
364
|
+
let response = null;
|
|
365
|
+
try {
|
|
366
|
+
response = await send(`${base}${path}`, {
|
|
367
|
+
method: "POST",
|
|
368
|
+
headers: { "content-type": "application/json" },
|
|
369
|
+
body: JSON.stringify(body)
|
|
370
|
+
});
|
|
371
|
+
} catch (error) {
|
|
372
|
+
if (attempt >= delays.length)
|
|
373
|
+
throw error;
|
|
374
|
+
}
|
|
375
|
+
if (response && !GATEWAY_ERRORS.has(response.status)) {
|
|
376
|
+
if (!response.ok)
|
|
377
|
+
throw await refusal(response);
|
|
378
|
+
return await response.json();
|
|
379
|
+
}
|
|
380
|
+
if (attempt >= delays.length)
|
|
381
|
+
throw await refusal(response);
|
|
382
|
+
await new Promise((resolve) => setTimeout(resolve, delays[attempt]));
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
const read = async (path) => {
|
|
386
|
+
const response = await send(`${base}${path}`, {});
|
|
387
|
+
if (!response.ok)
|
|
388
|
+
throw await refusal(response);
|
|
389
|
+
return await response.json();
|
|
390
|
+
};
|
|
391
|
+
const raise = (request) => {
|
|
392
|
+
const { event, payload } = request.body ?? {};
|
|
393
|
+
return post("/_alma/events", {
|
|
394
|
+
event,
|
|
395
|
+
...payload === undefined ? {} : { payload },
|
|
396
|
+
idempotency_key: request.idempotencyKey ?? crypto.randomUUID()
|
|
397
|
+
});
|
|
398
|
+
};
|
|
399
|
+
const add = async (request) => {
|
|
400
|
+
const body = request.body ?? {};
|
|
401
|
+
const type = body["topic_type_id"];
|
|
402
|
+
if (typeof type !== "string")
|
|
403
|
+
return noViewer("At a published address an entry is added to one of the app's public types, named by its key.");
|
|
404
|
+
const sent = Array.isArray(body["fields"]) ? body["fields"] : [];
|
|
405
|
+
if (sent.some((field) => field["ref_topic_id"] !== undefined))
|
|
406
|
+
return noViewer("A visitor's entry refers to no other record.");
|
|
407
|
+
const name = typeof body["name"] === "string" ? body["name"].trim() : "";
|
|
408
|
+
const fields = name ? { name } : {};
|
|
409
|
+
for (const field of sent)
|
|
410
|
+
fields[String(field["key"])] = String(field["value"]);
|
|
411
|
+
const added = await post("/_alma/records", {
|
|
412
|
+
type,
|
|
413
|
+
fields,
|
|
414
|
+
idempotency_key: request.idempotencyKey ?? crypto.randomUUID()
|
|
415
|
+
});
|
|
416
|
+
const created = {
|
|
417
|
+
id: added.record.id,
|
|
418
|
+
name,
|
|
419
|
+
topic_type_id: null,
|
|
420
|
+
...added.result ? { result: added.result } : {}
|
|
421
|
+
};
|
|
422
|
+
return created;
|
|
423
|
+
};
|
|
424
|
+
const list = async (request) => {
|
|
425
|
+
const query = request.query ?? {};
|
|
426
|
+
const type = query["type"];
|
|
427
|
+
if (typeof type !== "string" || type === "")
|
|
428
|
+
return noViewer("At a published address a list reads one public type's entries: name it with type.");
|
|
429
|
+
if (UNLISTED_QUERY.some((key) => query[key] !== undefined))
|
|
430
|
+
return noViewer("At a published address a list reads a type's entries newest first, by type, cursor and limit only.");
|
|
431
|
+
const search = new URLSearchParams({ type });
|
|
432
|
+
if (typeof query["cursor"] === "string")
|
|
433
|
+
search.set("cursor", query["cursor"]);
|
|
434
|
+
if (typeof query["limit"] === "number")
|
|
435
|
+
search.set("limit", String(Math.min(query["limit"], DOOR_PAGE_MAX)));
|
|
436
|
+
const page = await read(`/_alma/records?${search.toString()}`);
|
|
437
|
+
return {
|
|
438
|
+
data: page["data"].map((record) => asTopicRecord(record, type)),
|
|
439
|
+
meta: {
|
|
440
|
+
next_cursor: page["next_cursor"] ?? null,
|
|
441
|
+
type_id: null
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
};
|
|
445
|
+
const one = async (request) => {
|
|
446
|
+
const id = request.params?.["id"] ?? "";
|
|
447
|
+
const type = request.query?.["type"];
|
|
448
|
+
if (typeof type !== "string" || type === "")
|
|
449
|
+
return noViewer("At a published address an entry is read with its type: getTopicRecord(id, { type }).");
|
|
450
|
+
const search = new URLSearchParams({ type });
|
|
451
|
+
const answer = await read(`/_alma/records/${encodeURIComponent(id)}?${search.toString()}`);
|
|
452
|
+
return asAppTopicRecord(answer["data"]);
|
|
453
|
+
};
|
|
454
|
+
const tellsNothing = () => Promise.resolve({ watching: false, stop: () => {} });
|
|
455
|
+
return {
|
|
456
|
+
place: "public",
|
|
457
|
+
call: (operationId, request = {}) => {
|
|
458
|
+
switch (operationId) {
|
|
459
|
+
case "raiseAppEvent":
|
|
460
|
+
return raise(request);
|
|
461
|
+
case "createTopic":
|
|
462
|
+
return add(request);
|
|
463
|
+
case "listTopics":
|
|
464
|
+
return list(request);
|
|
465
|
+
case "getTopicRecord":
|
|
466
|
+
return one(request);
|
|
467
|
+
default:
|
|
468
|
+
return noViewer();
|
|
469
|
+
}
|
|
470
|
+
},
|
|
471
|
+
viewer: () => Promise.resolve(null),
|
|
472
|
+
shell: () => Promise.resolve(null),
|
|
473
|
+
watch: () => Promise.resolve({ watching: [], stop: () => {} }),
|
|
474
|
+
watchTypes: () => Promise.resolve({ watching: [], stop: () => {} }),
|
|
475
|
+
watchShared: tellsNothing,
|
|
476
|
+
watchPresence: tellsNothing,
|
|
477
|
+
watchBroadcasts: tellsNothing,
|
|
478
|
+
fileUrl: (name) => {
|
|
479
|
+
if (!isAppFileName(name))
|
|
480
|
+
throw new AppCallError(`"${name}" is not a file name.`, {
|
|
481
|
+
code: "file.invalid_name"
|
|
482
|
+
});
|
|
483
|
+
return `${base}/_files/${name}`;
|
|
484
|
+
},
|
|
485
|
+
result: async (token) => {
|
|
486
|
+
let response = await send(`${base}/_alma/results`, {
|
|
487
|
+
method: "POST",
|
|
488
|
+
headers: { "content-type": "application/json" },
|
|
489
|
+
body: JSON.stringify({ token }),
|
|
490
|
+
cache: "no-store"
|
|
491
|
+
});
|
|
492
|
+
if ([403, 404, 405].includes(response.status))
|
|
493
|
+
response = await send(`${base}/_alma/results/${encodeURIComponent(token)}`, { cache: "no-store" });
|
|
494
|
+
if (!response.ok)
|
|
495
|
+
throw await refusal(response);
|
|
496
|
+
const answer = await response.json();
|
|
497
|
+
if (answer["status"] !== "ready")
|
|
498
|
+
return { status: "pending" };
|
|
499
|
+
const record = answer["record"];
|
|
500
|
+
const type = answer["type"];
|
|
501
|
+
if (typeof type === "string" && typeof record === "object" && record)
|
|
502
|
+
return {
|
|
503
|
+
status: "ready",
|
|
504
|
+
result: {
|
|
505
|
+
type,
|
|
506
|
+
record: asTopicRecord(record, type)
|
|
507
|
+
}
|
|
508
|
+
};
|
|
509
|
+
return { status: "ready", result: answer["result"] };
|
|
510
|
+
}
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
// src/app.ts
|
|
141
514
|
var SITE_ORIGIN_TOKEN = "__ALMA_SITE_ORIGIN__";
|
|
142
|
-
var
|
|
515
|
+
var NOT_FOUND_ROUTE_ID = "404";
|
|
516
|
+
var AUDIENCE_OF_PLACE = {
|
|
517
|
+
frame: "members",
|
|
518
|
+
public: "public"
|
|
519
|
+
};
|
|
143
520
|
var SITE_REDIRECT_STATUSES = [301, 302, 307, 308];
|
|
144
521
|
var DEFAULT_THEME_SCRIPT = '(function(){var t;try{t=localStorage.getItem("alma-site-theme")}catch(e){}' + 'document.documentElement.dataset.theme=t==="dark"||t==="light"?t:' + 'matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"})()';
|
|
145
|
-
function
|
|
146
|
-
return
|
|
522
|
+
function defineApp(app) {
|
|
523
|
+
return app;
|
|
147
524
|
}
|
|
148
|
-
function
|
|
149
|
-
return
|
|
525
|
+
function defineRoute(route) {
|
|
526
|
+
return route;
|
|
527
|
+
}
|
|
528
|
+
function appIn(app, place) {
|
|
529
|
+
const audience = AUDIENCE_OF_PLACE[place];
|
|
530
|
+
return {
|
|
531
|
+
...app,
|
|
532
|
+
routes: app.routes.filter((route) => route.audience === undefined || route.audience === audience)
|
|
533
|
+
};
|
|
150
534
|
}
|
|
151
535
|
var NOT_FOUND = Symbol.for("alma.site.notFound");
|
|
152
536
|
function notFound() {
|
|
153
|
-
const error = new Error("This address has no
|
|
537
|
+
const error = new Error("This address has no route.");
|
|
154
538
|
error[NOT_FOUND] = true;
|
|
155
539
|
return error;
|
|
156
540
|
}
|
|
@@ -258,48 +642,48 @@ function matchRedirect(redirects, address) {
|
|
|
258
642
|
}
|
|
259
643
|
return best?.redirect ?? null;
|
|
260
644
|
}
|
|
261
|
-
function matchAddress(
|
|
645
|
+
function matchAddress(app, address, listed) {
|
|
262
646
|
if (siteAddressProblem(address) !== null)
|
|
263
647
|
return null;
|
|
264
|
-
const redirects =
|
|
265
|
-
const
|
|
266
|
-
if (
|
|
267
|
-
return { kind: "
|
|
648
|
+
const redirects = app.redirects ?? [];
|
|
649
|
+
const exactRoute = app.routes.find((route) => route.path === address);
|
|
650
|
+
if (exactRoute)
|
|
651
|
+
return { kind: "route", route: exactRoute, params: {} };
|
|
268
652
|
const exactRedirect = redirects.find((redirect) => redirect.from === address);
|
|
269
653
|
if (exactRedirect)
|
|
270
654
|
return { kind: "redirect", redirect: exactRedirect };
|
|
271
655
|
let found = null;
|
|
272
656
|
if (!listed || listed.has(address))
|
|
273
|
-
for (const
|
|
274
|
-
const params = matchPattern(
|
|
275
|
-
if (params && (!found || moreSpecific(
|
|
276
|
-
found = {
|
|
657
|
+
for (const route of app.routes) {
|
|
658
|
+
const params = matchPattern(route.path, address);
|
|
659
|
+
if (params && (!found || moreSpecific(route.path, found.route.path) < 0))
|
|
660
|
+
found = { route, params };
|
|
277
661
|
}
|
|
278
662
|
if (found)
|
|
279
|
-
return { kind: "
|
|
663
|
+
return { kind: "route", ...found };
|
|
280
664
|
const redirect = matchRedirect(redirects, address);
|
|
281
665
|
return redirect ? { kind: "redirect", redirect } : null;
|
|
282
666
|
}
|
|
283
|
-
async function listAddresses(
|
|
667
|
+
async function listAddresses(app) {
|
|
284
668
|
const listed = [];
|
|
285
|
-
for (const
|
|
286
|
-
const sets =
|
|
669
|
+
for (const route of app.routes) {
|
|
670
|
+
const sets = route.path.includes("/:") && route.addresses ? await route.addresses() : [{}];
|
|
287
671
|
for (const params of sets) {
|
|
288
|
-
const address = fillPattern(
|
|
672
|
+
const address = fillPattern(route.path, params);
|
|
289
673
|
const problem = siteAddressProblem(address);
|
|
290
674
|
if (problem)
|
|
291
|
-
throw new Error(`
|
|
292
|
-
listed.push({
|
|
675
|
+
throw new Error(`Route ${route.path}: ${problem}`);
|
|
676
|
+
listed.push({ route, params, address });
|
|
293
677
|
}
|
|
294
678
|
}
|
|
295
679
|
const addresses = new Set(listed.map((entry) => entry.address));
|
|
296
680
|
const seen = new Set;
|
|
297
681
|
for (const entry of listed) {
|
|
298
|
-
const match = matchAddress(
|
|
299
|
-
if (match?.kind !== "
|
|
300
|
-
throw new Error(`
|
|
682
|
+
const match = matchAddress(app, entry.address, addresses);
|
|
683
|
+
if (match?.kind !== "route" || match.route !== entry.route)
|
|
684
|
+
throw new Error(`Route ${entry.route.path}: ${entry.address} is served by ${match?.kind === "route" ? `route ${match.route.path}` : "a redirect"}.`);
|
|
301
685
|
if (seen.has(entry.address))
|
|
302
|
-
throw new Error(`
|
|
686
|
+
throw new Error(`Route ${entry.route.path}: ${entry.address} is listed twice.`);
|
|
303
687
|
seen.add(entry.address);
|
|
304
688
|
entry.params = match.params;
|
|
305
689
|
}
|
|
@@ -328,26 +712,51 @@ function siteFileContentType(path) {
|
|
|
328
712
|
return extension ? FILE_TYPES[extension] ?? null : null;
|
|
329
713
|
}
|
|
330
714
|
var ORIGIN = /^https:\/\/[a-z0-9.-]+(?::\d{1,5})?$/;
|
|
331
|
-
|
|
715
|
+
var AUDIENCES = ["members", "public"];
|
|
716
|
+
var PLACE_WORDS = {
|
|
717
|
+
frame: "In Alma",
|
|
718
|
+
public: "At the published address"
|
|
719
|
+
};
|
|
720
|
+
function placeProblems(app, place) {
|
|
332
721
|
const problems = [];
|
|
333
|
-
|
|
334
|
-
problems.push("The site's meta needs a name.");
|
|
335
|
-
const paths = new Set;
|
|
722
|
+
const there = appIn(app, place);
|
|
336
723
|
const shapes = new Map;
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
problems.push(`Page ${problem}`);
|
|
341
|
-
const shape = page.path.replace(/:[A-Za-z_][A-Za-z0-9_]*/g, ":");
|
|
724
|
+
const paths = new Set;
|
|
725
|
+
for (const route of there.routes) {
|
|
726
|
+
const shape = route.path.replace(/:[A-Za-z_][A-Za-z0-9_]*/g, ":");
|
|
342
727
|
if (shapes.has(shape))
|
|
343
|
-
problems.push(
|
|
344
|
-
shapes.set(shape,
|
|
345
|
-
paths.add(
|
|
346
|
-
if (
|
|
347
|
-
problems.push(`
|
|
728
|
+
problems.push(`${PLACE_WORDS[place]}, routes "${shapes.get(shape)}" and "${route.path}" match the same addresses.`);
|
|
729
|
+
shapes.set(shape, route.path);
|
|
730
|
+
paths.add(route.path);
|
|
731
|
+
if (place === "public" && route.path.includes("/:") && !route.addresses)
|
|
732
|
+
problems.push(`Route "${route.path}" has parameters and is public, so it must list its addresses.`);
|
|
733
|
+
if (place === "public" && typeof route.meta !== "function")
|
|
734
|
+
problems.push(`Route "${route.path}" is public, so it needs meta (its title at the published address).`);
|
|
348
735
|
}
|
|
736
|
+
for (const redirect of app.redirects ?? [])
|
|
737
|
+
if (paths.has(redirect.from))
|
|
738
|
+
problems.push(`"${redirect.from}" is both a route and a redirect.`);
|
|
739
|
+
if (place === "public" && there.routes.length === 0)
|
|
740
|
+
problems.push(`No route is public, so there is nothing to publish: set a route's audience to "public", or leave it out for members and the public both.`);
|
|
741
|
+
else if (place === "public" && !app.meta?.name)
|
|
742
|
+
problems.push("The app's meta needs a name to be published.");
|
|
743
|
+
return problems;
|
|
744
|
+
}
|
|
745
|
+
function appDefinitionProblems(app, places = ["frame", "public"]) {
|
|
746
|
+
const problems = [];
|
|
747
|
+
if (!Array.isArray(app.routes))
|
|
748
|
+
return ["The app must list its routes: defineApp({ routes: [...] })."];
|
|
749
|
+
for (const route of app.routes) {
|
|
750
|
+
const problem = patternProblem(route.path);
|
|
751
|
+
if (problem)
|
|
752
|
+
problems.push(`Route ${problem}`);
|
|
753
|
+
if (route.audience !== undefined && !AUDIENCES.includes(route.audience))
|
|
754
|
+
problems.push(`Route "${route.path}": its audience is "members" or "public", or left out for both.`);
|
|
755
|
+
}
|
|
756
|
+
for (const place of places)
|
|
757
|
+
problems.push(...placeProblems(app, place));
|
|
349
758
|
const froms = new Set;
|
|
350
|
-
for (const redirect of
|
|
759
|
+
for (const redirect of app.redirects ?? []) {
|
|
351
760
|
const prefix = redirectPrefix(redirect.from);
|
|
352
761
|
const problem = prefix === "" ? null : siteAddressProblem(prefix ?? redirect.from);
|
|
353
762
|
if (problem)
|
|
@@ -357,31 +766,29 @@ function siteDefinitionProblems(site) {
|
|
|
357
766
|
froms.add(redirect.from);
|
|
358
767
|
if (!SITE_REDIRECT_STATUSES.includes(redirect.status))
|
|
359
768
|
problems.push(`Redirect "${redirect.from}" must be a 301, 302, 307 or 308.`);
|
|
360
|
-
if (paths.has(redirect.from))
|
|
361
|
-
problems.push(`"${redirect.from}" is both a page and a redirect.`);
|
|
362
769
|
const external = redirect.to.startsWith("https://");
|
|
363
770
|
if (!external && siteAddressProblem(redirect.to) !== null)
|
|
364
|
-
problems.push(`Redirect "${redirect.from}" must go to an address
|
|
771
|
+
problems.push(`Redirect "${redirect.from}" must go to an address of this app or an https URL.`);
|
|
365
772
|
if (!external && redirect.to === redirect.from)
|
|
366
773
|
problems.push(`Redirect "${redirect.from}" goes to itself.`);
|
|
367
774
|
}
|
|
368
|
-
for (const origin of
|
|
775
|
+
for (const origin of app.embeds ?? [])
|
|
369
776
|
if (!ORIGIN.test(origin))
|
|
370
777
|
problems.push(`Embed "${origin}" must be an https origin, such as https://calendar.google.com.`);
|
|
371
|
-
for (const path of Object.keys(
|
|
778
|
+
for (const path of Object.keys(app.files ?? {})) {
|
|
372
779
|
const segments = path.split("/");
|
|
373
780
|
if (path.startsWith("/") || segments.some((segment) => segment === "" || segment === "." || segment === "..") || /^_(assets|files|alma)$/.test(segments[0]) || RESERVED_FILES.has(path))
|
|
374
781
|
problems.push(`File "${path}" cannot be declared.`);
|
|
375
782
|
else if (siteFileContentType(path) === null)
|
|
376
|
-
problems.push(`File "${path}" has an extension
|
|
783
|
+
problems.push(`File "${path}" has an extension the published address cannot serve.`);
|
|
377
784
|
}
|
|
378
|
-
return problems;
|
|
785
|
+
return [...new Set(problems)];
|
|
379
786
|
}
|
|
380
|
-
function isSiteFileAddress(
|
|
381
|
-
if (!
|
|
787
|
+
function isSiteFileAddress(app, address) {
|
|
788
|
+
if (!app.files || address === "/" || !address.startsWith("/"))
|
|
382
789
|
return false;
|
|
383
790
|
const path = address.slice(1);
|
|
384
|
-
return Object.hasOwn(
|
|
791
|
+
return Object.hasOwn(app.files, path) || Object.hasOwn(app.files, `${path}/index.html`);
|
|
385
792
|
}
|
|
386
793
|
function outputPathOf(address) {
|
|
387
794
|
return address === "/" ? "index.html" : `${address.slice(1)}/index.html`;
|
|
@@ -395,22 +802,22 @@ function escapeHtml(text) {
|
|
|
395
802
|
function scriptJson(value) {
|
|
396
803
|
return JSON.stringify(value).replaceAll("<", "\\u003c").replaceAll(">", "\\u003e").replaceAll("&", "\\u0026").replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
|
|
397
804
|
}
|
|
398
|
-
function pageTitle(
|
|
399
|
-
return
|
|
805
|
+
function pageTitle(app, meta) {
|
|
806
|
+
return app.titleTemplate && !meta.absoluteTitle ? app.titleTemplate.replace("%s", meta.title) : meta.title;
|
|
400
807
|
}
|
|
401
808
|
function buildDocumentHead(input) {
|
|
402
|
-
const {
|
|
403
|
-
const title = pageTitle(
|
|
404
|
-
const description = meta.description ??
|
|
809
|
+
const { app, meta, origin } = input;
|
|
810
|
+
const title = pageTitle(app, meta);
|
|
811
|
+
const description = meta.description ?? app.description;
|
|
405
812
|
const canonical = absoluteUrl(origin, meta.canonical ?? input.address);
|
|
406
|
-
const ogTitle = meta.openGraph?.title ??
|
|
407
|
-
const ogDescription = meta.openGraph?.description ??
|
|
408
|
-
const twitterTitle = meta.x?.title ??
|
|
409
|
-
const twitterDescription = meta.x?.description ??
|
|
813
|
+
const ogTitle = meta.openGraph?.title ?? app.openGraph?.title ?? meta.title;
|
|
814
|
+
const ogDescription = meta.openGraph?.description ?? app.openGraph?.description ?? description;
|
|
815
|
+
const twitterTitle = meta.x?.title ?? app.x?.title ?? meta.title;
|
|
816
|
+
const twitterDescription = meta.x?.description ?? app.x?.description ?? description;
|
|
410
817
|
const pageImage = meta.openGraph?.image ?? meta.image;
|
|
411
|
-
const image = pageImage ??
|
|
412
|
-
const imageAlt = pageImage ? meta.imageAlt :
|
|
413
|
-
const twitterImage = meta.image ??
|
|
818
|
+
const image = pageImage ?? app.image;
|
|
819
|
+
const imageAlt = pageImage ? meta.imageAlt : app.imageAlt;
|
|
820
|
+
const twitterImage = meta.image ?? app.image;
|
|
414
821
|
const tag = (name, attributes) => `<${name} ${Object.entries(attributes).map(([key, value]) => `${key}="${escapeHtml(value)}"`).join(" ")}>`;
|
|
415
822
|
const property = (key, content) => tag("meta", { property: key, content });
|
|
416
823
|
const named = (key, content) => tag("meta", { name: key, content });
|
|
@@ -424,15 +831,15 @@ function buildDocumentHead(input) {
|
|
|
424
831
|
head.push(property("og:title", ogTitle), property("og:type", meta.type ?? "website"));
|
|
425
832
|
if (!meta.noindex)
|
|
426
833
|
head.push(property("og:url", canonical));
|
|
427
|
-
head.push(property("og:site_name",
|
|
834
|
+
head.push(property("og:site_name", app.name));
|
|
428
835
|
if (ogDescription)
|
|
429
836
|
head.push(property("og:description", ogDescription));
|
|
430
|
-
if (
|
|
431
|
-
head.push(property("og:locale",
|
|
837
|
+
if (app.locale)
|
|
838
|
+
head.push(property("og:locale", app.locale));
|
|
432
839
|
if (image) {
|
|
433
840
|
head.push(property("og:image", absoluteUrl(origin, image)));
|
|
434
|
-
if (!pageImage &&
|
|
435
|
-
head.push(property("og:image:width", String(
|
|
841
|
+
if (!pageImage && app.imageWidth && app.imageHeight)
|
|
842
|
+
head.push(property("og:image:width", String(app.imageWidth)), property("og:image:height", String(app.imageHeight)));
|
|
436
843
|
if (imageAlt)
|
|
437
844
|
head.push(property("og:image:alt", imageAlt));
|
|
438
845
|
}
|
|
@@ -442,30 +849,30 @@ function buildDocumentHead(input) {
|
|
|
442
849
|
head.push(named("twitter:description", twitterDescription));
|
|
443
850
|
if (twitterImage)
|
|
444
851
|
head.push(named("twitter:image", absoluteUrl(origin, twitterImage)));
|
|
445
|
-
if (
|
|
446
|
-
head.push(named("twitter:site",
|
|
447
|
-
if (typeof
|
|
448
|
-
head.push(tag("link", { rel: "icon", href:
|
|
449
|
-
else if (
|
|
852
|
+
if (app.twitter)
|
|
853
|
+
head.push(named("twitter:site", app.twitter));
|
|
854
|
+
if (typeof app.favicon === "string")
|
|
855
|
+
head.push(tag("link", { rel: "icon", href: app.favicon }));
|
|
856
|
+
else if (app.favicon)
|
|
450
857
|
head.push(tag("link", {
|
|
451
858
|
rel: "icon",
|
|
452
|
-
href:
|
|
859
|
+
href: app.favicon.light,
|
|
453
860
|
media: "(prefers-color-scheme: light)"
|
|
454
861
|
}), tag("link", {
|
|
455
862
|
rel: "icon",
|
|
456
|
-
href:
|
|
863
|
+
href: app.favicon.dark,
|
|
457
864
|
media: "(prefers-color-scheme: dark)"
|
|
458
865
|
}));
|
|
459
|
-
if (typeof
|
|
460
|
-
head.push(named("theme-color",
|
|
461
|
-
else if (
|
|
866
|
+
if (typeof app.themeColor === "string")
|
|
867
|
+
head.push(named("theme-color", app.themeColor));
|
|
868
|
+
else if (app.themeColor)
|
|
462
869
|
head.push(tag("meta", {
|
|
463
870
|
name: "theme-color",
|
|
464
|
-
content:
|
|
871
|
+
content: app.themeColor.light,
|
|
465
872
|
media: "(prefers-color-scheme: light)"
|
|
466
873
|
}), tag("meta", {
|
|
467
874
|
name: "theme-color",
|
|
468
|
-
content:
|
|
875
|
+
content: app.themeColor.dark,
|
|
469
876
|
media: "(prefers-color-scheme: dark)"
|
|
470
877
|
}));
|
|
471
878
|
for (const font of input.fonts ?? [])
|
|
@@ -476,7 +883,7 @@ function buildDocumentHead(input) {
|
|
|
476
883
|
type: font.type ?? "font/woff2",
|
|
477
884
|
crossorigin: ""
|
|
478
885
|
}));
|
|
479
|
-
for (const jsonLd of [
|
|
886
|
+
for (const jsonLd of [app.jsonLd ?? [], meta.jsonLd ?? []].flat())
|
|
480
887
|
head.push(`<script type="application/ld+json">${scriptJson(jsonLd)}</script>`);
|
|
481
888
|
return head.join(`
|
|
482
889
|
`);
|
|
@@ -513,149 +920,6 @@ function buildRobots(origin, robots = {}) {
|
|
|
513
920
|
].join(`
|
|
514
921
|
`);
|
|
515
922
|
}
|
|
516
|
-
// src/siteRuntime.ts
|
|
517
|
-
class SiteRefusalError extends AppCallError {
|
|
518
|
-
retryAfterSeconds;
|
|
519
|
-
constructor(message, code, retryAfterSeconds) {
|
|
520
|
-
super(message, { code });
|
|
521
|
-
this.name = "SiteRefusalError";
|
|
522
|
-
this.retryAfterSeconds = retryAfterSeconds;
|
|
523
|
-
}
|
|
524
|
-
}
|
|
525
|
-
function isSiteRefusal(error) {
|
|
526
|
-
return error instanceof SiteRefusalError;
|
|
527
|
-
}
|
|
528
|
-
var PUBLISHED_SITE_ATTRIBUTE = "data-alma-site";
|
|
529
|
-
function publishedSite() {
|
|
530
|
-
if (typeof document === "undefined")
|
|
531
|
-
return null;
|
|
532
|
-
return document.documentElement.hasAttribute(PUBLISHED_SITE_ATTRIBUTE) ? { origin: location.origin } : null;
|
|
533
|
-
}
|
|
534
|
-
var RESULT_TOKEN = /^[A-Za-z0-9_-]{16,512}$/;
|
|
535
|
-
function readResultToken(hash = typeof location === "undefined" ? "" : location.hash) {
|
|
536
|
-
const fragment = hash.startsWith("#") ? hash.slice(1) : hash;
|
|
537
|
-
const token = fragment.includes("=") ? new URLSearchParams(fragment).get("token") : fragment;
|
|
538
|
-
return token && RESULT_TOKEN.test(token) ? token : null;
|
|
539
|
-
}
|
|
540
|
-
var LEAVES_ALMA = "A site published to the web has no Alma around it to open.";
|
|
541
|
-
function siteNavigation() {
|
|
542
|
-
const listeners = new Set;
|
|
543
|
-
const current = () => applicationPath(location.pathname) ?? "/";
|
|
544
|
-
window.addEventListener("popstate", () => {
|
|
545
|
-
const path = current();
|
|
546
|
-
for (const listener of listeners)
|
|
547
|
-
listener(path, null);
|
|
548
|
-
});
|
|
549
|
-
return {
|
|
550
|
-
getPath: current,
|
|
551
|
-
subscribe: (listener) => {
|
|
552
|
-
listeners.add(listener);
|
|
553
|
-
return () => listeners.delete(listener);
|
|
554
|
-
},
|
|
555
|
-
navigate: (path, options = {}) => {
|
|
556
|
-
if (applicationPath(path) === null)
|
|
557
|
-
throw new Error("Site navigation requires a path on this site");
|
|
558
|
-
const hash = options.hash ?? "";
|
|
559
|
-
if (/[\s#]/.test(hash))
|
|
560
|
-
throw new Error("A fragment holds no space or #");
|
|
561
|
-
const url = hash ? `${path}#${hash}` : path;
|
|
562
|
-
if (options.replace)
|
|
563
|
-
history.replaceState(null, "", url);
|
|
564
|
-
else
|
|
565
|
-
history.pushState(null, "", url);
|
|
566
|
-
for (const listener of listeners)
|
|
567
|
-
listener(path, "latest");
|
|
568
|
-
},
|
|
569
|
-
openApps: () => {
|
|
570
|
-
throw new Error(LEAVES_ALMA);
|
|
571
|
-
},
|
|
572
|
-
openTasks: () => {
|
|
573
|
-
throw new Error(LEAVES_ALMA);
|
|
574
|
-
},
|
|
575
|
-
openTopic: () => {
|
|
576
|
-
throw new Error(LEAVES_ALMA);
|
|
577
|
-
}
|
|
578
|
-
};
|
|
579
|
-
}
|
|
580
|
-
var NO_VIEWER = "A site published to the web has no signed-in viewer, so it can only raise the events its app declares.";
|
|
581
|
-
var noViewer = () => Promise.reject(new AppCallError(NO_VIEWER, { code: "site.no_viewer" }));
|
|
582
|
-
function retryAfter(response) {
|
|
583
|
-
const header = response.headers.get("retry-after");
|
|
584
|
-
if (header === null)
|
|
585
|
-
return null;
|
|
586
|
-
const seconds = Number(header);
|
|
587
|
-
if (Number.isFinite(seconds) && seconds >= 0)
|
|
588
|
-
return Math.ceil(seconds);
|
|
589
|
-
const at = Date.parse(header);
|
|
590
|
-
return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - Date.now()) / 1000));
|
|
591
|
-
}
|
|
592
|
-
async function refusal(response) {
|
|
593
|
-
let said = {};
|
|
594
|
-
try {
|
|
595
|
-
said = await response.json();
|
|
596
|
-
} catch {}
|
|
597
|
-
const message = typeof said.error === "string" ? said.error : `The site refused the request (${response.status}).`;
|
|
598
|
-
const code = typeof said.code === "string" ? said.code : undefined;
|
|
599
|
-
if (code === "visitor.rate_limited" || code === "site.paused")
|
|
600
|
-
return new SiteRefusalError(message, code, retryAfter(response));
|
|
601
|
-
return new AppCallError(message, code ? { code } : {});
|
|
602
|
-
}
|
|
603
|
-
var GATEWAY_ERRORS = new Set([502, 503, 504]);
|
|
604
|
-
function siteTransport(options = {}) {
|
|
605
|
-
const base = options.base ?? "";
|
|
606
|
-
const send = options.fetch ?? ((input, init) => fetch(input, init));
|
|
607
|
-
const delays = options.retryDelaysMs ?? [1000, 2000];
|
|
608
|
-
const raise = async (body) => {
|
|
609
|
-
for (let attempt = 0;; attempt += 1) {
|
|
610
|
-
let response = null;
|
|
611
|
-
try {
|
|
612
|
-
response = await send(`${base}/_alma/events`, {
|
|
613
|
-
method: "POST",
|
|
614
|
-
headers: { "content-type": "application/json" },
|
|
615
|
-
body: JSON.stringify(body)
|
|
616
|
-
});
|
|
617
|
-
} catch (error) {
|
|
618
|
-
if (attempt >= delays.length)
|
|
619
|
-
throw error;
|
|
620
|
-
}
|
|
621
|
-
if (response && !GATEWAY_ERRORS.has(response.status)) {
|
|
622
|
-
if (!response.ok)
|
|
623
|
-
throw await refusal(response);
|
|
624
|
-
return await response.json();
|
|
625
|
-
}
|
|
626
|
-
if (attempt >= delays.length)
|
|
627
|
-
throw await refusal(response);
|
|
628
|
-
await new Promise((resolve) => setTimeout(resolve, delays[attempt]));
|
|
629
|
-
}
|
|
630
|
-
};
|
|
631
|
-
const tellsNothing = () => Promise.resolve({ watching: false, stop: () => {} });
|
|
632
|
-
return {
|
|
633
|
-
call: (operationId, request = {}) => {
|
|
634
|
-
if (operationId !== "raiseAppEvent")
|
|
635
|
-
return noViewer();
|
|
636
|
-
const { event, payload } = request.body ?? {};
|
|
637
|
-
return raise({
|
|
638
|
-
event,
|
|
639
|
-
...payload === undefined ? {} : { payload },
|
|
640
|
-
idempotency_key: request.idempotencyKey ?? crypto.randomUUID()
|
|
641
|
-
});
|
|
642
|
-
},
|
|
643
|
-
viewer: () => Promise.resolve(null),
|
|
644
|
-
shell: () => Promise.resolve(null),
|
|
645
|
-
watch: () => Promise.resolve({ watching: [], stop: () => {} }),
|
|
646
|
-
watchTypes: () => Promise.resolve({ watching: [], stop: () => {} }),
|
|
647
|
-
watchShared: tellsNothing,
|
|
648
|
-
watchPresence: tellsNothing,
|
|
649
|
-
watchBroadcasts: tellsNothing,
|
|
650
|
-
result: async (token) => {
|
|
651
|
-
const response = await send(`${base}/_alma/results/${encodeURIComponent(token)}`, { cache: "no-store" });
|
|
652
|
-
if (!response.ok)
|
|
653
|
-
throw await refusal(response);
|
|
654
|
-
const answer = await response.json();
|
|
655
|
-
return answer["status"] === "ready" ? { status: "ready", result: answer["result"] } : { status: "pending" };
|
|
656
|
-
}
|
|
657
|
-
};
|
|
658
|
-
}
|
|
659
923
|
|
|
660
924
|
// src/index.ts
|
|
661
925
|
var FINISHED = [
|
|
@@ -677,6 +941,7 @@ var SHELL_QUESTION = "getAppShell";
|
|
|
677
941
|
var SHELL_WAIT_MS = 3000;
|
|
678
942
|
var WATCH_QUESTION = "watchTopicChanges";
|
|
679
943
|
var WATCH_WAIT_MS = 5000;
|
|
944
|
+
var FILE_WAIT_MS = 120000;
|
|
680
945
|
var WATCH_TYPES_QUESTION = "watchTypeChanges";
|
|
681
946
|
var PUSHED_REREAD_MS = 300000;
|
|
682
947
|
var CATCH_UP_OVERLAP_MS = 60000;
|
|
@@ -692,6 +957,8 @@ var WATCH_BROADCASTS_QUESTION = "watchBroadcasts";
|
|
|
692
957
|
var BROADCAST_MESSAGE = "alma:broadcast";
|
|
693
958
|
var BROADCAST_EVENT = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
694
959
|
var oneRequest = () => crypto.randomUUID();
|
|
960
|
+
var workflowParam = (workflow) => typeof workflow === "string" ? workflow : workflow.key;
|
|
961
|
+
var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
695
962
|
function createAppSdk(transport) {
|
|
696
963
|
const read = new Map;
|
|
697
964
|
const precondition = (topicId, fieldKey, options) => {
|
|
@@ -706,6 +973,20 @@ function createAppSdk(transport) {
|
|
|
706
973
|
const revision = fields[fieldKey];
|
|
707
974
|
return revision === undefined ? { if_value: null } : { if_revision: revision };
|
|
708
975
|
};
|
|
976
|
+
let types = null;
|
|
977
|
+
const typeIdOf = async (typeKey) => {
|
|
978
|
+
types ??= transport.call("listTopicTypes").catch((error) => {
|
|
979
|
+
types = null;
|
|
980
|
+
throw error;
|
|
981
|
+
});
|
|
982
|
+
const named = (await types).filter((type) => type.key === typeKey);
|
|
983
|
+
const found = named.find((type) => type.schema.kind === "app") ?? (named.length === 1 ? named[0] : undefined);
|
|
984
|
+
if (!found)
|
|
985
|
+
throw new AppCallError(`This app reads no one type "${typeKey}".`, {
|
|
986
|
+
code: "type.not_found"
|
|
987
|
+
});
|
|
988
|
+
return found.id;
|
|
989
|
+
};
|
|
709
990
|
const getExecution = (executionId) => transport.call("getExecution", {
|
|
710
991
|
params: { id: executionId }
|
|
711
992
|
});
|
|
@@ -1017,8 +1298,11 @@ function createAppSdk(transport) {
|
|
|
1017
1298
|
params: { key },
|
|
1018
1299
|
query: { type, cursor: page.cursor, limit: page.limit }
|
|
1019
1300
|
}),
|
|
1020
|
-
getTopicRecord: async (topicId) => {
|
|
1021
|
-
const record = await transport.call("getTopicRecord", {
|
|
1301
|
+
getTopicRecord: async (topicId, options = {}) => {
|
|
1302
|
+
const record = await transport.call("getTopicRecord", {
|
|
1303
|
+
params: { id: topicId },
|
|
1304
|
+
...options.type ? { query: { type: options.type } } : {}
|
|
1305
|
+
});
|
|
1022
1306
|
if (record.revisions)
|
|
1023
1307
|
read.set(topicId, { ...record.revisions });
|
|
1024
1308
|
return record;
|
|
@@ -1090,10 +1374,11 @@ function createAppSdk(transport) {
|
|
|
1090
1374
|
},
|
|
1091
1375
|
createTopic: async (name, topicTypeId, options = {}) => {
|
|
1092
1376
|
const fields = options.fields ?? [];
|
|
1377
|
+
const typeId = topicTypeId && !UUID2.test(topicTypeId) && transport.place !== "public" ? await typeIdOf(topicTypeId) : topicTypeId;
|
|
1093
1378
|
const created = await transport.call("createTopic", {
|
|
1094
1379
|
body: {
|
|
1095
1380
|
name,
|
|
1096
|
-
...
|
|
1381
|
+
...typeId ? { topic_type_id: typeId } : {},
|
|
1097
1382
|
...fields.length > 0 ? {
|
|
1098
1383
|
fields: fields.map((field) => ({
|
|
1099
1384
|
key: field.key,
|
|
@@ -1116,10 +1401,19 @@ function createAppSdk(transport) {
|
|
|
1116
1401
|
params: { id: topicId },
|
|
1117
1402
|
idempotencyKey: options.idempotencyKey ?? oneRequest()
|
|
1118
1403
|
}),
|
|
1404
|
+
issueRecordLink: (recordId, link, options = {}) => transport.call("issueRecordLink", {
|
|
1405
|
+
params: { id: recordId },
|
|
1406
|
+
body: { path: link.path },
|
|
1407
|
+
idempotencyKey: options.idempotencyKey ?? oneRequest()
|
|
1408
|
+
}),
|
|
1409
|
+
revokeRecordLink: (recordId, options = {}) => transport.call("revokeRecordLink", {
|
|
1410
|
+
params: { id: recordId },
|
|
1411
|
+
idempotencyKey: options.idempotencyKey ?? oneRequest()
|
|
1412
|
+
}),
|
|
1119
1413
|
listTopicTypes: () => transport.call("listTopicTypes"),
|
|
1120
1414
|
listWorkflows: () => transport.call("listWorkflows"),
|
|
1121
|
-
runWorkflow: (
|
|
1122
|
-
params: { id:
|
|
1415
|
+
runWorkflow: (workflow, run = {}, options = {}) => transport.call("runWorkflow", {
|
|
1416
|
+
params: { id: workflowParam(workflow) },
|
|
1123
1417
|
body: {
|
|
1124
1418
|
...run.topicId ? { topic_id: run.topicId } : {},
|
|
1125
1419
|
...run.input ? { input: run.input } : {}
|
|
@@ -1127,8 +1421,8 @@ function createAppSdk(transport) {
|
|
|
1127
1421
|
idempotencyKey: options.idempotencyKey ?? oneRequest()
|
|
1128
1422
|
}),
|
|
1129
1423
|
getExecution,
|
|
1130
|
-
listRuns: async (
|
|
1131
|
-
params: { id:
|
|
1424
|
+
listRuns: async (workflow, run = {}) => await transport.call("listWorkflowExecutions", {
|
|
1425
|
+
params: { id: workflowParam(workflow) },
|
|
1132
1426
|
query: { topic_id: run.topicId }
|
|
1133
1427
|
}),
|
|
1134
1428
|
waitForExecution: async (executionId, options = {}) => {
|
|
@@ -1176,6 +1470,31 @@ function createAppSdk(transport) {
|
|
|
1176
1470
|
}));
|
|
1177
1471
|
return transport.result(token);
|
|
1178
1472
|
},
|
|
1473
|
+
fileUrl: (name) => {
|
|
1474
|
+
const fileUrl = transport.fileUrl?.bind(transport);
|
|
1475
|
+
if (!fileUrl)
|
|
1476
|
+
return Promise.reject(new AppCallError("This app has no files to show.", {
|
|
1477
|
+
code: "file.unavailable"
|
|
1478
|
+
}));
|
|
1479
|
+
return new Promise((resolve) => resolve(fileUrl(name)));
|
|
1480
|
+
},
|
|
1481
|
+
ownEntry: async (hash) => {
|
|
1482
|
+
if (!transport.result)
|
|
1483
|
+
throw new AppCallError("This app has no event results to read.", {
|
|
1484
|
+
code: "result.unavailable"
|
|
1485
|
+
});
|
|
1486
|
+
const token = readResultToken(hash);
|
|
1487
|
+
if (token === null)
|
|
1488
|
+
return null;
|
|
1489
|
+
const answer = await transport.result(token);
|
|
1490
|
+
if (answer.status === "pending")
|
|
1491
|
+
return answer;
|
|
1492
|
+
if (!isOwnEntry(answer.result))
|
|
1493
|
+
throw new AppCallError("This private link names no entry.", {
|
|
1494
|
+
code: "result.not_entry"
|
|
1495
|
+
});
|
|
1496
|
+
return { status: "ready", ...answer.result };
|
|
1497
|
+
},
|
|
1179
1498
|
waitForResult: async (token, options = {}) => {
|
|
1180
1499
|
const read = transport.result?.bind(transport);
|
|
1181
1500
|
if (!read)
|
|
@@ -1596,6 +1915,7 @@ function hostTransport() {
|
|
|
1596
1915
|
return { watching: [], stop };
|
|
1597
1916
|
}
|
|
1598
1917
|
};
|
|
1918
|
+
const files2 = new Map;
|
|
1599
1919
|
return {
|
|
1600
1920
|
call: (operationId, request = {}) => ask(operationId, request),
|
|
1601
1921
|
viewer: async () => {
|
|
@@ -1607,6 +1927,28 @@ function hostTransport() {
|
|
|
1607
1927
|
const told = await ask(SHELL_QUESTION, {}, SHELL_WAIT_MS);
|
|
1608
1928
|
return isAppShell(told) ? told : null;
|
|
1609
1929
|
},
|
|
1930
|
+
fileUrl: (name) => {
|
|
1931
|
+
if (!isAppFileName(name))
|
|
1932
|
+
return Promise.reject(new AppCallError(`"${name}" is not a file name.`, {
|
|
1933
|
+
code: "file.invalid_name"
|
|
1934
|
+
}));
|
|
1935
|
+
let url = files2.get(name);
|
|
1936
|
+
if (!url) {
|
|
1937
|
+
url = ask(APP_FILE_QUESTION, { body: { name } }, FILE_WAIT_MS).then((told) => {
|
|
1938
|
+
const answer = typeof told === "object" && told !== null ? told : {};
|
|
1939
|
+
const bytes = answer["bytes"];
|
|
1940
|
+
const mediaType = answer["media_type"];
|
|
1941
|
+
if (!(bytes instanceof ArrayBuffer) || typeof mediaType !== "string")
|
|
1942
|
+
throw new AppCallError("The host sent no file.", {
|
|
1943
|
+
code: "file.unavailable"
|
|
1944
|
+
});
|
|
1945
|
+
return URL.createObjectURL(new Blob([bytes], { type: mediaType }));
|
|
1946
|
+
});
|
|
1947
|
+
files2.set(name, url);
|
|
1948
|
+
url.catch(() => files2.delete(name));
|
|
1949
|
+
}
|
|
1950
|
+
return url;
|
|
1951
|
+
},
|
|
1610
1952
|
watch: (topicIds, changed) => watchFor(WATCH_QUESTION, "topic_ids", topicChanges, topicIds, changed),
|
|
1611
1953
|
watchTypes: (typeIds, changed) => watchFor(WATCH_TYPES_QUESTION, "type_ids", typeChanges, typeIds, changed),
|
|
1612
1954
|
watchShared: async (told) => {
|
|
@@ -1663,11 +2005,16 @@ function hostTransport() {
|
|
|
1663
2005
|
};
|
|
1664
2006
|
}
|
|
1665
2007
|
export {
|
|
2008
|
+
APP_FILE_QUESTION,
|
|
1666
2009
|
AppCallError,
|
|
1667
2010
|
BROADCAST_MESSAGE,
|
|
1668
2011
|
DEFAULT_THEME_SCRIPT,
|
|
1669
|
-
|
|
2012
|
+
NOT_FOUND_ROUTE_ID,
|
|
2013
|
+
OPEN_FILE_MESSAGE,
|
|
2014
|
+
OPEN_FILE_TEXT_LIMIT,
|
|
2015
|
+
OPEN_URL_MESSAGE,
|
|
1670
2016
|
PRESENCE_MESSAGE,
|
|
2017
|
+
PUBLIC_RECORD_SHAPE,
|
|
1671
2018
|
PUBLISHED_SITE_ATTRIBUTE,
|
|
1672
2019
|
SHARED_STATE_MESSAGE,
|
|
1673
2020
|
SHELL_QUESTION,
|
|
@@ -1681,20 +2028,26 @@ export {
|
|
|
1681
2028
|
WATCH_SHARED_QUESTION,
|
|
1682
2029
|
WATCH_TYPES_QUESTION,
|
|
1683
2030
|
absoluteUrl,
|
|
2031
|
+
appDefinitionProblems,
|
|
2032
|
+
appFileNameOf,
|
|
2033
|
+
appIn,
|
|
2034
|
+
appPlace,
|
|
1684
2035
|
applicationPath,
|
|
1685
2036
|
buildDocumentHead,
|
|
1686
2037
|
buildRobots,
|
|
1687
2038
|
buildSitemap,
|
|
1688
2039
|
createAppSdk,
|
|
1689
|
-
|
|
1690
|
-
|
|
2040
|
+
defineApp,
|
|
2041
|
+
defineRoute,
|
|
1691
2042
|
escapeHtml,
|
|
1692
2043
|
fillPattern,
|
|
1693
2044
|
hostEvents,
|
|
1694
2045
|
hostNavigation,
|
|
1695
2046
|
hostTransport,
|
|
2047
|
+
isAppFileName,
|
|
1696
2048
|
isFieldChanged,
|
|
1697
2049
|
isNotFound,
|
|
2050
|
+
isOwnEntry,
|
|
1698
2051
|
isSharedStateConflict,
|
|
1699
2052
|
isSiteFileAddress,
|
|
1700
2053
|
isSiteRefusal,
|
|
@@ -1704,13 +2057,13 @@ export {
|
|
|
1704
2057
|
matchRedirect,
|
|
1705
2058
|
notFound,
|
|
1706
2059
|
outputPathOf,
|
|
2060
|
+
outsideUrl,
|
|
1707
2061
|
pageTitle,
|
|
1708
2062
|
parseAppHostEvent,
|
|
1709
2063
|
publishedSite,
|
|
1710
2064
|
readResultToken,
|
|
1711
2065
|
scriptJson,
|
|
1712
2066
|
siteAddressProblem,
|
|
1713
|
-
siteDefinitionProblems,
|
|
1714
2067
|
siteFileContentType,
|
|
1715
2068
|
siteNavigation,
|
|
1716
2069
|
siteTransport
|