@almateam/app-sdk 0.8.0 → 0.9.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 +127 -9
- package/callError.d.ts +21 -0
- package/cli.js +404 -35
- package/index.d.ts +49 -35
- package/index.js +618 -17
- package/package.json +1 -1
- package/site.d.ts +267 -0
- package/siteRuntime.d.ts +69 -0
package/index.js
CHANGED
|
@@ -20,6 +20,18 @@ 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
|
+
|
|
23
35
|
// src/navigation.ts
|
|
24
36
|
function applicationPath(value) {
|
|
25
37
|
if (typeof value !== "string" || value.length > 2048 || !value.startsWith("/") || value.startsWith("//") || /[\\?#]/.test(value) || [...value].some((character) => character.charCodeAt(0) < 32))
|
|
@@ -125,6 +137,525 @@ function hostNavigation() {
|
|
|
125
137
|
}
|
|
126
138
|
};
|
|
127
139
|
}
|
|
140
|
+
// src/site.ts
|
|
141
|
+
var SITE_ORIGIN_TOKEN = "__ALMA_SITE_ORIGIN__";
|
|
142
|
+
var NOT_FOUND_PAGE_ID = "404";
|
|
143
|
+
var SITE_REDIRECT_STATUSES = [301, 302, 307, 308];
|
|
144
|
+
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 defineSite(site) {
|
|
146
|
+
return site;
|
|
147
|
+
}
|
|
148
|
+
function definePage(page) {
|
|
149
|
+
return page;
|
|
150
|
+
}
|
|
151
|
+
var NOT_FOUND = Symbol.for("alma.site.notFound");
|
|
152
|
+
function notFound() {
|
|
153
|
+
const error = new Error("This address has no page.");
|
|
154
|
+
error[NOT_FOUND] = true;
|
|
155
|
+
return error;
|
|
156
|
+
}
|
|
157
|
+
function isNotFound(error) {
|
|
158
|
+
return error instanceof Error && error[NOT_FOUND] === true;
|
|
159
|
+
}
|
|
160
|
+
var SEGMENT = /^(?:[A-Za-z0-9\-._~!$&'()*+,;=:@]|%[0-9A-Fa-f]{2})+$/;
|
|
161
|
+
var PARAMETER = /^:([A-Za-z_][A-Za-z0-9_]*)$/;
|
|
162
|
+
function siteAddressProblem(address) {
|
|
163
|
+
if (address === "/")
|
|
164
|
+
return null;
|
|
165
|
+
if (!address.startsWith("/"))
|
|
166
|
+
return `"${address}" does not start with /.`;
|
|
167
|
+
if (address.length > 1024)
|
|
168
|
+
return `"${address.slice(0, 40)}…" is too long.`;
|
|
169
|
+
if (address.endsWith("/"))
|
|
170
|
+
return `"${address}" ends with /; write it without.`;
|
|
171
|
+
for (const segment of address.slice(1).split("/")) {
|
|
172
|
+
if (segment === "" || segment === "." || segment === "..")
|
|
173
|
+
return `"${address}" has an empty or dot segment.`;
|
|
174
|
+
if (segment === "index.html")
|
|
175
|
+
return `"${address}" names index.html; write the address without it.`;
|
|
176
|
+
if (!SEGMENT.test(segment))
|
|
177
|
+
return `"${address}" has a character an address cannot hold.`;
|
|
178
|
+
}
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
function patternProblem(path) {
|
|
182
|
+
if (path === "/")
|
|
183
|
+
return null;
|
|
184
|
+
const names = new Set;
|
|
185
|
+
for (const segment of path.slice(1).split("/")) {
|
|
186
|
+
const parameter = PARAMETER.exec(segment);
|
|
187
|
+
if (!parameter)
|
|
188
|
+
continue;
|
|
189
|
+
if (names.has(parameter[1]))
|
|
190
|
+
return `"${path}" names :${parameter[1]} twice.`;
|
|
191
|
+
names.add(parameter[1]);
|
|
192
|
+
}
|
|
193
|
+
return siteAddressProblem(path.replace(/\/:[A-Za-z_][A-Za-z0-9_]*/g, "/parameter"));
|
|
194
|
+
}
|
|
195
|
+
function decodeSegment(segment) {
|
|
196
|
+
try {
|
|
197
|
+
return decodeURIComponent(segment);
|
|
198
|
+
} catch {
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
function matchPattern(pattern, address) {
|
|
203
|
+
if (pattern === "/" || address === "/")
|
|
204
|
+
return pattern === address ? {} : null;
|
|
205
|
+
const want = pattern.slice(1).split("/");
|
|
206
|
+
const have = address.slice(1).split("/");
|
|
207
|
+
if (want.length !== have.length)
|
|
208
|
+
return null;
|
|
209
|
+
const params = {};
|
|
210
|
+
for (let index = 0;index < want.length; index += 1) {
|
|
211
|
+
const parameter = PARAMETER.exec(want[index]);
|
|
212
|
+
if (parameter) {
|
|
213
|
+
const value = decodeSegment(have[index]);
|
|
214
|
+
if (value === null || value === "")
|
|
215
|
+
return null;
|
|
216
|
+
params[parameter[1]] = value;
|
|
217
|
+
} else if (want[index] !== have[index])
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
return params;
|
|
221
|
+
}
|
|
222
|
+
function fillPattern(pattern, params) {
|
|
223
|
+
return pattern.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, (_, name) => {
|
|
224
|
+
const value = params[name];
|
|
225
|
+
if (typeof value !== "string" || value === "")
|
|
226
|
+
throw new Error(`"${pattern}" needs a value for :${name}.`);
|
|
227
|
+
return encodeURIComponent(value);
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
function moreSpecific(a, b) {
|
|
231
|
+
const left = a.split("/");
|
|
232
|
+
const right = b.split("/");
|
|
233
|
+
for (let index = 0;index < Math.min(left.length, right.length); index += 1) {
|
|
234
|
+
const leftParameter = left[index].startsWith(":");
|
|
235
|
+
const rightParameter = right[index].startsWith(":");
|
|
236
|
+
if (leftParameter !== rightParameter)
|
|
237
|
+
return leftParameter ? 1 : -1;
|
|
238
|
+
}
|
|
239
|
+
return 0;
|
|
240
|
+
}
|
|
241
|
+
function redirectPrefix(from) {
|
|
242
|
+
if (from === "/*")
|
|
243
|
+
return "";
|
|
244
|
+
return from.endsWith("/*") ? from.slice(0, -2) : null;
|
|
245
|
+
}
|
|
246
|
+
function matchRedirect(redirects, address) {
|
|
247
|
+
let best = null;
|
|
248
|
+
for (const redirect of redirects) {
|
|
249
|
+
const prefix = redirectPrefix(redirect.from);
|
|
250
|
+
if (prefix === null) {
|
|
251
|
+
if (redirect.from === address)
|
|
252
|
+
return redirect;
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
const under = prefix === "" || address === prefix || address.startsWith(`${prefix}/`);
|
|
256
|
+
if (under && (best === null || prefix.length > best.length))
|
|
257
|
+
best = { redirect, length: prefix.length };
|
|
258
|
+
}
|
|
259
|
+
return best?.redirect ?? null;
|
|
260
|
+
}
|
|
261
|
+
function matchAddress(site, address, listed) {
|
|
262
|
+
if (siteAddressProblem(address) !== null)
|
|
263
|
+
return null;
|
|
264
|
+
const redirects = site.redirects ?? [];
|
|
265
|
+
const exactPage = site.pages.find((page) => page.path === address);
|
|
266
|
+
if (exactPage)
|
|
267
|
+
return { kind: "page", page: exactPage, params: {} };
|
|
268
|
+
const exactRedirect = redirects.find((redirect) => redirect.from === address);
|
|
269
|
+
if (exactRedirect)
|
|
270
|
+
return { kind: "redirect", redirect: exactRedirect };
|
|
271
|
+
let found = null;
|
|
272
|
+
if (!listed || listed.has(address))
|
|
273
|
+
for (const page of site.pages) {
|
|
274
|
+
const params = matchPattern(page.path, address);
|
|
275
|
+
if (params && (!found || moreSpecific(page.path, found.page.path) < 0))
|
|
276
|
+
found = { page, params };
|
|
277
|
+
}
|
|
278
|
+
if (found)
|
|
279
|
+
return { kind: "page", ...found };
|
|
280
|
+
const redirect = matchRedirect(redirects, address);
|
|
281
|
+
return redirect ? { kind: "redirect", redirect } : null;
|
|
282
|
+
}
|
|
283
|
+
async function listAddresses(site) {
|
|
284
|
+
const listed = [];
|
|
285
|
+
for (const page of site.pages) {
|
|
286
|
+
const sets = page.path.includes("/:") && page.addresses ? await page.addresses() : [{}];
|
|
287
|
+
for (const params of sets) {
|
|
288
|
+
const address = fillPattern(page.path, params);
|
|
289
|
+
const problem = siteAddressProblem(address);
|
|
290
|
+
if (problem)
|
|
291
|
+
throw new Error(`Page ${page.path}: ${problem}`);
|
|
292
|
+
listed.push({ page, params, address });
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
const addresses = new Set(listed.map((entry) => entry.address));
|
|
296
|
+
const seen = new Set;
|
|
297
|
+
for (const entry of listed) {
|
|
298
|
+
const match = matchAddress(site, entry.address, addresses);
|
|
299
|
+
if (match?.kind !== "page" || match.page !== entry.page)
|
|
300
|
+
throw new Error(`Page ${entry.page.path}: ${entry.address} is served by ${match?.kind === "page" ? `page ${match.page.path}` : "a redirect"}.`);
|
|
301
|
+
if (seen.has(entry.address))
|
|
302
|
+
throw new Error(`Page ${entry.page.path}: ${entry.address} is listed twice.`);
|
|
303
|
+
seen.add(entry.address);
|
|
304
|
+
entry.params = match.params;
|
|
305
|
+
}
|
|
306
|
+
return listed;
|
|
307
|
+
}
|
|
308
|
+
var RESERVED_FILES = new Set([
|
|
309
|
+
"index.html",
|
|
310
|
+
"404.html",
|
|
311
|
+
"sitemap.xml",
|
|
312
|
+
"robots.txt",
|
|
313
|
+
"_site.json"
|
|
314
|
+
]);
|
|
315
|
+
var FILE_TYPES = {
|
|
316
|
+
txt: "text/plain; charset=utf-8",
|
|
317
|
+
md: "text/markdown; charset=utf-8",
|
|
318
|
+
html: "text/html; charset=utf-8",
|
|
319
|
+
xml: "application/xml; charset=utf-8",
|
|
320
|
+
json: "application/json; charset=utf-8",
|
|
321
|
+
webmanifest: "application/manifest+json; charset=utf-8",
|
|
322
|
+
css: "text/css; charset=utf-8",
|
|
323
|
+
svg: "image/svg+xml; charset=utf-8",
|
|
324
|
+
csv: "text/csv; charset=utf-8"
|
|
325
|
+
};
|
|
326
|
+
function siteFileContentType(path) {
|
|
327
|
+
const extension = /\.([a-z0-9]+)$/i.exec(path)?.[1]?.toLowerCase();
|
|
328
|
+
return extension ? FILE_TYPES[extension] ?? null : null;
|
|
329
|
+
}
|
|
330
|
+
var ORIGIN = /^https:\/\/[a-z0-9.-]+(?::\d{1,5})?$/;
|
|
331
|
+
function siteDefinitionProblems(site) {
|
|
332
|
+
const problems = [];
|
|
333
|
+
if (!site.meta?.name)
|
|
334
|
+
problems.push("The site's meta needs a name.");
|
|
335
|
+
const paths = new Set;
|
|
336
|
+
const shapes = new Map;
|
|
337
|
+
for (const page of site.pages) {
|
|
338
|
+
const problem = patternProblem(page.path);
|
|
339
|
+
if (problem)
|
|
340
|
+
problems.push(`Page ${problem}`);
|
|
341
|
+
const shape = page.path.replace(/:[A-Za-z_][A-Za-z0-9_]*/g, ":");
|
|
342
|
+
if (shapes.has(shape))
|
|
343
|
+
problems.push(`Pages "${shapes.get(shape)}" and "${page.path}" match the same addresses.`);
|
|
344
|
+
shapes.set(shape, page.path);
|
|
345
|
+
paths.add(page.path);
|
|
346
|
+
if (page.path.includes("/:") && !page.addresses)
|
|
347
|
+
problems.push(`Page "${page.path}" has parameters, so it must list its addresses.`);
|
|
348
|
+
}
|
|
349
|
+
const froms = new Set;
|
|
350
|
+
for (const redirect of site.redirects ?? []) {
|
|
351
|
+
const prefix = redirectPrefix(redirect.from);
|
|
352
|
+
const problem = prefix === "" ? null : siteAddressProblem(prefix ?? redirect.from);
|
|
353
|
+
if (problem)
|
|
354
|
+
problems.push(`Redirect ${problem}`);
|
|
355
|
+
if (froms.has(redirect.from))
|
|
356
|
+
problems.push(`Two redirects move "${redirect.from}".`);
|
|
357
|
+
froms.add(redirect.from);
|
|
358
|
+
if (!SITE_REDIRECT_STATUSES.includes(redirect.status))
|
|
359
|
+
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
|
+
const external = redirect.to.startsWith("https://");
|
|
363
|
+
if (!external && siteAddressProblem(redirect.to) !== null)
|
|
364
|
+
problems.push(`Redirect "${redirect.from}" must go to an address on this site or an https URL.`);
|
|
365
|
+
if (!external && redirect.to === redirect.from)
|
|
366
|
+
problems.push(`Redirect "${redirect.from}" goes to itself.`);
|
|
367
|
+
}
|
|
368
|
+
for (const origin of site.embeds ?? [])
|
|
369
|
+
if (!ORIGIN.test(origin))
|
|
370
|
+
problems.push(`Embed "${origin}" must be an https origin, such as https://calendar.google.com.`);
|
|
371
|
+
for (const path of Object.keys(site.files ?? {})) {
|
|
372
|
+
const segments = path.split("/");
|
|
373
|
+
if (path.startsWith("/") || segments.some((segment) => segment === "" || segment === "." || segment === "..") || /^_(assets|files|alma)$/.test(segments[0]) || RESERVED_FILES.has(path))
|
|
374
|
+
problems.push(`File "${path}" cannot be declared.`);
|
|
375
|
+
else if (siteFileContentType(path) === null)
|
|
376
|
+
problems.push(`File "${path}" has an extension a site cannot serve.`);
|
|
377
|
+
}
|
|
378
|
+
return problems;
|
|
379
|
+
}
|
|
380
|
+
function isSiteFileAddress(site, address) {
|
|
381
|
+
if (!site.files || address === "/" || !address.startsWith("/"))
|
|
382
|
+
return false;
|
|
383
|
+
const path = address.slice(1);
|
|
384
|
+
return Object.hasOwn(site.files, path) || Object.hasOwn(site.files, `${path}/index.html`);
|
|
385
|
+
}
|
|
386
|
+
function outputPathOf(address) {
|
|
387
|
+
return address === "/" ? "index.html" : `${address.slice(1)}/index.html`;
|
|
388
|
+
}
|
|
389
|
+
function absoluteUrl(origin, path) {
|
|
390
|
+
return /^https?:\/\//.test(path) ? path : `${origin}${path}`;
|
|
391
|
+
}
|
|
392
|
+
function escapeHtml(text) {
|
|
393
|
+
return text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
394
|
+
}
|
|
395
|
+
function scriptJson(value) {
|
|
396
|
+
return JSON.stringify(value).replaceAll("<", "\\u003c").replaceAll(">", "\\u003e").replaceAll("&", "\\u0026").replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
|
|
397
|
+
}
|
|
398
|
+
function pageTitle(site, meta) {
|
|
399
|
+
return site.titleTemplate && !meta.absoluteTitle ? site.titleTemplate.replace("%s", meta.title) : meta.title;
|
|
400
|
+
}
|
|
401
|
+
function buildDocumentHead(input) {
|
|
402
|
+
const { site, meta, origin } = input;
|
|
403
|
+
const title = pageTitle(site, meta);
|
|
404
|
+
const description = meta.description ?? site.description;
|
|
405
|
+
const canonical = absoluteUrl(origin, meta.canonical ?? input.address);
|
|
406
|
+
const ogTitle = meta.openGraph?.title ?? site.openGraph?.title ?? meta.title;
|
|
407
|
+
const ogDescription = meta.openGraph?.description ?? site.openGraph?.description ?? description;
|
|
408
|
+
const twitterTitle = meta.x?.title ?? site.x?.title ?? meta.title;
|
|
409
|
+
const twitterDescription = meta.x?.description ?? site.x?.description ?? description;
|
|
410
|
+
const pageImage = meta.openGraph?.image ?? meta.image;
|
|
411
|
+
const image = pageImage ?? site.image;
|
|
412
|
+
const imageAlt = pageImage ? meta.imageAlt : site.imageAlt;
|
|
413
|
+
const twitterImage = meta.image ?? site.image;
|
|
414
|
+
const tag = (name, attributes) => `<${name} ${Object.entries(attributes).map(([key, value]) => `${key}="${escapeHtml(value)}"`).join(" ")}>`;
|
|
415
|
+
const property = (key, content) => tag("meta", { property: key, content });
|
|
416
|
+
const named = (key, content) => tag("meta", { name: key, content });
|
|
417
|
+
const head = [`<title>${escapeHtml(title)}</title>`];
|
|
418
|
+
if (description)
|
|
419
|
+
head.push(named("description", description));
|
|
420
|
+
if (meta.noindex)
|
|
421
|
+
head.push(named("robots", "noindex"));
|
|
422
|
+
else
|
|
423
|
+
head.push(tag("link", { rel: "canonical", href: canonical }));
|
|
424
|
+
head.push(property("og:title", ogTitle), property("og:type", meta.type ?? "website"));
|
|
425
|
+
if (!meta.noindex)
|
|
426
|
+
head.push(property("og:url", canonical));
|
|
427
|
+
head.push(property("og:site_name", site.name));
|
|
428
|
+
if (ogDescription)
|
|
429
|
+
head.push(property("og:description", ogDescription));
|
|
430
|
+
if (site.locale)
|
|
431
|
+
head.push(property("og:locale", site.locale));
|
|
432
|
+
if (image) {
|
|
433
|
+
head.push(property("og:image", absoluteUrl(origin, image)));
|
|
434
|
+
if (!pageImage && site.imageWidth && site.imageHeight)
|
|
435
|
+
head.push(property("og:image:width", String(site.imageWidth)), property("og:image:height", String(site.imageHeight)));
|
|
436
|
+
if (imageAlt)
|
|
437
|
+
head.push(property("og:image:alt", imageAlt));
|
|
438
|
+
}
|
|
439
|
+
head.push(named("twitter:card", twitterImage ? "summary_large_image" : "summary"));
|
|
440
|
+
head.push(named("twitter:title", twitterTitle));
|
|
441
|
+
if (twitterDescription)
|
|
442
|
+
head.push(named("twitter:description", twitterDescription));
|
|
443
|
+
if (twitterImage)
|
|
444
|
+
head.push(named("twitter:image", absoluteUrl(origin, twitterImage)));
|
|
445
|
+
if (site.twitter)
|
|
446
|
+
head.push(named("twitter:site", site.twitter));
|
|
447
|
+
if (typeof site.favicon === "string")
|
|
448
|
+
head.push(tag("link", { rel: "icon", href: site.favicon }));
|
|
449
|
+
else if (site.favicon)
|
|
450
|
+
head.push(tag("link", {
|
|
451
|
+
rel: "icon",
|
|
452
|
+
href: site.favicon.light,
|
|
453
|
+
media: "(prefers-color-scheme: light)"
|
|
454
|
+
}), tag("link", {
|
|
455
|
+
rel: "icon",
|
|
456
|
+
href: site.favicon.dark,
|
|
457
|
+
media: "(prefers-color-scheme: dark)"
|
|
458
|
+
}));
|
|
459
|
+
if (typeof site.themeColor === "string")
|
|
460
|
+
head.push(named("theme-color", site.themeColor));
|
|
461
|
+
else if (site.themeColor)
|
|
462
|
+
head.push(tag("meta", {
|
|
463
|
+
name: "theme-color",
|
|
464
|
+
content: site.themeColor.light,
|
|
465
|
+
media: "(prefers-color-scheme: light)"
|
|
466
|
+
}), tag("meta", {
|
|
467
|
+
name: "theme-color",
|
|
468
|
+
content: site.themeColor.dark,
|
|
469
|
+
media: "(prefers-color-scheme: dark)"
|
|
470
|
+
}));
|
|
471
|
+
for (const font of input.fonts ?? [])
|
|
472
|
+
head.push(tag("link", {
|
|
473
|
+
rel: "preload",
|
|
474
|
+
href: font.href,
|
|
475
|
+
as: "font",
|
|
476
|
+
type: font.type ?? "font/woff2",
|
|
477
|
+
crossorigin: ""
|
|
478
|
+
}));
|
|
479
|
+
for (const jsonLd of [site.jsonLd ?? [], meta.jsonLd ?? []].flat())
|
|
480
|
+
head.push(`<script type="application/ld+json">${scriptJson(jsonLd)}</script>`);
|
|
481
|
+
return head.join(`
|
|
482
|
+
`);
|
|
483
|
+
}
|
|
484
|
+
function buildSitemap(origin, entries) {
|
|
485
|
+
const urls = entries.map((entry) => {
|
|
486
|
+
const lines = [
|
|
487
|
+
`<loc>${escapeHtml(absoluteUrl(origin, entry.address))}</loc>`
|
|
488
|
+
];
|
|
489
|
+
if (entry.lastModified)
|
|
490
|
+
lines.push(`<lastmod>${escapeHtml(entry.lastModified)}</lastmod>`);
|
|
491
|
+
if (entry.changeFrequency)
|
|
492
|
+
lines.push(`<changefreq>${entry.changeFrequency}</changefreq>`);
|
|
493
|
+
if (entry.priority !== undefined)
|
|
494
|
+
lines.push(`<priority>${Math.min(1, Math.max(0, entry.priority)).toFixed(1)}</priority>`);
|
|
495
|
+
return `<url>${lines.join("")}</url>`;
|
|
496
|
+
});
|
|
497
|
+
return [
|
|
498
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
499
|
+
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
|
|
500
|
+
...urls,
|
|
501
|
+
"</urlset>",
|
|
502
|
+
""
|
|
503
|
+
].join(`
|
|
504
|
+
`);
|
|
505
|
+
}
|
|
506
|
+
function buildRobots(origin, robots = {}) {
|
|
507
|
+
return [
|
|
508
|
+
"User-agent: *",
|
|
509
|
+
...robots.disallow?.length ? robots.disallow.map((path) => `Disallow: ${path}`) : ["Allow: /"],
|
|
510
|
+
"",
|
|
511
|
+
`Sitemap: ${origin}/sitemap.xml`,
|
|
512
|
+
""
|
|
513
|
+
].join(`
|
|
514
|
+
`);
|
|
515
|
+
}
|
|
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
|
+
}
|
|
128
659
|
|
|
129
660
|
// src/index.ts
|
|
130
661
|
var FINISHED = [
|
|
@@ -132,16 +663,6 @@ var FINISHED = [
|
|
|
132
663
|
"failed",
|
|
133
664
|
"cancelled"
|
|
134
665
|
];
|
|
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
666
|
function isFieldChanged(error) {
|
|
146
667
|
return error instanceof Error && error.code === "field.changed" && error.current !== undefined;
|
|
147
668
|
}
|
|
@@ -648,6 +1169,41 @@ function createAppSdk(transport) {
|
|
|
648
1169
|
body: { event, ...payload ? { payload } : {} },
|
|
649
1170
|
idempotencyKey: options.idempotencyKey ?? oneRequest()
|
|
650
1171
|
}),
|
|
1172
|
+
result: (token) => {
|
|
1173
|
+
if (!transport.result)
|
|
1174
|
+
return Promise.reject(new AppCallError("This app has no event results to read.", {
|
|
1175
|
+
code: "result.unavailable"
|
|
1176
|
+
}));
|
|
1177
|
+
return transport.result(token);
|
|
1178
|
+
},
|
|
1179
|
+
waitForResult: async (token, options = {}) => {
|
|
1180
|
+
const read = transport.result?.bind(transport);
|
|
1181
|
+
if (!read)
|
|
1182
|
+
throw new AppCallError("This app has no event results to read.", {
|
|
1183
|
+
code: "result.unavailable"
|
|
1184
|
+
});
|
|
1185
|
+
const deadline = Date.now() + (options.timeoutMs ?? 120000);
|
|
1186
|
+
let delay = 1000;
|
|
1187
|
+
for (;; ) {
|
|
1188
|
+
options.signal?.throwIfAborted();
|
|
1189
|
+
const answer = await read(token);
|
|
1190
|
+
if (answer.status === "ready")
|
|
1191
|
+
return answer.result;
|
|
1192
|
+
const left = deadline - Date.now();
|
|
1193
|
+
if (left <= 0)
|
|
1194
|
+
throw new AppCallError("The result is not ready yet.", {
|
|
1195
|
+
code: "result.timeout"
|
|
1196
|
+
});
|
|
1197
|
+
await new Promise((resolve, reject) => {
|
|
1198
|
+
const timer = setTimeout(resolve, Math.min(delay, left));
|
|
1199
|
+
options.signal?.addEventListener("abort", () => {
|
|
1200
|
+
clearTimeout(timer);
|
|
1201
|
+
reject(options.signal?.reason);
|
|
1202
|
+
}, { once: true });
|
|
1203
|
+
});
|
|
1204
|
+
delay = Math.min(delay * 2, 8000);
|
|
1205
|
+
}
|
|
1206
|
+
},
|
|
651
1207
|
state: {
|
|
652
1208
|
get: async (key) => {
|
|
653
1209
|
const entry = await transport.call("getAppState", { params: { key } });
|
|
@@ -679,6 +1235,7 @@ function createAppSdk(transport) {
|
|
|
679
1235
|
const seen = new Map;
|
|
680
1236
|
let toldWhileReading = null;
|
|
681
1237
|
let watch = null;
|
|
1238
|
+
let pushed = false;
|
|
682
1239
|
let stopped = false;
|
|
683
1240
|
let delay = every;
|
|
684
1241
|
let timer;
|
|
@@ -737,7 +1294,7 @@ function createAppSdk(transport) {
|
|
|
737
1294
|
const tick = async () => {
|
|
738
1295
|
try {
|
|
739
1296
|
const changed = await readAll();
|
|
740
|
-
if (
|
|
1297
|
+
if (pushed)
|
|
741
1298
|
return PUSHED_REREAD_MS;
|
|
742
1299
|
delay = changed ? every : Math.min(delay * 2, 60000);
|
|
743
1300
|
} catch {
|
|
@@ -766,8 +1323,10 @@ function createAppSdk(transport) {
|
|
|
766
1323
|
const heard = (told) => {
|
|
767
1324
|
if (stopped)
|
|
768
1325
|
return;
|
|
769
|
-
if ("missed" in told)
|
|
1326
|
+
if ("missed" in told) {
|
|
1327
|
+
pushed = true;
|
|
770
1328
|
return read();
|
|
1329
|
+
}
|
|
771
1330
|
toldWhileReading?.add(told.key);
|
|
772
1331
|
if ("exists" in told)
|
|
773
1332
|
tellDeleted(told.key, told.revision);
|
|
@@ -789,6 +1348,8 @@ function createAppSdk(transport) {
|
|
|
789
1348
|
asked?.stop();
|
|
790
1349
|
else
|
|
791
1350
|
watch = asked ?? null;
|
|
1351
|
+
if (watch?.watching)
|
|
1352
|
+
pushed = true;
|
|
792
1353
|
read();
|
|
793
1354
|
})();
|
|
794
1355
|
return () => {
|
|
@@ -826,7 +1387,11 @@ function createAppSdk(transport) {
|
|
|
826
1387
|
let watch = null;
|
|
827
1388
|
(async () => {
|
|
828
1389
|
const asked = await transport.watchBroadcasts?.((message) => {
|
|
829
|
-
if (stopped
|
|
1390
|
+
if (stopped)
|
|
1391
|
+
return;
|
|
1392
|
+
if ("missed" in message)
|
|
1393
|
+
return options.missed?.();
|
|
1394
|
+
if (message.event !== event)
|
|
830
1395
|
return;
|
|
831
1396
|
if (message.self && !options.self)
|
|
832
1397
|
return;
|
|
@@ -913,6 +1478,8 @@ function broadcastTold(told) {
|
|
|
913
1478
|
const message = told;
|
|
914
1479
|
if (message["type"] !== BROADCAST_MESSAGE)
|
|
915
1480
|
return null;
|
|
1481
|
+
if (message["missed"] === true)
|
|
1482
|
+
return { missed: true };
|
|
916
1483
|
const { event } = message;
|
|
917
1484
|
if (typeof event !== "string" || !BROADCAST_EVENT.test(event))
|
|
918
1485
|
return null;
|
|
@@ -1047,10 +1614,12 @@ function hostTransport() {
|
|
|
1047
1614
|
const stop = () => sharedChanges.delete(told);
|
|
1048
1615
|
try {
|
|
1049
1616
|
const answer = await ask(WATCH_SHARED_QUESTION, {}, WATCH_WAIT_MS);
|
|
1050
|
-
const
|
|
1051
|
-
|
|
1617
|
+
const said = typeof answer === "object" && answer !== null ? answer : {};
|
|
1618
|
+
const watching = said["watching"] === true;
|
|
1619
|
+
const joining = !watching && said["joining"] === true;
|
|
1620
|
+
if (!watching && !joining)
|
|
1052
1621
|
stop();
|
|
1053
|
-
return { watching, stop };
|
|
1622
|
+
return { watching, joining, stop };
|
|
1054
1623
|
} catch {
|
|
1055
1624
|
stop();
|
|
1056
1625
|
return { watching: false, stop };
|
|
@@ -1096,21 +1665,53 @@ function hostTransport() {
|
|
|
1096
1665
|
export {
|
|
1097
1666
|
AppCallError,
|
|
1098
1667
|
BROADCAST_MESSAGE,
|
|
1668
|
+
DEFAULT_THEME_SCRIPT,
|
|
1669
|
+
NOT_FOUND_PAGE_ID,
|
|
1099
1670
|
PRESENCE_MESSAGE,
|
|
1671
|
+
PUBLISHED_SITE_ATTRIBUTE,
|
|
1100
1672
|
SHARED_STATE_MESSAGE,
|
|
1101
1673
|
SHELL_QUESTION,
|
|
1674
|
+
SITE_ORIGIN_TOKEN,
|
|
1675
|
+
SITE_REDIRECT_STATUSES,
|
|
1676
|
+
SiteRefusalError,
|
|
1102
1677
|
VIEWER_QUESTION,
|
|
1103
1678
|
WATCH_BROADCASTS_QUESTION,
|
|
1104
1679
|
WATCH_PRESENCE_QUESTION,
|
|
1105
1680
|
WATCH_QUESTION,
|
|
1106
1681
|
WATCH_SHARED_QUESTION,
|
|
1107
1682
|
WATCH_TYPES_QUESTION,
|
|
1683
|
+
absoluteUrl,
|
|
1108
1684
|
applicationPath,
|
|
1685
|
+
buildDocumentHead,
|
|
1686
|
+
buildRobots,
|
|
1687
|
+
buildSitemap,
|
|
1109
1688
|
createAppSdk,
|
|
1689
|
+
definePage,
|
|
1690
|
+
defineSite,
|
|
1691
|
+
escapeHtml,
|
|
1692
|
+
fillPattern,
|
|
1110
1693
|
hostEvents,
|
|
1111
1694
|
hostNavigation,
|
|
1112
1695
|
hostTransport,
|
|
1113
1696
|
isFieldChanged,
|
|
1697
|
+
isNotFound,
|
|
1114
1698
|
isSharedStateConflict,
|
|
1115
|
-
|
|
1699
|
+
isSiteFileAddress,
|
|
1700
|
+
isSiteRefusal,
|
|
1701
|
+
listAddresses,
|
|
1702
|
+
matchAddress,
|
|
1703
|
+
matchPattern,
|
|
1704
|
+
matchRedirect,
|
|
1705
|
+
notFound,
|
|
1706
|
+
outputPathOf,
|
|
1707
|
+
pageTitle,
|
|
1708
|
+
parseAppHostEvent,
|
|
1709
|
+
publishedSite,
|
|
1710
|
+
readResultToken,
|
|
1711
|
+
scriptJson,
|
|
1712
|
+
siteAddressProblem,
|
|
1713
|
+
siteDefinitionProblems,
|
|
1714
|
+
siteFileContentType,
|
|
1715
|
+
siteNavigation,
|
|
1716
|
+
siteTransport
|
|
1116
1717
|
};
|