@almateam/app-sdk 0.9.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 +90 -45
- package/app.d.ts +297 -0
- package/cli.js +307 -10
- package/files.d.ts +25 -0
- package/index.d.ts +49 -5
- package/index.js +570 -234
- package/navigation.d.ts +44 -2
- package/package.json +1 -1
- package/siteRuntime.d.ts +41 -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,342 @@ 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
|
+
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
|
|
141
507
|
var SITE_ORIGIN_TOKEN = "__ALMA_SITE_ORIGIN__";
|
|
142
|
-
var
|
|
508
|
+
var NOT_FOUND_ROUTE_ID = "404";
|
|
509
|
+
var AUDIENCE_OF_PLACE = {
|
|
510
|
+
frame: "members",
|
|
511
|
+
public: "public"
|
|
512
|
+
};
|
|
143
513
|
var SITE_REDIRECT_STATUSES = [301, 302, 307, 308];
|
|
144
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"})()';
|
|
145
|
-
function
|
|
146
|
-
return
|
|
515
|
+
function defineApp(app) {
|
|
516
|
+
return app;
|
|
147
517
|
}
|
|
148
|
-
function
|
|
149
|
-
return
|
|
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
|
+
};
|
|
150
527
|
}
|
|
151
528
|
var NOT_FOUND = Symbol.for("alma.site.notFound");
|
|
152
529
|
function notFound() {
|
|
153
|
-
const error = new Error("This address has no
|
|
530
|
+
const error = new Error("This address has no route.");
|
|
154
531
|
error[NOT_FOUND] = true;
|
|
155
532
|
return error;
|
|
156
533
|
}
|
|
@@ -258,48 +635,48 @@ function matchRedirect(redirects, address) {
|
|
|
258
635
|
}
|
|
259
636
|
return best?.redirect ?? null;
|
|
260
637
|
}
|
|
261
|
-
function matchAddress(
|
|
638
|
+
function matchAddress(app, address, listed) {
|
|
262
639
|
if (siteAddressProblem(address) !== null)
|
|
263
640
|
return null;
|
|
264
|
-
const redirects =
|
|
265
|
-
const
|
|
266
|
-
if (
|
|
267
|
-
return { kind: "
|
|
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: {} };
|
|
268
645
|
const exactRedirect = redirects.find((redirect) => redirect.from === address);
|
|
269
646
|
if (exactRedirect)
|
|
270
647
|
return { kind: "redirect", redirect: exactRedirect };
|
|
271
648
|
let found = null;
|
|
272
649
|
if (!listed || listed.has(address))
|
|
273
|
-
for (const
|
|
274
|
-
const params = matchPattern(
|
|
275
|
-
if (params && (!found || moreSpecific(
|
|
276
|
-
found = {
|
|
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 };
|
|
277
654
|
}
|
|
278
655
|
if (found)
|
|
279
|
-
return { kind: "
|
|
656
|
+
return { kind: "route", ...found };
|
|
280
657
|
const redirect = matchRedirect(redirects, address);
|
|
281
658
|
return redirect ? { kind: "redirect", redirect } : null;
|
|
282
659
|
}
|
|
283
|
-
async function listAddresses(
|
|
660
|
+
async function listAddresses(app) {
|
|
284
661
|
const listed = [];
|
|
285
|
-
for (const
|
|
286
|
-
const sets =
|
|
662
|
+
for (const route of app.routes) {
|
|
663
|
+
const sets = route.path.includes("/:") && route.addresses ? await route.addresses() : [{}];
|
|
287
664
|
for (const params of sets) {
|
|
288
|
-
const address = fillPattern(
|
|
665
|
+
const address = fillPattern(route.path, params);
|
|
289
666
|
const problem = siteAddressProblem(address);
|
|
290
667
|
if (problem)
|
|
291
|
-
throw new Error(`
|
|
292
|
-
listed.push({
|
|
668
|
+
throw new Error(`Route ${route.path}: ${problem}`);
|
|
669
|
+
listed.push({ route, params, address });
|
|
293
670
|
}
|
|
294
671
|
}
|
|
295
672
|
const addresses = new Set(listed.map((entry) => entry.address));
|
|
296
673
|
const seen = new Set;
|
|
297
674
|
for (const entry of listed) {
|
|
298
|
-
const match = matchAddress(
|
|
299
|
-
if (match?.kind !== "
|
|
300
|
-
throw new Error(`
|
|
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"}.`);
|
|
301
678
|
if (seen.has(entry.address))
|
|
302
|
-
throw new Error(`
|
|
679
|
+
throw new Error(`Route ${entry.route.path}: ${entry.address} is listed twice.`);
|
|
303
680
|
seen.add(entry.address);
|
|
304
681
|
entry.params = match.params;
|
|
305
682
|
}
|
|
@@ -328,26 +705,51 @@ function siteFileContentType(path) {
|
|
|
328
705
|
return extension ? FILE_TYPES[extension] ?? null : null;
|
|
329
706
|
}
|
|
330
707
|
var ORIGIN = /^https:\/\/[a-z0-9.-]+(?::\d{1,5})?$/;
|
|
331
|
-
|
|
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) {
|
|
332
714
|
const problems = [];
|
|
333
|
-
|
|
334
|
-
problems.push("The site's meta needs a name.");
|
|
335
|
-
const paths = new Set;
|
|
715
|
+
const there = appIn(app, place);
|
|
336
716
|
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, ":");
|
|
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, ":");
|
|
342
720
|
if (shapes.has(shape))
|
|
343
|
-
problems.push(
|
|
344
|
-
shapes.set(shape,
|
|
345
|
-
paths.add(
|
|
346
|
-
if (
|
|
347
|
-
problems.push(`
|
|
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).`);
|
|
348
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));
|
|
349
751
|
const froms = new Set;
|
|
350
|
-
for (const redirect of
|
|
752
|
+
for (const redirect of app.redirects ?? []) {
|
|
351
753
|
const prefix = redirectPrefix(redirect.from);
|
|
352
754
|
const problem = prefix === "" ? null : siteAddressProblem(prefix ?? redirect.from);
|
|
353
755
|
if (problem)
|
|
@@ -357,31 +759,29 @@ function siteDefinitionProblems(site) {
|
|
|
357
759
|
froms.add(redirect.from);
|
|
358
760
|
if (!SITE_REDIRECT_STATUSES.includes(redirect.status))
|
|
359
761
|
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
762
|
const external = redirect.to.startsWith("https://");
|
|
363
763
|
if (!external && siteAddressProblem(redirect.to) !== null)
|
|
364
|
-
problems.push(`Redirect "${redirect.from}" must go to an address
|
|
764
|
+
problems.push(`Redirect "${redirect.from}" must go to an address of this app or an https URL.`);
|
|
365
765
|
if (!external && redirect.to === redirect.from)
|
|
366
766
|
problems.push(`Redirect "${redirect.from}" goes to itself.`);
|
|
367
767
|
}
|
|
368
|
-
for (const origin of
|
|
768
|
+
for (const origin of app.embeds ?? [])
|
|
369
769
|
if (!ORIGIN.test(origin))
|
|
370
770
|
problems.push(`Embed "${origin}" must be an https origin, such as https://calendar.google.com.`);
|
|
371
|
-
for (const path of Object.keys(
|
|
771
|
+
for (const path of Object.keys(app.files ?? {})) {
|
|
372
772
|
const segments = path.split("/");
|
|
373
773
|
if (path.startsWith("/") || segments.some((segment) => segment === "" || segment === "." || segment === "..") || /^_(assets|files|alma)$/.test(segments[0]) || RESERVED_FILES.has(path))
|
|
374
774
|
problems.push(`File "${path}" cannot be declared.`);
|
|
375
775
|
else if (siteFileContentType(path) === null)
|
|
376
|
-
problems.push(`File "${path}" has an extension
|
|
776
|
+
problems.push(`File "${path}" has an extension the published address cannot serve.`);
|
|
377
777
|
}
|
|
378
|
-
return problems;
|
|
778
|
+
return [...new Set(problems)];
|
|
379
779
|
}
|
|
380
|
-
function isSiteFileAddress(
|
|
381
|
-
if (!
|
|
780
|
+
function isSiteFileAddress(app, address) {
|
|
781
|
+
if (!app.files || address === "/" || !address.startsWith("/"))
|
|
382
782
|
return false;
|
|
383
783
|
const path = address.slice(1);
|
|
384
|
-
return Object.hasOwn(
|
|
784
|
+
return Object.hasOwn(app.files, path) || Object.hasOwn(app.files, `${path}/index.html`);
|
|
385
785
|
}
|
|
386
786
|
function outputPathOf(address) {
|
|
387
787
|
return address === "/" ? "index.html" : `${address.slice(1)}/index.html`;
|
|
@@ -395,22 +795,22 @@ function escapeHtml(text) {
|
|
|
395
795
|
function scriptJson(value) {
|
|
396
796
|
return JSON.stringify(value).replaceAll("<", "\\u003c").replaceAll(">", "\\u003e").replaceAll("&", "\\u0026").replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
|
|
397
797
|
}
|
|
398
|
-
function pageTitle(
|
|
399
|
-
return
|
|
798
|
+
function pageTitle(app, meta) {
|
|
799
|
+
return app.titleTemplate && !meta.absoluteTitle ? app.titleTemplate.replace("%s", meta.title) : meta.title;
|
|
400
800
|
}
|
|
401
801
|
function buildDocumentHead(input) {
|
|
402
|
-
const {
|
|
403
|
-
const title = pageTitle(
|
|
404
|
-
const description = meta.description ??
|
|
802
|
+
const { app, meta, origin } = input;
|
|
803
|
+
const title = pageTitle(app, meta);
|
|
804
|
+
const description = meta.description ?? app.description;
|
|
405
805
|
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 ??
|
|
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;
|
|
410
810
|
const pageImage = meta.openGraph?.image ?? meta.image;
|
|
411
|
-
const image = pageImage ??
|
|
412
|
-
const imageAlt = pageImage ? meta.imageAlt :
|
|
413
|
-
const twitterImage = meta.image ??
|
|
811
|
+
const image = pageImage ?? app.image;
|
|
812
|
+
const imageAlt = pageImage ? meta.imageAlt : app.imageAlt;
|
|
813
|
+
const twitterImage = meta.image ?? app.image;
|
|
414
814
|
const tag = (name, attributes) => `<${name} ${Object.entries(attributes).map(([key, value]) => `${key}="${escapeHtml(value)}"`).join(" ")}>`;
|
|
415
815
|
const property = (key, content) => tag("meta", { property: key, content });
|
|
416
816
|
const named = (key, content) => tag("meta", { name: key, content });
|
|
@@ -424,15 +824,15 @@ function buildDocumentHead(input) {
|
|
|
424
824
|
head.push(property("og:title", ogTitle), property("og:type", meta.type ?? "website"));
|
|
425
825
|
if (!meta.noindex)
|
|
426
826
|
head.push(property("og:url", canonical));
|
|
427
|
-
head.push(property("og:site_name",
|
|
827
|
+
head.push(property("og:site_name", app.name));
|
|
428
828
|
if (ogDescription)
|
|
429
829
|
head.push(property("og:description", ogDescription));
|
|
430
|
-
if (
|
|
431
|
-
head.push(property("og:locale",
|
|
830
|
+
if (app.locale)
|
|
831
|
+
head.push(property("og:locale", app.locale));
|
|
432
832
|
if (image) {
|
|
433
833
|
head.push(property("og:image", absoluteUrl(origin, image)));
|
|
434
|
-
if (!pageImage &&
|
|
435
|
-
head.push(property("og:image:width", String(
|
|
834
|
+
if (!pageImage && app.imageWidth && app.imageHeight)
|
|
835
|
+
head.push(property("og:image:width", String(app.imageWidth)), property("og:image:height", String(app.imageHeight)));
|
|
436
836
|
if (imageAlt)
|
|
437
837
|
head.push(property("og:image:alt", imageAlt));
|
|
438
838
|
}
|
|
@@ -442,30 +842,30 @@ function buildDocumentHead(input) {
|
|
|
442
842
|
head.push(named("twitter:description", twitterDescription));
|
|
443
843
|
if (twitterImage)
|
|
444
844
|
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 (
|
|
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)
|
|
450
850
|
head.push(tag("link", {
|
|
451
851
|
rel: "icon",
|
|
452
|
-
href:
|
|
852
|
+
href: app.favicon.light,
|
|
453
853
|
media: "(prefers-color-scheme: light)"
|
|
454
854
|
}), tag("link", {
|
|
455
855
|
rel: "icon",
|
|
456
|
-
href:
|
|
856
|
+
href: app.favicon.dark,
|
|
457
857
|
media: "(prefers-color-scheme: dark)"
|
|
458
858
|
}));
|
|
459
|
-
if (typeof
|
|
460
|
-
head.push(named("theme-color",
|
|
461
|
-
else if (
|
|
859
|
+
if (typeof app.themeColor === "string")
|
|
860
|
+
head.push(named("theme-color", app.themeColor));
|
|
861
|
+
else if (app.themeColor)
|
|
462
862
|
head.push(tag("meta", {
|
|
463
863
|
name: "theme-color",
|
|
464
|
-
content:
|
|
864
|
+
content: app.themeColor.light,
|
|
465
865
|
media: "(prefers-color-scheme: light)"
|
|
466
866
|
}), tag("meta", {
|
|
467
867
|
name: "theme-color",
|
|
468
|
-
content:
|
|
868
|
+
content: app.themeColor.dark,
|
|
469
869
|
media: "(prefers-color-scheme: dark)"
|
|
470
870
|
}));
|
|
471
871
|
for (const font of input.fonts ?? [])
|
|
@@ -476,7 +876,7 @@ function buildDocumentHead(input) {
|
|
|
476
876
|
type: font.type ?? "font/woff2",
|
|
477
877
|
crossorigin: ""
|
|
478
878
|
}));
|
|
479
|
-
for (const jsonLd of [
|
|
879
|
+
for (const jsonLd of [app.jsonLd ?? [], meta.jsonLd ?? []].flat())
|
|
480
880
|
head.push(`<script type="application/ld+json">${scriptJson(jsonLd)}</script>`);
|
|
481
881
|
return head.join(`
|
|
482
882
|
`);
|
|
@@ -513,149 +913,6 @@ function buildRobots(origin, robots = {}) {
|
|
|
513
913
|
].join(`
|
|
514
914
|
`);
|
|
515
915
|
}
|
|
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
916
|
|
|
660
917
|
// src/index.ts
|
|
661
918
|
var FINISHED = [
|
|
@@ -677,6 +934,7 @@ var SHELL_QUESTION = "getAppShell";
|
|
|
677
934
|
var SHELL_WAIT_MS = 3000;
|
|
678
935
|
var WATCH_QUESTION = "watchTopicChanges";
|
|
679
936
|
var WATCH_WAIT_MS = 5000;
|
|
937
|
+
var FILE_WAIT_MS = 120000;
|
|
680
938
|
var WATCH_TYPES_QUESTION = "watchTypeChanges";
|
|
681
939
|
var PUSHED_REREAD_MS = 300000;
|
|
682
940
|
var CATCH_UP_OVERLAP_MS = 60000;
|
|
@@ -692,6 +950,7 @@ var WATCH_BROADCASTS_QUESTION = "watchBroadcasts";
|
|
|
692
950
|
var BROADCAST_MESSAGE = "alma:broadcast";
|
|
693
951
|
var BROADCAST_EVENT = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
694
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;
|
|
695
954
|
function createAppSdk(transport) {
|
|
696
955
|
const read = new Map;
|
|
697
956
|
const precondition = (topicId, fieldKey, options) => {
|
|
@@ -706,6 +965,20 @@ function createAppSdk(transport) {
|
|
|
706
965
|
const revision = fields[fieldKey];
|
|
707
966
|
return revision === undefined ? { if_value: null } : { if_revision: revision };
|
|
708
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
|
+
};
|
|
709
982
|
const getExecution = (executionId) => transport.call("getExecution", {
|
|
710
983
|
params: { id: executionId }
|
|
711
984
|
});
|
|
@@ -1017,8 +1290,11 @@ function createAppSdk(transport) {
|
|
|
1017
1290
|
params: { key },
|
|
1018
1291
|
query: { type, cursor: page.cursor, limit: page.limit }
|
|
1019
1292
|
}),
|
|
1020
|
-
getTopicRecord: async (topicId) => {
|
|
1021
|
-
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
|
+
});
|
|
1022
1298
|
if (record.revisions)
|
|
1023
1299
|
read.set(topicId, { ...record.revisions });
|
|
1024
1300
|
return record;
|
|
@@ -1090,10 +1366,11 @@ function createAppSdk(transport) {
|
|
|
1090
1366
|
},
|
|
1091
1367
|
createTopic: async (name, topicTypeId, options = {}) => {
|
|
1092
1368
|
const fields = options.fields ?? [];
|
|
1369
|
+
const typeId = topicTypeId && !UUID2.test(topicTypeId) && transport.place !== "public" ? await typeIdOf(topicTypeId) : topicTypeId;
|
|
1093
1370
|
const created = await transport.call("createTopic", {
|
|
1094
1371
|
body: {
|
|
1095
1372
|
name,
|
|
1096
|
-
...
|
|
1373
|
+
...typeId ? { topic_type_id: typeId } : {},
|
|
1097
1374
|
...fields.length > 0 ? {
|
|
1098
1375
|
fields: fields.map((field) => ({
|
|
1099
1376
|
key: field.key,
|
|
@@ -1176,6 +1453,31 @@ function createAppSdk(transport) {
|
|
|
1176
1453
|
}));
|
|
1177
1454
|
return transport.result(token);
|
|
1178
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
|
+
},
|
|
1179
1481
|
waitForResult: async (token, options = {}) => {
|
|
1180
1482
|
const read = transport.result?.bind(transport);
|
|
1181
1483
|
if (!read)
|
|
@@ -1596,6 +1898,7 @@ function hostTransport() {
|
|
|
1596
1898
|
return { watching: [], stop };
|
|
1597
1899
|
}
|
|
1598
1900
|
};
|
|
1901
|
+
const files2 = new Map;
|
|
1599
1902
|
return {
|
|
1600
1903
|
call: (operationId, request = {}) => ask(operationId, request),
|
|
1601
1904
|
viewer: async () => {
|
|
@@ -1607,6 +1910,28 @@ function hostTransport() {
|
|
|
1607
1910
|
const told = await ask(SHELL_QUESTION, {}, SHELL_WAIT_MS);
|
|
1608
1911
|
return isAppShell(told) ? told : null;
|
|
1609
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
|
+
},
|
|
1610
1935
|
watch: (topicIds, changed) => watchFor(WATCH_QUESTION, "topic_ids", topicChanges, topicIds, changed),
|
|
1611
1936
|
watchTypes: (typeIds, changed) => watchFor(WATCH_TYPES_QUESTION, "type_ids", typeChanges, typeIds, changed),
|
|
1612
1937
|
watchShared: async (told) => {
|
|
@@ -1663,11 +1988,16 @@ function hostTransport() {
|
|
|
1663
1988
|
};
|
|
1664
1989
|
}
|
|
1665
1990
|
export {
|
|
1991
|
+
APP_FILE_QUESTION,
|
|
1666
1992
|
AppCallError,
|
|
1667
1993
|
BROADCAST_MESSAGE,
|
|
1668
1994
|
DEFAULT_THEME_SCRIPT,
|
|
1669
|
-
|
|
1995
|
+
NOT_FOUND_ROUTE_ID,
|
|
1996
|
+
OPEN_FILE_MESSAGE,
|
|
1997
|
+
OPEN_FILE_TEXT_LIMIT,
|
|
1998
|
+
OPEN_URL_MESSAGE,
|
|
1670
1999
|
PRESENCE_MESSAGE,
|
|
2000
|
+
PUBLIC_RECORD_SHAPE,
|
|
1671
2001
|
PUBLISHED_SITE_ATTRIBUTE,
|
|
1672
2002
|
SHARED_STATE_MESSAGE,
|
|
1673
2003
|
SHELL_QUESTION,
|
|
@@ -1681,20 +2011,26 @@ export {
|
|
|
1681
2011
|
WATCH_SHARED_QUESTION,
|
|
1682
2012
|
WATCH_TYPES_QUESTION,
|
|
1683
2013
|
absoluteUrl,
|
|
2014
|
+
appDefinitionProblems,
|
|
2015
|
+
appFileNameOf,
|
|
2016
|
+
appIn,
|
|
2017
|
+
appPlace,
|
|
1684
2018
|
applicationPath,
|
|
1685
2019
|
buildDocumentHead,
|
|
1686
2020
|
buildRobots,
|
|
1687
2021
|
buildSitemap,
|
|
1688
2022
|
createAppSdk,
|
|
1689
|
-
|
|
1690
|
-
|
|
2023
|
+
defineApp,
|
|
2024
|
+
defineRoute,
|
|
1691
2025
|
escapeHtml,
|
|
1692
2026
|
fillPattern,
|
|
1693
2027
|
hostEvents,
|
|
1694
2028
|
hostNavigation,
|
|
1695
2029
|
hostTransport,
|
|
2030
|
+
isAppFileName,
|
|
1696
2031
|
isFieldChanged,
|
|
1697
2032
|
isNotFound,
|
|
2033
|
+
isOwnEntry,
|
|
1698
2034
|
isSharedStateConflict,
|
|
1699
2035
|
isSiteFileAddress,
|
|
1700
2036
|
isSiteRefusal,
|
|
@@ -1704,13 +2040,13 @@ export {
|
|
|
1704
2040
|
matchRedirect,
|
|
1705
2041
|
notFound,
|
|
1706
2042
|
outputPathOf,
|
|
2043
|
+
outsideUrl,
|
|
1707
2044
|
pageTitle,
|
|
1708
2045
|
parseAppHostEvent,
|
|
1709
2046
|
publishedSite,
|
|
1710
2047
|
readResultToken,
|
|
1711
2048
|
scriptJson,
|
|
1712
2049
|
siteAddressProblem,
|
|
1713
|
-
siteDefinitionProblems,
|
|
1714
2050
|
siteFileContentType,
|
|
1715
2051
|
siteNavigation,
|
|
1716
2052
|
siteTransport
|