@almateam/app-sdk 0.8.0 → 0.10.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 +180 -17
- package/app.d.ts +297 -0
- package/callError.d.ts +21 -0
- package/cli.js +703 -37
- package/files.d.ts +25 -0
- package/index.d.ts +96 -38
- package/index.js +959 -22
- package/navigation.d.ts +44 -2
- package/package.json +1 -1
- package/siteRuntime.d.ts +96 -0
package/index.js
CHANGED
|
@@ -20,6 +20,31 @@ function hostLine() {
|
|
|
20
20
|
};
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
// src/callError.ts
|
|
24
|
+
class AppCallError extends Error {
|
|
25
|
+
code;
|
|
26
|
+
current;
|
|
27
|
+
constructor(message, detail = {}) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.name = "AppCallError";
|
|
30
|
+
this.code = detail.code;
|
|
31
|
+
this.current = detail.current;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
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
|
+
|
|
23
48
|
// src/navigation.ts
|
|
24
49
|
function applicationPath(value) {
|
|
25
50
|
if (typeof value !== "string" || value.length > 2048 || !value.startsWith("/") || value.startsWith("//") || /[\\?#]/.test(value) || [...value].some((character) => character.charCodeAt(0) < 32))
|
|
@@ -27,6 +52,22 @@ function applicationPath(value) {
|
|
|
27
52
|
const parsed = new URL(value, "https://application.invalid");
|
|
28
53
|
return parsed.origin === "https://application.invalid" && parsed.pathname === value ? value : null;
|
|
29
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
|
+
}
|
|
30
71
|
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
31
72
|
function parseAppHostEvent(told) {
|
|
32
73
|
if (typeof told !== "object" || told === null)
|
|
@@ -103,11 +144,37 @@ function hostNavigation() {
|
|
|
103
144
|
listeners.add(listener);
|
|
104
145
|
return () => listeners.delete(listener);
|
|
105
146
|
},
|
|
106
|
-
navigate: (next) => {
|
|
147
|
+
navigate: (next, options = {}) => {
|
|
107
148
|
if (applicationPath(next) === null)
|
|
108
149
|
throw new Error("App navigation requires a relative path");
|
|
109
150
|
reported += 1;
|
|
110
|
-
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 });
|
|
111
178
|
},
|
|
112
179
|
openApps: () => line.post({ type: "alma:leave" }),
|
|
113
180
|
openTasks: (taskId) => {
|
|
@@ -126,22 +193,733 @@ function hostNavigation() {
|
|
|
126
193
|
};
|
|
127
194
|
}
|
|
128
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
|
+
const response = await send(`${base}/_alma/results/${encodeURIComponent(token)}`, { cache: "no-store" });
|
|
487
|
+
if (!response.ok)
|
|
488
|
+
throw await refusal(response);
|
|
489
|
+
const answer = await response.json();
|
|
490
|
+
if (answer["status"] !== "ready")
|
|
491
|
+
return { status: "pending" };
|
|
492
|
+
const record = answer["record"];
|
|
493
|
+
const type = answer["type"];
|
|
494
|
+
if (typeof type === "string" && typeof record === "object" && record)
|
|
495
|
+
return {
|
|
496
|
+
status: "ready",
|
|
497
|
+
result: {
|
|
498
|
+
type,
|
|
499
|
+
record: asTopicRecord(record, type)
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
return { status: "ready", result: answer["result"] };
|
|
503
|
+
}
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
// src/app.ts
|
|
507
|
+
var SITE_ORIGIN_TOKEN = "__ALMA_SITE_ORIGIN__";
|
|
508
|
+
var NOT_FOUND_ROUTE_ID = "404";
|
|
509
|
+
var AUDIENCE_OF_PLACE = {
|
|
510
|
+
frame: "members",
|
|
511
|
+
public: "public"
|
|
512
|
+
};
|
|
513
|
+
var SITE_REDIRECT_STATUSES = [301, 302, 307, 308];
|
|
514
|
+
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"})()';
|
|
515
|
+
function defineApp(app) {
|
|
516
|
+
return app;
|
|
517
|
+
}
|
|
518
|
+
function defineRoute(route) {
|
|
519
|
+
return route;
|
|
520
|
+
}
|
|
521
|
+
function appIn(app, place) {
|
|
522
|
+
const audience = AUDIENCE_OF_PLACE[place];
|
|
523
|
+
return {
|
|
524
|
+
...app,
|
|
525
|
+
routes: app.routes.filter((route) => route.audience === undefined || route.audience === audience)
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
var NOT_FOUND = Symbol.for("alma.site.notFound");
|
|
529
|
+
function notFound() {
|
|
530
|
+
const error = new Error("This address has no route.");
|
|
531
|
+
error[NOT_FOUND] = true;
|
|
532
|
+
return error;
|
|
533
|
+
}
|
|
534
|
+
function isNotFound(error) {
|
|
535
|
+
return error instanceof Error && error[NOT_FOUND] === true;
|
|
536
|
+
}
|
|
537
|
+
var SEGMENT = /^(?:[A-Za-z0-9\-._~!$&'()*+,;=:@]|%[0-9A-Fa-f]{2})+$/;
|
|
538
|
+
var PARAMETER = /^:([A-Za-z_][A-Za-z0-9_]*)$/;
|
|
539
|
+
function siteAddressProblem(address) {
|
|
540
|
+
if (address === "/")
|
|
541
|
+
return null;
|
|
542
|
+
if (!address.startsWith("/"))
|
|
543
|
+
return `"${address}" does not start with /.`;
|
|
544
|
+
if (address.length > 1024)
|
|
545
|
+
return `"${address.slice(0, 40)}…" is too long.`;
|
|
546
|
+
if (address.endsWith("/"))
|
|
547
|
+
return `"${address}" ends with /; write it without.`;
|
|
548
|
+
for (const segment of address.slice(1).split("/")) {
|
|
549
|
+
if (segment === "" || segment === "." || segment === "..")
|
|
550
|
+
return `"${address}" has an empty or dot segment.`;
|
|
551
|
+
if (segment === "index.html")
|
|
552
|
+
return `"${address}" names index.html; write the address without it.`;
|
|
553
|
+
if (!SEGMENT.test(segment))
|
|
554
|
+
return `"${address}" has a character an address cannot hold.`;
|
|
555
|
+
}
|
|
556
|
+
return null;
|
|
557
|
+
}
|
|
558
|
+
function patternProblem(path) {
|
|
559
|
+
if (path === "/")
|
|
560
|
+
return null;
|
|
561
|
+
const names = new Set;
|
|
562
|
+
for (const segment of path.slice(1).split("/")) {
|
|
563
|
+
const parameter = PARAMETER.exec(segment);
|
|
564
|
+
if (!parameter)
|
|
565
|
+
continue;
|
|
566
|
+
if (names.has(parameter[1]))
|
|
567
|
+
return `"${path}" names :${parameter[1]} twice.`;
|
|
568
|
+
names.add(parameter[1]);
|
|
569
|
+
}
|
|
570
|
+
return siteAddressProblem(path.replace(/\/:[A-Za-z_][A-Za-z0-9_]*/g, "/parameter"));
|
|
571
|
+
}
|
|
572
|
+
function decodeSegment(segment) {
|
|
573
|
+
try {
|
|
574
|
+
return decodeURIComponent(segment);
|
|
575
|
+
} catch {
|
|
576
|
+
return null;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
function matchPattern(pattern, address) {
|
|
580
|
+
if (pattern === "/" || address === "/")
|
|
581
|
+
return pattern === address ? {} : null;
|
|
582
|
+
const want = pattern.slice(1).split("/");
|
|
583
|
+
const have = address.slice(1).split("/");
|
|
584
|
+
if (want.length !== have.length)
|
|
585
|
+
return null;
|
|
586
|
+
const params = {};
|
|
587
|
+
for (let index = 0;index < want.length; index += 1) {
|
|
588
|
+
const parameter = PARAMETER.exec(want[index]);
|
|
589
|
+
if (parameter) {
|
|
590
|
+
const value = decodeSegment(have[index]);
|
|
591
|
+
if (value === null || value === "")
|
|
592
|
+
return null;
|
|
593
|
+
params[parameter[1]] = value;
|
|
594
|
+
} else if (want[index] !== have[index])
|
|
595
|
+
return null;
|
|
596
|
+
}
|
|
597
|
+
return params;
|
|
598
|
+
}
|
|
599
|
+
function fillPattern(pattern, params) {
|
|
600
|
+
return pattern.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, (_, name) => {
|
|
601
|
+
const value = params[name];
|
|
602
|
+
if (typeof value !== "string" || value === "")
|
|
603
|
+
throw new Error(`"${pattern}" needs a value for :${name}.`);
|
|
604
|
+
return encodeURIComponent(value);
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
function moreSpecific(a, b) {
|
|
608
|
+
const left = a.split("/");
|
|
609
|
+
const right = b.split("/");
|
|
610
|
+
for (let index = 0;index < Math.min(left.length, right.length); index += 1) {
|
|
611
|
+
const leftParameter = left[index].startsWith(":");
|
|
612
|
+
const rightParameter = right[index].startsWith(":");
|
|
613
|
+
if (leftParameter !== rightParameter)
|
|
614
|
+
return leftParameter ? 1 : -1;
|
|
615
|
+
}
|
|
616
|
+
return 0;
|
|
617
|
+
}
|
|
618
|
+
function redirectPrefix(from) {
|
|
619
|
+
if (from === "/*")
|
|
620
|
+
return "";
|
|
621
|
+
return from.endsWith("/*") ? from.slice(0, -2) : null;
|
|
622
|
+
}
|
|
623
|
+
function matchRedirect(redirects, address) {
|
|
624
|
+
let best = null;
|
|
625
|
+
for (const redirect of redirects) {
|
|
626
|
+
const prefix = redirectPrefix(redirect.from);
|
|
627
|
+
if (prefix === null) {
|
|
628
|
+
if (redirect.from === address)
|
|
629
|
+
return redirect;
|
|
630
|
+
continue;
|
|
631
|
+
}
|
|
632
|
+
const under = prefix === "" || address === prefix || address.startsWith(`${prefix}/`);
|
|
633
|
+
if (under && (best === null || prefix.length > best.length))
|
|
634
|
+
best = { redirect, length: prefix.length };
|
|
635
|
+
}
|
|
636
|
+
return best?.redirect ?? null;
|
|
637
|
+
}
|
|
638
|
+
function matchAddress(app, address, listed) {
|
|
639
|
+
if (siteAddressProblem(address) !== null)
|
|
640
|
+
return null;
|
|
641
|
+
const redirects = app.redirects ?? [];
|
|
642
|
+
const exactRoute = app.routes.find((route) => route.path === address);
|
|
643
|
+
if (exactRoute)
|
|
644
|
+
return { kind: "route", route: exactRoute, params: {} };
|
|
645
|
+
const exactRedirect = redirects.find((redirect) => redirect.from === address);
|
|
646
|
+
if (exactRedirect)
|
|
647
|
+
return { kind: "redirect", redirect: exactRedirect };
|
|
648
|
+
let found = null;
|
|
649
|
+
if (!listed || listed.has(address))
|
|
650
|
+
for (const route of app.routes) {
|
|
651
|
+
const params = matchPattern(route.path, address);
|
|
652
|
+
if (params && (!found || moreSpecific(route.path, found.route.path) < 0))
|
|
653
|
+
found = { route, params };
|
|
654
|
+
}
|
|
655
|
+
if (found)
|
|
656
|
+
return { kind: "route", ...found };
|
|
657
|
+
const redirect = matchRedirect(redirects, address);
|
|
658
|
+
return redirect ? { kind: "redirect", redirect } : null;
|
|
659
|
+
}
|
|
660
|
+
async function listAddresses(app) {
|
|
661
|
+
const listed = [];
|
|
662
|
+
for (const route of app.routes) {
|
|
663
|
+
const sets = route.path.includes("/:") && route.addresses ? await route.addresses() : [{}];
|
|
664
|
+
for (const params of sets) {
|
|
665
|
+
const address = fillPattern(route.path, params);
|
|
666
|
+
const problem = siteAddressProblem(address);
|
|
667
|
+
if (problem)
|
|
668
|
+
throw new Error(`Route ${route.path}: ${problem}`);
|
|
669
|
+
listed.push({ route, params, address });
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
const addresses = new Set(listed.map((entry) => entry.address));
|
|
673
|
+
const seen = new Set;
|
|
674
|
+
for (const entry of listed) {
|
|
675
|
+
const match = matchAddress(app, entry.address, addresses);
|
|
676
|
+
if (match?.kind !== "route" || match.route !== entry.route)
|
|
677
|
+
throw new Error(`Route ${entry.route.path}: ${entry.address} is served by ${match?.kind === "route" ? `route ${match.route.path}` : "a redirect"}.`);
|
|
678
|
+
if (seen.has(entry.address))
|
|
679
|
+
throw new Error(`Route ${entry.route.path}: ${entry.address} is listed twice.`);
|
|
680
|
+
seen.add(entry.address);
|
|
681
|
+
entry.params = match.params;
|
|
682
|
+
}
|
|
683
|
+
return listed;
|
|
684
|
+
}
|
|
685
|
+
var RESERVED_FILES = new Set([
|
|
686
|
+
"index.html",
|
|
687
|
+
"404.html",
|
|
688
|
+
"sitemap.xml",
|
|
689
|
+
"robots.txt",
|
|
690
|
+
"_site.json"
|
|
691
|
+
]);
|
|
692
|
+
var FILE_TYPES = {
|
|
693
|
+
txt: "text/plain; charset=utf-8",
|
|
694
|
+
md: "text/markdown; charset=utf-8",
|
|
695
|
+
html: "text/html; charset=utf-8",
|
|
696
|
+
xml: "application/xml; charset=utf-8",
|
|
697
|
+
json: "application/json; charset=utf-8",
|
|
698
|
+
webmanifest: "application/manifest+json; charset=utf-8",
|
|
699
|
+
css: "text/css; charset=utf-8",
|
|
700
|
+
svg: "image/svg+xml; charset=utf-8",
|
|
701
|
+
csv: "text/csv; charset=utf-8"
|
|
702
|
+
};
|
|
703
|
+
function siteFileContentType(path) {
|
|
704
|
+
const extension = /\.([a-z0-9]+)$/i.exec(path)?.[1]?.toLowerCase();
|
|
705
|
+
return extension ? FILE_TYPES[extension] ?? null : null;
|
|
706
|
+
}
|
|
707
|
+
var ORIGIN = /^https:\/\/[a-z0-9.-]+(?::\d{1,5})?$/;
|
|
708
|
+
var AUDIENCES = ["members", "public"];
|
|
709
|
+
var PLACE_WORDS = {
|
|
710
|
+
frame: "In Alma",
|
|
711
|
+
public: "At the published address"
|
|
712
|
+
};
|
|
713
|
+
function placeProblems(app, place) {
|
|
714
|
+
const problems = [];
|
|
715
|
+
const there = appIn(app, place);
|
|
716
|
+
const shapes = new Map;
|
|
717
|
+
const paths = new Set;
|
|
718
|
+
for (const route of there.routes) {
|
|
719
|
+
const shape = route.path.replace(/:[A-Za-z_][A-Za-z0-9_]*/g, ":");
|
|
720
|
+
if (shapes.has(shape))
|
|
721
|
+
problems.push(`${PLACE_WORDS[place]}, routes "${shapes.get(shape)}" and "${route.path}" match the same addresses.`);
|
|
722
|
+
shapes.set(shape, route.path);
|
|
723
|
+
paths.add(route.path);
|
|
724
|
+
if (place === "public" && route.path.includes("/:") && !route.addresses)
|
|
725
|
+
problems.push(`Route "${route.path}" has parameters and is public, so it must list its addresses.`);
|
|
726
|
+
if (place === "public" && typeof route.meta !== "function")
|
|
727
|
+
problems.push(`Route "${route.path}" is public, so it needs meta (its title at the published address).`);
|
|
728
|
+
}
|
|
729
|
+
for (const redirect of app.redirects ?? [])
|
|
730
|
+
if (paths.has(redirect.from))
|
|
731
|
+
problems.push(`"${redirect.from}" is both a route and a redirect.`);
|
|
732
|
+
if (place === "public" && there.routes.length === 0)
|
|
733
|
+
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.`);
|
|
734
|
+
else if (place === "public" && !app.meta?.name)
|
|
735
|
+
problems.push("The app's meta needs a name to be published.");
|
|
736
|
+
return problems;
|
|
737
|
+
}
|
|
738
|
+
function appDefinitionProblems(app, places = ["frame", "public"]) {
|
|
739
|
+
const problems = [];
|
|
740
|
+
if (!Array.isArray(app.routes))
|
|
741
|
+
return ["The app must list its routes: defineApp({ routes: [...] })."];
|
|
742
|
+
for (const route of app.routes) {
|
|
743
|
+
const problem = patternProblem(route.path);
|
|
744
|
+
if (problem)
|
|
745
|
+
problems.push(`Route ${problem}`);
|
|
746
|
+
if (route.audience !== undefined && !AUDIENCES.includes(route.audience))
|
|
747
|
+
problems.push(`Route "${route.path}": its audience is "members" or "public", or left out for both.`);
|
|
748
|
+
}
|
|
749
|
+
for (const place of places)
|
|
750
|
+
problems.push(...placeProblems(app, place));
|
|
751
|
+
const froms = new Set;
|
|
752
|
+
for (const redirect of app.redirects ?? []) {
|
|
753
|
+
const prefix = redirectPrefix(redirect.from);
|
|
754
|
+
const problem = prefix === "" ? null : siteAddressProblem(prefix ?? redirect.from);
|
|
755
|
+
if (problem)
|
|
756
|
+
problems.push(`Redirect ${problem}`);
|
|
757
|
+
if (froms.has(redirect.from))
|
|
758
|
+
problems.push(`Two redirects move "${redirect.from}".`);
|
|
759
|
+
froms.add(redirect.from);
|
|
760
|
+
if (!SITE_REDIRECT_STATUSES.includes(redirect.status))
|
|
761
|
+
problems.push(`Redirect "${redirect.from}" must be a 301, 302, 307 or 308.`);
|
|
762
|
+
const external = redirect.to.startsWith("https://");
|
|
763
|
+
if (!external && siteAddressProblem(redirect.to) !== null)
|
|
764
|
+
problems.push(`Redirect "${redirect.from}" must go to an address of this app or an https URL.`);
|
|
765
|
+
if (!external && redirect.to === redirect.from)
|
|
766
|
+
problems.push(`Redirect "${redirect.from}" goes to itself.`);
|
|
767
|
+
}
|
|
768
|
+
for (const origin of app.embeds ?? [])
|
|
769
|
+
if (!ORIGIN.test(origin))
|
|
770
|
+
problems.push(`Embed "${origin}" must be an https origin, such as https://calendar.google.com.`);
|
|
771
|
+
for (const path of Object.keys(app.files ?? {})) {
|
|
772
|
+
const segments = path.split("/");
|
|
773
|
+
if (path.startsWith("/") || segments.some((segment) => segment === "" || segment === "." || segment === "..") || /^_(assets|files|alma)$/.test(segments[0]) || RESERVED_FILES.has(path))
|
|
774
|
+
problems.push(`File "${path}" cannot be declared.`);
|
|
775
|
+
else if (siteFileContentType(path) === null)
|
|
776
|
+
problems.push(`File "${path}" has an extension the published address cannot serve.`);
|
|
777
|
+
}
|
|
778
|
+
return [...new Set(problems)];
|
|
779
|
+
}
|
|
780
|
+
function isSiteFileAddress(app, address) {
|
|
781
|
+
if (!app.files || address === "/" || !address.startsWith("/"))
|
|
782
|
+
return false;
|
|
783
|
+
const path = address.slice(1);
|
|
784
|
+
return Object.hasOwn(app.files, path) || Object.hasOwn(app.files, `${path}/index.html`);
|
|
785
|
+
}
|
|
786
|
+
function outputPathOf(address) {
|
|
787
|
+
return address === "/" ? "index.html" : `${address.slice(1)}/index.html`;
|
|
788
|
+
}
|
|
789
|
+
function absoluteUrl(origin, path) {
|
|
790
|
+
return /^https?:\/\//.test(path) ? path : `${origin}${path}`;
|
|
791
|
+
}
|
|
792
|
+
function escapeHtml(text) {
|
|
793
|
+
return text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
794
|
+
}
|
|
795
|
+
function scriptJson(value) {
|
|
796
|
+
return JSON.stringify(value).replaceAll("<", "\\u003c").replaceAll(">", "\\u003e").replaceAll("&", "\\u0026").replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
|
|
797
|
+
}
|
|
798
|
+
function pageTitle(app, meta) {
|
|
799
|
+
return app.titleTemplate && !meta.absoluteTitle ? app.titleTemplate.replace("%s", meta.title) : meta.title;
|
|
800
|
+
}
|
|
801
|
+
function buildDocumentHead(input) {
|
|
802
|
+
const { app, meta, origin } = input;
|
|
803
|
+
const title = pageTitle(app, meta);
|
|
804
|
+
const description = meta.description ?? app.description;
|
|
805
|
+
const canonical = absoluteUrl(origin, meta.canonical ?? input.address);
|
|
806
|
+
const ogTitle = meta.openGraph?.title ?? app.openGraph?.title ?? meta.title;
|
|
807
|
+
const ogDescription = meta.openGraph?.description ?? app.openGraph?.description ?? description;
|
|
808
|
+
const twitterTitle = meta.x?.title ?? app.x?.title ?? meta.title;
|
|
809
|
+
const twitterDescription = meta.x?.description ?? app.x?.description ?? description;
|
|
810
|
+
const pageImage = meta.openGraph?.image ?? meta.image;
|
|
811
|
+
const image = pageImage ?? app.image;
|
|
812
|
+
const imageAlt = pageImage ? meta.imageAlt : app.imageAlt;
|
|
813
|
+
const twitterImage = meta.image ?? app.image;
|
|
814
|
+
const tag = (name, attributes) => `<${name} ${Object.entries(attributes).map(([key, value]) => `${key}="${escapeHtml(value)}"`).join(" ")}>`;
|
|
815
|
+
const property = (key, content) => tag("meta", { property: key, content });
|
|
816
|
+
const named = (key, content) => tag("meta", { name: key, content });
|
|
817
|
+
const head = [`<title>${escapeHtml(title)}</title>`];
|
|
818
|
+
if (description)
|
|
819
|
+
head.push(named("description", description));
|
|
820
|
+
if (meta.noindex)
|
|
821
|
+
head.push(named("robots", "noindex"));
|
|
822
|
+
else
|
|
823
|
+
head.push(tag("link", { rel: "canonical", href: canonical }));
|
|
824
|
+
head.push(property("og:title", ogTitle), property("og:type", meta.type ?? "website"));
|
|
825
|
+
if (!meta.noindex)
|
|
826
|
+
head.push(property("og:url", canonical));
|
|
827
|
+
head.push(property("og:site_name", app.name));
|
|
828
|
+
if (ogDescription)
|
|
829
|
+
head.push(property("og:description", ogDescription));
|
|
830
|
+
if (app.locale)
|
|
831
|
+
head.push(property("og:locale", app.locale));
|
|
832
|
+
if (image) {
|
|
833
|
+
head.push(property("og:image", absoluteUrl(origin, image)));
|
|
834
|
+
if (!pageImage && app.imageWidth && app.imageHeight)
|
|
835
|
+
head.push(property("og:image:width", String(app.imageWidth)), property("og:image:height", String(app.imageHeight)));
|
|
836
|
+
if (imageAlt)
|
|
837
|
+
head.push(property("og:image:alt", imageAlt));
|
|
838
|
+
}
|
|
839
|
+
head.push(named("twitter:card", twitterImage ? "summary_large_image" : "summary"));
|
|
840
|
+
head.push(named("twitter:title", twitterTitle));
|
|
841
|
+
if (twitterDescription)
|
|
842
|
+
head.push(named("twitter:description", twitterDescription));
|
|
843
|
+
if (twitterImage)
|
|
844
|
+
head.push(named("twitter:image", absoluteUrl(origin, twitterImage)));
|
|
845
|
+
if (app.twitter)
|
|
846
|
+
head.push(named("twitter:site", app.twitter));
|
|
847
|
+
if (typeof app.favicon === "string")
|
|
848
|
+
head.push(tag("link", { rel: "icon", href: app.favicon }));
|
|
849
|
+
else if (app.favicon)
|
|
850
|
+
head.push(tag("link", {
|
|
851
|
+
rel: "icon",
|
|
852
|
+
href: app.favicon.light,
|
|
853
|
+
media: "(prefers-color-scheme: light)"
|
|
854
|
+
}), tag("link", {
|
|
855
|
+
rel: "icon",
|
|
856
|
+
href: app.favicon.dark,
|
|
857
|
+
media: "(prefers-color-scheme: dark)"
|
|
858
|
+
}));
|
|
859
|
+
if (typeof app.themeColor === "string")
|
|
860
|
+
head.push(named("theme-color", app.themeColor));
|
|
861
|
+
else if (app.themeColor)
|
|
862
|
+
head.push(tag("meta", {
|
|
863
|
+
name: "theme-color",
|
|
864
|
+
content: app.themeColor.light,
|
|
865
|
+
media: "(prefers-color-scheme: light)"
|
|
866
|
+
}), tag("meta", {
|
|
867
|
+
name: "theme-color",
|
|
868
|
+
content: app.themeColor.dark,
|
|
869
|
+
media: "(prefers-color-scheme: dark)"
|
|
870
|
+
}));
|
|
871
|
+
for (const font of input.fonts ?? [])
|
|
872
|
+
head.push(tag("link", {
|
|
873
|
+
rel: "preload",
|
|
874
|
+
href: font.href,
|
|
875
|
+
as: "font",
|
|
876
|
+
type: font.type ?? "font/woff2",
|
|
877
|
+
crossorigin: ""
|
|
878
|
+
}));
|
|
879
|
+
for (const jsonLd of [app.jsonLd ?? [], meta.jsonLd ?? []].flat())
|
|
880
|
+
head.push(`<script type="application/ld+json">${scriptJson(jsonLd)}</script>`);
|
|
881
|
+
return head.join(`
|
|
882
|
+
`);
|
|
883
|
+
}
|
|
884
|
+
function buildSitemap(origin, entries) {
|
|
885
|
+
const urls = entries.map((entry) => {
|
|
886
|
+
const lines = [
|
|
887
|
+
`<loc>${escapeHtml(absoluteUrl(origin, entry.address))}</loc>`
|
|
888
|
+
];
|
|
889
|
+
if (entry.lastModified)
|
|
890
|
+
lines.push(`<lastmod>${escapeHtml(entry.lastModified)}</lastmod>`);
|
|
891
|
+
if (entry.changeFrequency)
|
|
892
|
+
lines.push(`<changefreq>${entry.changeFrequency}</changefreq>`);
|
|
893
|
+
if (entry.priority !== undefined)
|
|
894
|
+
lines.push(`<priority>${Math.min(1, Math.max(0, entry.priority)).toFixed(1)}</priority>`);
|
|
895
|
+
return `<url>${lines.join("")}</url>`;
|
|
896
|
+
});
|
|
897
|
+
return [
|
|
898
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
899
|
+
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
|
|
900
|
+
...urls,
|
|
901
|
+
"</urlset>",
|
|
902
|
+
""
|
|
903
|
+
].join(`
|
|
904
|
+
`);
|
|
905
|
+
}
|
|
906
|
+
function buildRobots(origin, robots = {}) {
|
|
907
|
+
return [
|
|
908
|
+
"User-agent: *",
|
|
909
|
+
...robots.disallow?.length ? robots.disallow.map((path) => `Disallow: ${path}`) : ["Allow: /"],
|
|
910
|
+
"",
|
|
911
|
+
`Sitemap: ${origin}/sitemap.xml`,
|
|
912
|
+
""
|
|
913
|
+
].join(`
|
|
914
|
+
`);
|
|
915
|
+
}
|
|
916
|
+
|
|
129
917
|
// src/index.ts
|
|
130
918
|
var FINISHED = [
|
|
131
919
|
"completed",
|
|
132
920
|
"failed",
|
|
133
921
|
"cancelled"
|
|
134
922
|
];
|
|
135
|
-
class AppCallError extends Error {
|
|
136
|
-
code;
|
|
137
|
-
current;
|
|
138
|
-
constructor(message, detail = {}) {
|
|
139
|
-
super(message);
|
|
140
|
-
this.name = "AppCallError";
|
|
141
|
-
this.code = detail.code;
|
|
142
|
-
this.current = detail.current;
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
923
|
function isFieldChanged(error) {
|
|
146
924
|
return error instanceof Error && error.code === "field.changed" && error.current !== undefined;
|
|
147
925
|
}
|
|
@@ -156,6 +934,7 @@ var SHELL_QUESTION = "getAppShell";
|
|
|
156
934
|
var SHELL_WAIT_MS = 3000;
|
|
157
935
|
var WATCH_QUESTION = "watchTopicChanges";
|
|
158
936
|
var WATCH_WAIT_MS = 5000;
|
|
937
|
+
var FILE_WAIT_MS = 120000;
|
|
159
938
|
var WATCH_TYPES_QUESTION = "watchTypeChanges";
|
|
160
939
|
var PUSHED_REREAD_MS = 300000;
|
|
161
940
|
var CATCH_UP_OVERLAP_MS = 60000;
|
|
@@ -171,6 +950,7 @@ var WATCH_BROADCASTS_QUESTION = "watchBroadcasts";
|
|
|
171
950
|
var BROADCAST_MESSAGE = "alma:broadcast";
|
|
172
951
|
var BROADCAST_EVENT = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
173
952
|
var oneRequest = () => crypto.randomUUID();
|
|
953
|
+
var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
174
954
|
function createAppSdk(transport) {
|
|
175
955
|
const read = new Map;
|
|
176
956
|
const precondition = (topicId, fieldKey, options) => {
|
|
@@ -185,6 +965,20 @@ function createAppSdk(transport) {
|
|
|
185
965
|
const revision = fields[fieldKey];
|
|
186
966
|
return revision === undefined ? { if_value: null } : { if_revision: revision };
|
|
187
967
|
};
|
|
968
|
+
let types = null;
|
|
969
|
+
const typeIdOf = async (typeKey) => {
|
|
970
|
+
types ??= transport.call("listTopicTypes").catch((error) => {
|
|
971
|
+
types = null;
|
|
972
|
+
throw error;
|
|
973
|
+
});
|
|
974
|
+
const named = (await types).filter((type) => type.key === typeKey);
|
|
975
|
+
const found = named.find((type) => type.schema.kind === "app") ?? (named.length === 1 ? named[0] : undefined);
|
|
976
|
+
if (!found)
|
|
977
|
+
throw new AppCallError(`This app reads no one type "${typeKey}".`, {
|
|
978
|
+
code: "type.not_found"
|
|
979
|
+
});
|
|
980
|
+
return found.id;
|
|
981
|
+
};
|
|
188
982
|
const getExecution = (executionId) => transport.call("getExecution", {
|
|
189
983
|
params: { id: executionId }
|
|
190
984
|
});
|
|
@@ -496,8 +1290,11 @@ function createAppSdk(transport) {
|
|
|
496
1290
|
params: { key },
|
|
497
1291
|
query: { type, cursor: page.cursor, limit: page.limit }
|
|
498
1292
|
}),
|
|
499
|
-
getTopicRecord: async (topicId) => {
|
|
500
|
-
const record = await transport.call("getTopicRecord", {
|
|
1293
|
+
getTopicRecord: async (topicId, options = {}) => {
|
|
1294
|
+
const record = await transport.call("getTopicRecord", {
|
|
1295
|
+
params: { id: topicId },
|
|
1296
|
+
...options.type ? { query: { type: options.type } } : {}
|
|
1297
|
+
});
|
|
501
1298
|
if (record.revisions)
|
|
502
1299
|
read.set(topicId, { ...record.revisions });
|
|
503
1300
|
return record;
|
|
@@ -569,10 +1366,11 @@ function createAppSdk(transport) {
|
|
|
569
1366
|
},
|
|
570
1367
|
createTopic: async (name, topicTypeId, options = {}) => {
|
|
571
1368
|
const fields = options.fields ?? [];
|
|
1369
|
+
const typeId = topicTypeId && !UUID2.test(topicTypeId) && transport.place !== "public" ? await typeIdOf(topicTypeId) : topicTypeId;
|
|
572
1370
|
const created = await transport.call("createTopic", {
|
|
573
1371
|
body: {
|
|
574
1372
|
name,
|
|
575
|
-
...
|
|
1373
|
+
...typeId ? { topic_type_id: typeId } : {},
|
|
576
1374
|
...fields.length > 0 ? {
|
|
577
1375
|
fields: fields.map((field) => ({
|
|
578
1376
|
key: field.key,
|
|
@@ -648,6 +1446,66 @@ function createAppSdk(transport) {
|
|
|
648
1446
|
body: { event, ...payload ? { payload } : {} },
|
|
649
1447
|
idempotencyKey: options.idempotencyKey ?? oneRequest()
|
|
650
1448
|
}),
|
|
1449
|
+
result: (token) => {
|
|
1450
|
+
if (!transport.result)
|
|
1451
|
+
return Promise.reject(new AppCallError("This app has no event results to read.", {
|
|
1452
|
+
code: "result.unavailable"
|
|
1453
|
+
}));
|
|
1454
|
+
return transport.result(token);
|
|
1455
|
+
},
|
|
1456
|
+
fileUrl: (name) => {
|
|
1457
|
+
const fileUrl = transport.fileUrl?.bind(transport);
|
|
1458
|
+
if (!fileUrl)
|
|
1459
|
+
return Promise.reject(new AppCallError("This app has no files to show.", {
|
|
1460
|
+
code: "file.unavailable"
|
|
1461
|
+
}));
|
|
1462
|
+
return new Promise((resolve) => resolve(fileUrl(name)));
|
|
1463
|
+
},
|
|
1464
|
+
ownEntry: async (hash) => {
|
|
1465
|
+
if (!transport.result)
|
|
1466
|
+
throw new AppCallError("This app has no event results to read.", {
|
|
1467
|
+
code: "result.unavailable"
|
|
1468
|
+
});
|
|
1469
|
+
const token = readResultToken(hash);
|
|
1470
|
+
if (token === null)
|
|
1471
|
+
return null;
|
|
1472
|
+
const answer = await transport.result(token);
|
|
1473
|
+
if (answer.status === "pending")
|
|
1474
|
+
return answer;
|
|
1475
|
+
if (!isOwnEntry(answer.result))
|
|
1476
|
+
throw new AppCallError("This private link names no entry.", {
|
|
1477
|
+
code: "result.not_entry"
|
|
1478
|
+
});
|
|
1479
|
+
return { status: "ready", ...answer.result };
|
|
1480
|
+
},
|
|
1481
|
+
waitForResult: async (token, options = {}) => {
|
|
1482
|
+
const read = transport.result?.bind(transport);
|
|
1483
|
+
if (!read)
|
|
1484
|
+
throw new AppCallError("This app has no event results to read.", {
|
|
1485
|
+
code: "result.unavailable"
|
|
1486
|
+
});
|
|
1487
|
+
const deadline = Date.now() + (options.timeoutMs ?? 120000);
|
|
1488
|
+
let delay = 1000;
|
|
1489
|
+
for (;; ) {
|
|
1490
|
+
options.signal?.throwIfAborted();
|
|
1491
|
+
const answer = await read(token);
|
|
1492
|
+
if (answer.status === "ready")
|
|
1493
|
+
return answer.result;
|
|
1494
|
+
const left = deadline - Date.now();
|
|
1495
|
+
if (left <= 0)
|
|
1496
|
+
throw new AppCallError("The result is not ready yet.", {
|
|
1497
|
+
code: "result.timeout"
|
|
1498
|
+
});
|
|
1499
|
+
await new Promise((resolve, reject) => {
|
|
1500
|
+
const timer = setTimeout(resolve, Math.min(delay, left));
|
|
1501
|
+
options.signal?.addEventListener("abort", () => {
|
|
1502
|
+
clearTimeout(timer);
|
|
1503
|
+
reject(options.signal?.reason);
|
|
1504
|
+
}, { once: true });
|
|
1505
|
+
});
|
|
1506
|
+
delay = Math.min(delay * 2, 8000);
|
|
1507
|
+
}
|
|
1508
|
+
},
|
|
651
1509
|
state: {
|
|
652
1510
|
get: async (key) => {
|
|
653
1511
|
const entry = await transport.call("getAppState", { params: { key } });
|
|
@@ -679,6 +1537,7 @@ function createAppSdk(transport) {
|
|
|
679
1537
|
const seen = new Map;
|
|
680
1538
|
let toldWhileReading = null;
|
|
681
1539
|
let watch = null;
|
|
1540
|
+
let pushed = false;
|
|
682
1541
|
let stopped = false;
|
|
683
1542
|
let delay = every;
|
|
684
1543
|
let timer;
|
|
@@ -737,7 +1596,7 @@ function createAppSdk(transport) {
|
|
|
737
1596
|
const tick = async () => {
|
|
738
1597
|
try {
|
|
739
1598
|
const changed = await readAll();
|
|
740
|
-
if (
|
|
1599
|
+
if (pushed)
|
|
741
1600
|
return PUSHED_REREAD_MS;
|
|
742
1601
|
delay = changed ? every : Math.min(delay * 2, 60000);
|
|
743
1602
|
} catch {
|
|
@@ -766,8 +1625,10 @@ function createAppSdk(transport) {
|
|
|
766
1625
|
const heard = (told) => {
|
|
767
1626
|
if (stopped)
|
|
768
1627
|
return;
|
|
769
|
-
if ("missed" in told)
|
|
1628
|
+
if ("missed" in told) {
|
|
1629
|
+
pushed = true;
|
|
770
1630
|
return read();
|
|
1631
|
+
}
|
|
771
1632
|
toldWhileReading?.add(told.key);
|
|
772
1633
|
if ("exists" in told)
|
|
773
1634
|
tellDeleted(told.key, told.revision);
|
|
@@ -789,6 +1650,8 @@ function createAppSdk(transport) {
|
|
|
789
1650
|
asked?.stop();
|
|
790
1651
|
else
|
|
791
1652
|
watch = asked ?? null;
|
|
1653
|
+
if (watch?.watching)
|
|
1654
|
+
pushed = true;
|
|
792
1655
|
read();
|
|
793
1656
|
})();
|
|
794
1657
|
return () => {
|
|
@@ -826,7 +1689,11 @@ function createAppSdk(transport) {
|
|
|
826
1689
|
let watch = null;
|
|
827
1690
|
(async () => {
|
|
828
1691
|
const asked = await transport.watchBroadcasts?.((message) => {
|
|
829
|
-
if (stopped
|
|
1692
|
+
if (stopped)
|
|
1693
|
+
return;
|
|
1694
|
+
if ("missed" in message)
|
|
1695
|
+
return options.missed?.();
|
|
1696
|
+
if (message.event !== event)
|
|
830
1697
|
return;
|
|
831
1698
|
if (message.self && !options.self)
|
|
832
1699
|
return;
|
|
@@ -913,6 +1780,8 @@ function broadcastTold(told) {
|
|
|
913
1780
|
const message = told;
|
|
914
1781
|
if (message["type"] !== BROADCAST_MESSAGE)
|
|
915
1782
|
return null;
|
|
1783
|
+
if (message["missed"] === true)
|
|
1784
|
+
return { missed: true };
|
|
916
1785
|
const { event } = message;
|
|
917
1786
|
if (typeof event !== "string" || !BROADCAST_EVENT.test(event))
|
|
918
1787
|
return null;
|
|
@@ -1029,6 +1898,7 @@ function hostTransport() {
|
|
|
1029
1898
|
return { watching: [], stop };
|
|
1030
1899
|
}
|
|
1031
1900
|
};
|
|
1901
|
+
const files2 = new Map;
|
|
1032
1902
|
return {
|
|
1033
1903
|
call: (operationId, request = {}) => ask(operationId, request),
|
|
1034
1904
|
viewer: async () => {
|
|
@@ -1040,6 +1910,28 @@ function hostTransport() {
|
|
|
1040
1910
|
const told = await ask(SHELL_QUESTION, {}, SHELL_WAIT_MS);
|
|
1041
1911
|
return isAppShell(told) ? told : null;
|
|
1042
1912
|
},
|
|
1913
|
+
fileUrl: (name) => {
|
|
1914
|
+
if (!isAppFileName(name))
|
|
1915
|
+
return Promise.reject(new AppCallError(`"${name}" is not a file name.`, {
|
|
1916
|
+
code: "file.invalid_name"
|
|
1917
|
+
}));
|
|
1918
|
+
let url = files2.get(name);
|
|
1919
|
+
if (!url) {
|
|
1920
|
+
url = ask(APP_FILE_QUESTION, { body: { name } }, FILE_WAIT_MS).then((told) => {
|
|
1921
|
+
const answer = typeof told === "object" && told !== null ? told : {};
|
|
1922
|
+
const bytes = answer["bytes"];
|
|
1923
|
+
const mediaType = answer["media_type"];
|
|
1924
|
+
if (!(bytes instanceof ArrayBuffer) || typeof mediaType !== "string")
|
|
1925
|
+
throw new AppCallError("The host sent no file.", {
|
|
1926
|
+
code: "file.unavailable"
|
|
1927
|
+
});
|
|
1928
|
+
return URL.createObjectURL(new Blob([bytes], { type: mediaType }));
|
|
1929
|
+
});
|
|
1930
|
+
files2.set(name, url);
|
|
1931
|
+
url.catch(() => files2.delete(name));
|
|
1932
|
+
}
|
|
1933
|
+
return url;
|
|
1934
|
+
},
|
|
1043
1935
|
watch: (topicIds, changed) => watchFor(WATCH_QUESTION, "topic_ids", topicChanges, topicIds, changed),
|
|
1044
1936
|
watchTypes: (typeIds, changed) => watchFor(WATCH_TYPES_QUESTION, "type_ids", typeChanges, typeIds, changed),
|
|
1045
1937
|
watchShared: async (told) => {
|
|
@@ -1047,10 +1939,12 @@ function hostTransport() {
|
|
|
1047
1939
|
const stop = () => sharedChanges.delete(told);
|
|
1048
1940
|
try {
|
|
1049
1941
|
const answer = await ask(WATCH_SHARED_QUESTION, {}, WATCH_WAIT_MS);
|
|
1050
|
-
const
|
|
1051
|
-
|
|
1942
|
+
const said = typeof answer === "object" && answer !== null ? answer : {};
|
|
1943
|
+
const watching = said["watching"] === true;
|
|
1944
|
+
const joining = !watching && said["joining"] === true;
|
|
1945
|
+
if (!watching && !joining)
|
|
1052
1946
|
stop();
|
|
1053
|
-
return { watching, stop };
|
|
1947
|
+
return { watching, joining, stop };
|
|
1054
1948
|
} catch {
|
|
1055
1949
|
stop();
|
|
1056
1950
|
return { watching: false, stop };
|
|
@@ -1094,23 +1988,66 @@ function hostTransport() {
|
|
|
1094
1988
|
};
|
|
1095
1989
|
}
|
|
1096
1990
|
export {
|
|
1991
|
+
APP_FILE_QUESTION,
|
|
1097
1992
|
AppCallError,
|
|
1098
1993
|
BROADCAST_MESSAGE,
|
|
1994
|
+
DEFAULT_THEME_SCRIPT,
|
|
1995
|
+
NOT_FOUND_ROUTE_ID,
|
|
1996
|
+
OPEN_FILE_MESSAGE,
|
|
1997
|
+
OPEN_FILE_TEXT_LIMIT,
|
|
1998
|
+
OPEN_URL_MESSAGE,
|
|
1099
1999
|
PRESENCE_MESSAGE,
|
|
2000
|
+
PUBLIC_RECORD_SHAPE,
|
|
2001
|
+
PUBLISHED_SITE_ATTRIBUTE,
|
|
1100
2002
|
SHARED_STATE_MESSAGE,
|
|
1101
2003
|
SHELL_QUESTION,
|
|
2004
|
+
SITE_ORIGIN_TOKEN,
|
|
2005
|
+
SITE_REDIRECT_STATUSES,
|
|
2006
|
+
SiteRefusalError,
|
|
1102
2007
|
VIEWER_QUESTION,
|
|
1103
2008
|
WATCH_BROADCASTS_QUESTION,
|
|
1104
2009
|
WATCH_PRESENCE_QUESTION,
|
|
1105
2010
|
WATCH_QUESTION,
|
|
1106
2011
|
WATCH_SHARED_QUESTION,
|
|
1107
2012
|
WATCH_TYPES_QUESTION,
|
|
2013
|
+
absoluteUrl,
|
|
2014
|
+
appDefinitionProblems,
|
|
2015
|
+
appFileNameOf,
|
|
2016
|
+
appIn,
|
|
2017
|
+
appPlace,
|
|
1108
2018
|
applicationPath,
|
|
2019
|
+
buildDocumentHead,
|
|
2020
|
+
buildRobots,
|
|
2021
|
+
buildSitemap,
|
|
1109
2022
|
createAppSdk,
|
|
2023
|
+
defineApp,
|
|
2024
|
+
defineRoute,
|
|
2025
|
+
escapeHtml,
|
|
2026
|
+
fillPattern,
|
|
1110
2027
|
hostEvents,
|
|
1111
2028
|
hostNavigation,
|
|
1112
2029
|
hostTransport,
|
|
2030
|
+
isAppFileName,
|
|
1113
2031
|
isFieldChanged,
|
|
2032
|
+
isNotFound,
|
|
2033
|
+
isOwnEntry,
|
|
1114
2034
|
isSharedStateConflict,
|
|
1115
|
-
|
|
2035
|
+
isSiteFileAddress,
|
|
2036
|
+
isSiteRefusal,
|
|
2037
|
+
listAddresses,
|
|
2038
|
+
matchAddress,
|
|
2039
|
+
matchPattern,
|
|
2040
|
+
matchRedirect,
|
|
2041
|
+
notFound,
|
|
2042
|
+
outputPathOf,
|
|
2043
|
+
outsideUrl,
|
|
2044
|
+
pageTitle,
|
|
2045
|
+
parseAppHostEvent,
|
|
2046
|
+
publishedSite,
|
|
2047
|
+
readResultToken,
|
|
2048
|
+
scriptJson,
|
|
2049
|
+
siteAddressProblem,
|
|
2050
|
+
siteFileContentType,
|
|
2051
|
+
siteNavigation,
|
|
2052
|
+
siteTransport
|
|
1116
2053
|
};
|