@jxsuite/compiler 11.0.0 → 11.1.1
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/dist/cli.js +278 -275
- package/dist/compiler.js +120 -117
- package/package.json +8 -8
- package/src/child-separator.ts +260 -0
- package/src/shared.ts +26 -30
- package/src/site/build-time.ts +45 -0
- package/src/site/context-injection.ts +4 -0
- package/src/site/csp.ts +102 -0
- package/src/site/headers-emitter.ts +2 -1
- package/src/site/image-transform.ts +1 -1
- package/src/site/locale-negotiation.ts +44 -14
- package/src/site/site-build.ts +105 -29
- package/src/site/site-loader.ts +2 -1
- package/src/site/social-image.ts +159 -0
- package/src/site/validate-command.ts +54 -34
- package/src/targets/compile-client.ts +20 -9
- package/src/targets/compile-element.ts +14 -6
- package/src/targets/compile-server.ts +3 -2
- package/src/targets/compile-static.ts +5 -4
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
* @docs framework/site/i18n
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
|
+
import { withBase } from "@jxsuite/schema/asset-paths";
|
|
26
27
|
import type { ResolvedI18n } from "./i18n.ts";
|
|
27
28
|
|
|
28
29
|
/** One `Accept-Language` entry: a language range and the quality it was offered at. */
|
|
@@ -109,12 +110,14 @@ export function lookupRange(range: string, available: readonly string[]): string
|
|
|
109
110
|
/**
|
|
110
111
|
* The locale to serve a request carrying this `Accept-Language`, always one of `available`.
|
|
111
112
|
*
|
|
112
|
-
* `*`
|
|
113
|
-
*
|
|
113
|
+
* `*` is skipped, because RFC 4647 §3.4 says so: a `*` followed by other ranges defers to them, and
|
|
114
|
+
* a `*` that nothing follows takes the default value, which is `fallback`. The answer therefore
|
|
115
|
+
* never depends on the order of `available`.
|
|
114
116
|
*
|
|
115
117
|
* @param {string | null | undefined} header - The raw `Accept-Language`, if any
|
|
116
|
-
* @param {readonly string[]} available - Canonical tags
|
|
117
|
-
* @param {string} fallback - The
|
|
118
|
+
* @param {readonly string[]} available - Canonical tags; the answer does not depend on their order
|
|
119
|
+
* @param {string} fallback - The site's `defaultLocale`: the answer when nothing matches, and to a
|
|
120
|
+
* trailing `*`
|
|
118
121
|
* @returns {string}
|
|
119
122
|
*/
|
|
120
123
|
export function negotiateLocale(
|
|
@@ -127,7 +130,9 @@ export function negotiateLocale(
|
|
|
127
130
|
}
|
|
128
131
|
for (const { range } of parseAcceptLanguage(header)) {
|
|
129
132
|
if (range === "*") {
|
|
130
|
-
|
|
133
|
+
// RFC 4647 §3.4 reads: "If the language range `*` is followed by other language ranges, it
|
|
134
|
+
// Is skipped. If it is the only one, or none follows, the default value is computed."
|
|
135
|
+
continue;
|
|
131
136
|
}
|
|
132
137
|
const match = lookupRange(range, available);
|
|
133
138
|
if (match !== null) {
|
|
@@ -137,6 +142,20 @@ export function negotiateLocale(
|
|
|
137
142
|
return fallback;
|
|
138
143
|
}
|
|
139
144
|
|
|
145
|
+
/**
|
|
146
|
+
* Whether the site root has something to negotiate, and so whether a worker answers it.
|
|
147
|
+
*
|
|
148
|
+
* The root has a choice to make with two locales, and under `prefix-always` it has no page of its
|
|
149
|
+
* own even with one (site-architecture.md §13.6). The middleware, the Pages worker exemption and
|
|
150
|
+
* the `_routes.json` root entry all read this one definition.
|
|
151
|
+
*
|
|
152
|
+
* @param {ResolvedI18n | null} i18n
|
|
153
|
+
* @returns {boolean}
|
|
154
|
+
*/
|
|
155
|
+
export function negotiatesRoot(i18n: ResolvedI18n | null): boolean {
|
|
156
|
+
return i18n !== null && (i18n.locales.length > 1 || i18n.routing === "prefix-always");
|
|
157
|
+
}
|
|
158
|
+
|
|
140
159
|
/**
|
|
141
160
|
* The site-absolute path a locale's home page lives at.
|
|
142
161
|
*
|
|
@@ -172,23 +191,34 @@ export function localeHome(locale: string, i18n: ResolvedI18n): string {
|
|
|
172
191
|
* in one language for every later reader. That is worse than not negotiating at all, and it is
|
|
173
192
|
* invisible to the author — whose own browser was the first visitor.
|
|
174
193
|
*
|
|
194
|
+
* **Under the deployment base.** Every other worker route is registered under the base
|
|
195
|
+
* (site-architecture.md §14.7), so the middleware registers at the based root and every home it
|
|
196
|
+
* redirects to carries the base too. An unbased `app.use('/')` matches no request a based site
|
|
197
|
+
* receives.
|
|
198
|
+
*
|
|
175
199
|
* @param {ResolvedI18n | null} i18n
|
|
176
|
-
* @
|
|
200
|
+
* @param {string} [base] - The deployment base path (`""` or `/m/site`)
|
|
201
|
+
* @returns {string} JS source, or "" when the root has nothing to negotiate
|
|
202
|
+
* ({@link negotiatesRoot})
|
|
177
203
|
*/
|
|
178
|
-
export function localeNegotiationMiddleware(i18n: ResolvedI18n | null): string {
|
|
179
|
-
if (i18n === null || i18n
|
|
204
|
+
export function localeNegotiationMiddleware(i18n: ResolvedI18n | null, base = ""): string {
|
|
205
|
+
if (i18n === null || !negotiatesRoot(i18n)) {
|
|
180
206
|
return "";
|
|
181
207
|
}
|
|
182
208
|
const locales = JSON.stringify(i18n.locales);
|
|
183
209
|
const fallback = JSON.stringify(i18n.defaultLocale);
|
|
184
210
|
const homes = JSON.stringify(
|
|
185
|
-
Object.fromEntries(
|
|
211
|
+
Object.fromEntries(
|
|
212
|
+
i18n.locales.map((locale) => [locale, withBase(base, localeHome(locale, i18n))]),
|
|
213
|
+
),
|
|
186
214
|
);
|
|
215
|
+
const root = JSON.stringify(withBase(base, "/"));
|
|
187
216
|
|
|
188
217
|
return `
|
|
189
218
|
// ─── Locale negotiation (RFC 4647 Lookup over Accept-Language) ───────────────
|
|
190
219
|
const JX_LOCALES = ${locales}
|
|
191
220
|
const JX_DEFAULT_LOCALE = ${fallback}
|
|
221
|
+
const JX_ROOT = ${root}
|
|
192
222
|
const JX_LOCALE_HOMES = ${homes}
|
|
193
223
|
|
|
194
224
|
function jxParseAcceptLanguage(header) {
|
|
@@ -229,24 +259,24 @@ function jxLookupRange(range, available) {
|
|
|
229
259
|
function jxNegotiateLocale(header, available, fallback) {
|
|
230
260
|
if (typeof header !== 'string' || header.trim() === '') return fallback
|
|
231
261
|
for (const range of jxParseAcceptLanguage(header)) {
|
|
232
|
-
if (range === '*')
|
|
262
|
+
if (range === '*') continue
|
|
233
263
|
const match = jxLookupRange(range, available)
|
|
234
264
|
if (match !== null) return match
|
|
235
265
|
}
|
|
236
266
|
return fallback
|
|
237
267
|
}
|
|
238
268
|
|
|
239
|
-
app.use(
|
|
269
|
+
app.use(JX_ROOT, async (c, next) => {
|
|
240
270
|
const locale = jxNegotiateLocale(c.req.header('accept-language'), JX_LOCALES, JX_DEFAULT_LOCALE)
|
|
241
|
-
const home = JX_LOCALE_HOMES[locale] ||
|
|
242
|
-
if (home !==
|
|
271
|
+
const home = JX_LOCALE_HOMES[locale] || JX_ROOT
|
|
272
|
+
if (home !== JX_ROOT) {
|
|
243
273
|
// 302, never 301: the target depends on the request, so it must never be cached as permanent.
|
|
244
274
|
return new Response(null, {
|
|
245
275
|
headers: { 'Content-Language': locale, Location: home, Vary: 'Accept-Language' },
|
|
246
276
|
status: 302,
|
|
247
277
|
})
|
|
248
278
|
}
|
|
249
|
-
//
|
|
279
|
+
// The root already holds this locale (prefix-except-default). Let the chain serve it, then say the
|
|
250
280
|
// Response depended on the header — a cache that missed this would pin every visitor to it.
|
|
251
281
|
await next()
|
|
252
282
|
const res = new Response(c.res.body, c.res)
|
package/src/site/site-build.ts
CHANGED
|
@@ -39,6 +39,7 @@ import {
|
|
|
39
39
|
} from "@jxsuite/schema/guards";
|
|
40
40
|
import { cemManifest, cemManifestText } from "@jxsuite/schema/cem-manifest";
|
|
41
41
|
import type { CemDefinition } from "@jxsuite/schema/cem-manifest";
|
|
42
|
+
import { DEFAULT_CHARSET } from "@jxsuite/schema/defs";
|
|
42
43
|
import { errorMessage } from "@jxsuite/schema/parse";
|
|
43
44
|
import {
|
|
44
45
|
isNpmSpecifier,
|
|
@@ -48,6 +49,7 @@ import {
|
|
|
48
49
|
siteBasePath,
|
|
49
50
|
withBase,
|
|
50
51
|
} from "@jxsuite/schema/asset-paths";
|
|
52
|
+
import { resolveBuildTime } from "./build-time.ts";
|
|
51
53
|
import { rebaseDocument, rewriteCssUrls, rewriteHtmlBase } from "./base-path.ts";
|
|
52
54
|
import {
|
|
53
55
|
CLIENT_EXTERNALS,
|
|
@@ -59,6 +61,7 @@ import {
|
|
|
59
61
|
resolveSidecarEntry,
|
|
60
62
|
} from "./bundler.ts";
|
|
61
63
|
import type { BundleRequest } from "./bundler.ts";
|
|
64
|
+
import { negotiatesRoot } from "./locale-negotiation.ts";
|
|
62
65
|
import { loadProjectConfig } from "./site-loader.ts";
|
|
63
66
|
import type { ResolvedProjectConfig } from "./site-loader.ts";
|
|
64
67
|
import {
|
|
@@ -91,10 +94,13 @@ import {
|
|
|
91
94
|
import { layoutChain, resolveLayout } from "./layout-resolver.ts";
|
|
92
95
|
import { dedupeServerEntries, documentServerEntries } from "./server-entries.ts";
|
|
93
96
|
import type { DedupedServerEntries, ServerEntryRecord } from "./server-entries.ts";
|
|
94
|
-
import { mergeHead, renderHead
|
|
97
|
+
import { unrenderedHeadWarnings, mergeHead, renderHead } from "@jxsuite/site/head-merger";
|
|
98
|
+
import { pageDescription } from "@jxsuite/site/context";
|
|
99
|
+
import { readPageFacts } from "@jxsuite/site/layout";
|
|
95
100
|
import type { PagePagination } from "@jxsuite/site/pagination";
|
|
96
101
|
import { unregisteredHeadRelations } from "./link-relations.ts";
|
|
97
102
|
import { injectContext } from "./context-injection.ts";
|
|
103
|
+
import { joinChildren } from "../child-separator.ts";
|
|
98
104
|
import { compile, compileSiteServer } from "../compiler.ts";
|
|
99
105
|
import type { CompileOptions } from "../compiler.ts";
|
|
100
106
|
import { compileElement } from "../targets/compile-element.ts";
|
|
@@ -140,6 +146,7 @@ import { SLOT_ATTR } from "@jxsuite/runtime";
|
|
|
140
146
|
import { resolvePrototypes } from "./prototype-resolver.ts";
|
|
141
147
|
import { classEntrySource, locateClass, readsBuildContext } from "./external-class.ts";
|
|
142
148
|
import { literalReplacement, transformImageNodes } from "./image-transform.ts";
|
|
149
|
+
import { withSocialImageSize } from "./social-image.ts";
|
|
143
150
|
import { collectCspSources, emptyCspSources } from "./csp.ts";
|
|
144
151
|
import { resolveShadowMode } from "../shadow.ts";
|
|
145
152
|
import {
|
|
@@ -192,6 +199,7 @@ import type {
|
|
|
192
199
|
JxMappedArray,
|
|
193
200
|
JxPrototypeDef,
|
|
194
201
|
JxStateDefinition,
|
|
202
|
+
JxStateObject,
|
|
195
203
|
JxStyle,
|
|
196
204
|
ProjectConfig,
|
|
197
205
|
} from "@jxsuite/schema/types";
|
|
@@ -1027,8 +1035,9 @@ export async function buildSite(
|
|
|
1027
1035
|
* `prefix-always` with no adapter, and no page at `/`. The mode leaves the root for negotiation
|
|
1028
1036
|
* to answer (§13.6), negotiation needs a request, and a static deployment never sees one — so the
|
|
1029
1037
|
* site's front door is a 404 and nothing else in the build says so. `unprefixedRoutes` above
|
|
1030
|
-
* deliberately never reports `/`, because under an adapter it is handled
|
|
1031
|
-
*
|
|
1038
|
+
* deliberately never reports `/`, because under an adapter it is handled: `negotiatesRoot` is
|
|
1039
|
+
* true for every `prefix-always` site, so any adapter's worker answers the root, and `!adapter`
|
|
1040
|
+
* is exactly the unhandled shape.
|
|
1032
1041
|
*
|
|
1033
1042
|
* A warning rather than a generated redirect: which URL the root should send a visitor to is a
|
|
1034
1043
|
* deployment decision, and inventing one would be the compiler overruling a choice it cannot see.
|
|
@@ -1055,6 +1064,9 @@ export async function buildSite(
|
|
|
1055
1064
|
* therefore on every page.
|
|
1056
1065
|
*/
|
|
1057
1066
|
const warnedRelations = new Set<string>();
|
|
1067
|
+
/* Head material the build does not render (a flat attribute key, a `<title>` entry) is as silent
|
|
1068
|
+
as a mistyped `rel`, and lives in the same shared heads, so it is warned once per message too. */
|
|
1069
|
+
const warnedUnrenderedHead = new Set<string>();
|
|
1058
1070
|
for (const route of routes) {
|
|
1059
1071
|
const mismatch = undeclaredLocalePrefix(route.urlPattern, i18n);
|
|
1060
1072
|
if (mismatch && !warnedLocalePrefixes.has(mismatch.segment)) {
|
|
@@ -1103,6 +1115,13 @@ export async function buildSite(
|
|
|
1103
1115
|
}
|
|
1104
1116
|
}
|
|
1105
1117
|
|
|
1118
|
+
for (const message of result.unrenderedHeadMaterial) {
|
|
1119
|
+
if (!warnedUnrenderedHead.has(message)) {
|
|
1120
|
+
warnedUnrenderedHead.add(message);
|
|
1121
|
+
console.warn(message);
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1106
1125
|
// Inject component CSS and JS scripts
|
|
1107
1126
|
if (compiledComponentTags.length > 0) {
|
|
1108
1127
|
result.html = injectComponentScripts(
|
|
@@ -1305,9 +1324,13 @@ export async function buildSite(
|
|
|
1305
1324
|
|
|
1306
1325
|
// Cloudflare Pages uses advanced mode (_worker.js inside the build output) — the
|
|
1307
1326
|
// Functions/ directory convention only works from the project root, not from dist/.
|
|
1308
|
-
// A
|
|
1327
|
+
// A Pages site with no server tier and no root to negotiate needs no worker; one with mounts,
|
|
1328
|
+
// Server entries or a negotiating root (site-architecture.md §13.6) always gets one.
|
|
1309
1329
|
const skipWorker =
|
|
1310
|
-
adapter === "cloudflare-pages" &&
|
|
1330
|
+
adapter === "cloudflare-pages" &&
|
|
1331
|
+
serverEntries.length === 0 &&
|
|
1332
|
+
mounts.length === 0 &&
|
|
1333
|
+
!negotiatesRoot(i18n);
|
|
1311
1334
|
const workerSource = skipWorker
|
|
1312
1335
|
? null
|
|
1313
1336
|
: compileSiteServer(serverEntries, {
|
|
@@ -1344,7 +1367,7 @@ export async function buildSite(
|
|
|
1344
1367
|
writeFileSync(
|
|
1345
1368
|
resolve(outDir, "_routes.json"),
|
|
1346
1369
|
/*
|
|
1347
|
-
* `/` joins the include list only when
|
|
1370
|
+
* `/` joins the include list only when the worker negotiates the root: Pages invokes the
|
|
1348
1371
|
* worker for included paths only, so an uninvoked middleware is an inert one. Both carry
|
|
1349
1372
|
* the deployment base, because Pages matches them against the request path, and the
|
|
1350
1373
|
* worker's own routes are registered under it (site-architecture.md §14.7).
|
|
@@ -1352,8 +1375,8 @@ export async function buildSite(
|
|
|
1352
1375
|
`${JSON.stringify(
|
|
1353
1376
|
{
|
|
1354
1377
|
exclude: [],
|
|
1355
|
-
include: (i18n
|
|
1356
|
-
|
|
1378
|
+
include: (negotiatesRoot(i18n) ? ["/", "/_jx/*"] : ["/_jx/*"]).map((pattern) =>
|
|
1379
|
+
withBase(basePath, pattern),
|
|
1357
1380
|
),
|
|
1358
1381
|
version: 1,
|
|
1359
1382
|
},
|
|
@@ -1500,6 +1523,19 @@ export async function buildSite(
|
|
|
1500
1523
|
// (search indexes, feeds, …). The host writes the returned files so extensions stay pure;
|
|
1501
1524
|
// Paths are outDir-relative and guarded against traversal. Note the `public/` copy (7c)
|
|
1502
1525
|
// Runs later and can shadow emitted files — same semantics as sitemap.xml.
|
|
1526
|
+
/*
|
|
1527
|
+
* One timestamp for every emitter, resolved before the first runs so two emitters in one build
|
|
1528
|
+
* agree. A malformed SOURCE_DATE_EPOCH is a reported build error rather than a silent switch to
|
|
1529
|
+
* the clock, and the build still finishes with the clock so the other errors are reported too.
|
|
1530
|
+
*/
|
|
1531
|
+
let buildTime: string;
|
|
1532
|
+
try {
|
|
1533
|
+
buildTime = resolveBuildTime(process.env);
|
|
1534
|
+
} catch (error) {
|
|
1535
|
+
errors.push(errorMessage(error));
|
|
1536
|
+
console.error(errorMessage(error));
|
|
1537
|
+
buildTime = resolveBuildTime({});
|
|
1538
|
+
}
|
|
1503
1539
|
for (const entry of registry.emitters()) {
|
|
1504
1540
|
const sectionKey = entry.project?.key;
|
|
1505
1541
|
const sectionValue = sectionKey ? projectConfig[sectionKey] : undefined;
|
|
@@ -1514,6 +1550,7 @@ export async function buildSite(
|
|
|
1514
1550
|
/* The emit contract (extensions.md §8.4) answers outDir-relative files, or null for none; each
|
|
1515
1551
|
`path` is still checked for traversal below before anything is written. */
|
|
1516
1552
|
const emitted = await entry.call("emit", sectionValue ?? null, {
|
|
1553
|
+
buildTime,
|
|
1517
1554
|
projectConfig,
|
|
1518
1555
|
root: projectRoot,
|
|
1519
1556
|
routes,
|
|
@@ -1797,25 +1834,29 @@ async function compilePage(
|
|
|
1797
1834
|
...layoutLevels.flatMap((level) => documentServerEntries(level.doc, level.path, projectRoot)),
|
|
1798
1835
|
];
|
|
1799
1836
|
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
const pageHead =
|
|
1804
|
-
(pageDoc.$head ?? layoutDoc._pageHead ?? []) as JxHeadEntry[],
|
|
1805
|
-
pageDoc.description,
|
|
1806
|
-
);
|
|
1837
|
+
/* What the page says about itself, read from the page and never from the wrapped document, which
|
|
1838
|
+
is a clone of the outermost layout (site-architecture.md §5.5). */
|
|
1839
|
+
const facts = readPageFacts(pageDoc);
|
|
1840
|
+
const pageHead = [...(facts.head ?? [])];
|
|
1807
1841
|
const layoutHead = layoutDoc.$head ?? [];
|
|
1808
|
-
|
|
1809
|
-
string) into it when the page has one. */
|
|
1810
|
-
const pageTitle = (pageDoc.title ?? layoutDoc._pageTitle ?? null) as string | null;
|
|
1811
|
-
|
|
1812
|
-
// Clean up internal properties
|
|
1813
|
-
delete layoutDoc._pageHead;
|
|
1814
|
-
delete layoutDoc._pageTitle;
|
|
1842
|
+
const pageTitle = facts.title ?? null;
|
|
1815
1843
|
|
|
1816
1844
|
// Inject $site and $page context
|
|
1817
1845
|
const declaredStateKeys = new Set(Object.keys(layoutDoc.state ?? {}));
|
|
1818
|
-
injectContext(
|
|
1846
|
+
injectContext(
|
|
1847
|
+
layoutDoc,
|
|
1848
|
+
projectConfig,
|
|
1849
|
+
route,
|
|
1850
|
+
projectRoot,
|
|
1851
|
+
locale.i18n,
|
|
1852
|
+
locale.translations,
|
|
1853
|
+
facts,
|
|
1854
|
+
);
|
|
1855
|
+
/* The title is page metadata and never the root's `title` attribute, which would be a tooltip over
|
|
1856
|
+
the whole page. `pageTitle` was read above and `injectContext` has just read `$page.title`; with
|
|
1857
|
+
no layout this is `pageDoc` itself, and with one it is a clone of the outermost layout, whose own
|
|
1858
|
+
`title` is no more the page's (site-architecture.md §8.1). */
|
|
1859
|
+
delete layoutDoc.title;
|
|
1819
1860
|
/* The project `state` entries this page did not declare, nor its layout: the ones the injection
|
|
1820
1861
|
just copied in, which the page keeps only while something on it reads them (compiler.md §8.1). */
|
|
1821
1862
|
const inheritedStateKeys = Object.keys(projectConfig.state ?? {}).filter(
|
|
@@ -1830,7 +1871,7 @@ async function compilePage(
|
|
|
1830
1871
|
const language = pageLanguage({
|
|
1831
1872
|
defaults: projectConfig.defaults,
|
|
1832
1873
|
pageDir: isString(pageDoc.$dir) ? pageDoc.$dir : undefined,
|
|
1833
|
-
pageLang:
|
|
1874
|
+
pageLang: facts.lang,
|
|
1834
1875
|
routeLocale: localeOfRoute(route.urlPattern, locale.i18n),
|
|
1835
1876
|
});
|
|
1836
1877
|
|
|
@@ -1869,6 +1910,22 @@ async function compilePage(
|
|
|
1869
1910
|
holdMutable: true,
|
|
1870
1911
|
});
|
|
1871
1912
|
|
|
1913
|
+
/*
|
|
1914
|
+
* What the page says about itself is settled into `$page` before anything else reads it, so a
|
|
1915
|
+
* layout's `$head` (`og:title`) and its tree read `${state.$page.title}` as the text the page's
|
|
1916
|
+
* `<title>` shows, never as a template (site-architecture.md §5.5). The page's own `state` is
|
|
1917
|
+
* where a templated title or description resolves from, and it is merged over the layout's, so
|
|
1918
|
+
* the scope already holds it. A page that ships its `state` to the browser ships the settled
|
|
1919
|
+
* values, not the templates.
|
|
1920
|
+
*/
|
|
1921
|
+
const settlePage = (fields: JxStateObject) => {
|
|
1922
|
+
/* SAFETY: `injectContext` wrote `state.$page` as an object above, and `buildInitialScope`
|
|
1923
|
+
cloned it into `scope.$page`; both are the `$page` this assigns into. */
|
|
1924
|
+
Object.assign(layoutDoc.state!.$page as JxStateObject, fields);
|
|
1925
|
+
/* SAFETY: as above, the scope's `$page` is that clone. */
|
|
1926
|
+
Object.assign(scope.$page as JxStateObject, fields);
|
|
1927
|
+
};
|
|
1928
|
+
|
|
1872
1929
|
// Determine the page title — resolve template strings against the scope
|
|
1873
1930
|
let title = pageTitle ?? projectConfig.name;
|
|
1874
1931
|
if (isTemplateString(title)) {
|
|
@@ -1877,6 +1934,7 @@ async function compilePage(
|
|
|
1877
1934
|
the markup as text, so a non-string result renders as its string form. */
|
|
1878
1935
|
title = (evaluateStaticTemplate(title, scope) as string | null) ?? title;
|
|
1879
1936
|
}
|
|
1937
|
+
settlePage({ title });
|
|
1880
1938
|
|
|
1881
1939
|
// Resolve template strings in $head entries
|
|
1882
1940
|
/*
|
|
@@ -1894,6 +1952,10 @@ async function compilePage(
|
|
|
1894
1952
|
resolveHeadTemplates(pageHead, scope),
|
|
1895
1953
|
rewriteNpmAsset,
|
|
1896
1954
|
);
|
|
1955
|
+
const description = pageDescription(resolvedPageHead);
|
|
1956
|
+
if (description !== undefined) {
|
|
1957
|
+
settlePage({ description });
|
|
1958
|
+
}
|
|
1897
1959
|
const resolvedLayoutHead = resolveHeadBareSpecifiers(
|
|
1898
1960
|
resolveHeadTemplates(layoutHead, scope),
|
|
1899
1961
|
rewriteNpmAsset,
|
|
@@ -2039,9 +2101,9 @@ async function compilePage(
|
|
|
2039
2101
|
];
|
|
2040
2102
|
|
|
2041
2103
|
// Merge $head from site + layout + page
|
|
2042
|
-
const
|
|
2104
|
+
const mergedHeadBase = mergeHead(resolvedSiteHead, resolvedLayoutHead, resolvedPageHead, {
|
|
2043
2105
|
title,
|
|
2044
|
-
charset: projectConfig.defaults.charset ??
|
|
2106
|
+
charset: projectConfig.defaults.charset ?? DEFAULT_CHARSET,
|
|
2045
2107
|
siteName: projectConfig.name,
|
|
2046
2108
|
siteUrl: projectConfig.url,
|
|
2047
2109
|
...(locale.alternates.length > 0 && { alternates: locale.alternates }),
|
|
@@ -2054,6 +2116,12 @@ async function compilePage(
|
|
|
2054
2116
|
pageUrl: servedRoute(route.urlPattern, projectConfig.build.trailingSlash),
|
|
2055
2117
|
}),
|
|
2056
2118
|
});
|
|
2119
|
+
// `og:image:width` and `og:image:height`, read from the image file when the build can open it (§8.4.4).
|
|
2120
|
+
const mergedHead = await withSocialImageSize(mergedHeadBase, {
|
|
2121
|
+
mounts: assetMounts,
|
|
2122
|
+
projectRoot,
|
|
2123
|
+
siteUrl: projectConfig.url,
|
|
2124
|
+
});
|
|
2057
2125
|
|
|
2058
2126
|
// Merge project-level $media into the layout document so responsive queries are available
|
|
2059
2127
|
if (projectConfig.$media) {
|
|
@@ -2167,6 +2235,13 @@ async function compilePage(
|
|
|
2167
2235
|
* say it once instead of four hundred times.
|
|
2168
2236
|
*/
|
|
2169
2237
|
unregisteredRelations: unregisteredHeadRelations(mergedHead),
|
|
2238
|
+
/* Over the authored arrays, not the resolved ones: the extension, manifest and service-worker
|
|
2239
|
+
entries are generated, and a flat key the author wrote is what the warning is for. */
|
|
2240
|
+
unrenderedHeadMaterial: unrenderedHeadWarnings([
|
|
2241
|
+
...(projectConfig.$head ?? []),
|
|
2242
|
+
...layoutHead,
|
|
2243
|
+
...pageHead,
|
|
2244
|
+
]),
|
|
2170
2245
|
serverEntries,
|
|
2171
2246
|
};
|
|
2172
2247
|
}
|
|
@@ -2938,9 +3013,10 @@ function expandComponents(
|
|
|
2938
3013
|
const slotId =
|
|
2939
3014
|
!shadow && !isStatic && definitionHasSlot(def.children) ? nextSlotId(context) : null;
|
|
2940
3015
|
const slotContent = shadow
|
|
2941
|
-
? (
|
|
2942
|
-
.map((c: StaticChild) => renderSlotted(c))
|
|
2943
|
-
|
|
3016
|
+
? joinChildren(
|
|
3017
|
+
(Array.isArray(children) ? children : []).map((c: StaticChild) => renderSlotted(c)),
|
|
3018
|
+
{ separator: "\n" },
|
|
3019
|
+
)
|
|
2944
3020
|
: null;
|
|
2945
3021
|
const innerHTML = preRenderComponentHtml(
|
|
2946
3022
|
def,
|
package/src/site/site-loader.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { existsSync, readFileSync } from "node:fs";
|
|
9
|
+
import { DEFAULT_CHARSET } from "@jxsuite/schema/defs";
|
|
9
10
|
import type { ImageConfig, JxDocumentValue, ProjectConfig } from "@jxsuite/schema/types";
|
|
10
11
|
import { errorMessage } from "@jxsuite/schema/parse";
|
|
11
12
|
import { parseProjectSource } from "@jxsuite/schema/project-file";
|
|
@@ -43,7 +44,7 @@ const DEFAULTS = {
|
|
|
43
44
|
trailingSlash: "always",
|
|
44
45
|
},
|
|
45
46
|
defaults: {
|
|
46
|
-
charset:
|
|
47
|
+
charset: DEFAULT_CHARSET,
|
|
47
48
|
lang: "en",
|
|
48
49
|
layout: null,
|
|
49
50
|
},
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The size of a page's social image, stated for the crawlers that ask for it.
|
|
3
|
+
*
|
|
4
|
+
* A link preview is drawn before the image has been fetched, so Open Graph's `og:image:width` and
|
|
5
|
+
* `og:image:height` let a consumer reserve the card's box (and decide between a large and a small
|
|
6
|
+
* card) without downloading the picture first. A page states the image (`og:image`) and the build
|
|
7
|
+
* already holds the file, so the two numbers are read from it rather than typed twice and left to
|
|
8
|
+
* drift when the image is replaced (site-architecture.md §8.4.4).
|
|
9
|
+
*
|
|
10
|
+
* Only an image the build can open is measured: one under `public/` or an extension's asset mount,
|
|
11
|
+
* named by a site-absolute path or by an absolute URL under the project's own `url`. A remote
|
|
12
|
+
* image, a `data:` URI, a file that does not exist and one whose header the compiler cannot read
|
|
13
|
+
* are left alone, because a wrong size is worse than none. The author's own `og:image:width` or
|
|
14
|
+
* `og:image:height` always wins.
|
|
15
|
+
*
|
|
16
|
+
* @docs framework/site/seo
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { closeSync, existsSync, openSync, readSync, statSync } from "node:fs";
|
|
20
|
+
import { getImageMetadata } from "./image-optimizer.ts";
|
|
21
|
+
import { resolveImagePath } from "./image-transform.ts";
|
|
22
|
+
import { isNonNullObject, isString } from "@jxsuite/schema/guards";
|
|
23
|
+
|
|
24
|
+
import type { AssetMount } from "@jxsuite/schema/asset-paths";
|
|
25
|
+
import type { JxHeadEntry } from "@jxsuite/schema/types";
|
|
26
|
+
|
|
27
|
+
/** What the build knows about where an image named in the head may live. */
|
|
28
|
+
export interface SocialImageContext {
|
|
29
|
+
projectRoot: string;
|
|
30
|
+
/** The project's `url`, whose origin and path an absolute `og:image` is read relative to. */
|
|
31
|
+
siteUrl?: string | undefined;
|
|
32
|
+
mounts: readonly AssetMount[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Sizes already read, keyed by the file's path, modified time and byte length. */
|
|
36
|
+
const sizeCache = new Map<string, { width: number; height: number } | null>();
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The size of a GIF, from the 10 bytes that carry it. The compiler's native core decodes no GIF
|
|
40
|
+
* (§9.2.3), but the logical screen descriptor is two little-endian words after the signature.
|
|
41
|
+
*
|
|
42
|
+
* @param {string} absolute - Path to a file
|
|
43
|
+
* @returns {{ width: number; height: number } | null} Null when the file is not a GIF
|
|
44
|
+
*/
|
|
45
|
+
function gifSize(absolute: string): { width: number; height: number } | null {
|
|
46
|
+
const head = new Uint8Array(10);
|
|
47
|
+
const fd = openSync(absolute, "r");
|
|
48
|
+
try {
|
|
49
|
+
if (readSync(fd, head, 0, 10, 0) < 10) {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
} finally {
|
|
53
|
+
closeSync(fd);
|
|
54
|
+
}
|
|
55
|
+
const signature = String.fromCodePoint(...head.subarray(0, 6));
|
|
56
|
+
if (signature !== "GIF87a" && signature !== "GIF89a") {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
const view = new DataView(head.buffer);
|
|
60
|
+
const width = view.getUint16(6, true);
|
|
61
|
+
const height = view.getUint16(8, true);
|
|
62
|
+
return width > 0 && height > 0 ? { height, width } : null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The size of an image file as a viewer sees it, or null when the build cannot tell.
|
|
67
|
+
*
|
|
68
|
+
* @param {string} absolute - Path to the file
|
|
69
|
+
* @returns {Promise<{ width: number; height: number } | null>}
|
|
70
|
+
*/
|
|
71
|
+
async function readSize(absolute: string): Promise<{ width: number; height: number } | null> {
|
|
72
|
+
const stat = statSync(absolute);
|
|
73
|
+
const key = `${absolute}:${stat.mtimeMs}:${stat.size}`;
|
|
74
|
+
if (sizeCache.has(key)) {
|
|
75
|
+
return sizeCache.get(key) ?? null;
|
|
76
|
+
}
|
|
77
|
+
let size: { width: number; height: number } | null = null;
|
|
78
|
+
try {
|
|
79
|
+
size = gifSize(absolute);
|
|
80
|
+
if (size === null) {
|
|
81
|
+
const { height, width } = await getImageMetadata(absolute);
|
|
82
|
+
size = width > 0 && height > 0 ? { height, width } : null;
|
|
83
|
+
}
|
|
84
|
+
} catch {
|
|
85
|
+
// A header the compiler cannot read (an SVG, an unknown format, no native addon) states no size.
|
|
86
|
+
size = null;
|
|
87
|
+
}
|
|
88
|
+
sizeCache.set(key, size);
|
|
89
|
+
return size;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The site-absolute path a head value names, or null when it names no file the build can open.
|
|
94
|
+
*
|
|
95
|
+
* @param {string} value - The `og:image` content
|
|
96
|
+
* @param {string | undefined} siteUrl - The project's `url`
|
|
97
|
+
* @returns {string | null}
|
|
98
|
+
*/
|
|
99
|
+
function localPath(value: string, siteUrl: string | undefined): string | null {
|
|
100
|
+
let path = value.trim();
|
|
101
|
+
const base = siteUrl?.replace(/\/+$/, "");
|
|
102
|
+
if (base && path.startsWith(`${base}/`)) {
|
|
103
|
+
path = path.slice(base.length);
|
|
104
|
+
}
|
|
105
|
+
// `//host/x` is a scheme-relative URL and a bare `x.png` names no site path: neither is ours.
|
|
106
|
+
if (!path.startsWith("/") || path.startsWith("//")) {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
path = path.split("#")[0]!.split("?")[0]!;
|
|
110
|
+
try {
|
|
111
|
+
path = decodeURIComponent(path);
|
|
112
|
+
} catch {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
return path.split("/").includes("..") ? null : path;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The head with `og:image:width` and `og:image:height` entries after `og:image`, when the build can
|
|
120
|
+
* read that image's size and the author stated neither.
|
|
121
|
+
*
|
|
122
|
+
* @param {JxHeadEntry[]} head - The merged head
|
|
123
|
+
* @param {SocialImageContext} context
|
|
124
|
+
* @returns {Promise<JxHeadEntry[]>} The same array when nothing was added
|
|
125
|
+
*/
|
|
126
|
+
export async function withSocialImageSize(
|
|
127
|
+
head: JxHeadEntry[],
|
|
128
|
+
context: SocialImageContext,
|
|
129
|
+
): Promise<JxHeadEntry[]> {
|
|
130
|
+
const isMeta = (entry: JxHeadEntry, property: string) =>
|
|
131
|
+
isNonNullObject(entry) && entry.tagName === "meta" && entry.attributes?.property === property;
|
|
132
|
+
const at = head.findLastIndex((entry) => isMeta(entry, "og:image"));
|
|
133
|
+
if (at === -1 || head.some((e) => isMeta(e, "og:image:width") || isMeta(e, "og:image:height"))) {
|
|
134
|
+
return head;
|
|
135
|
+
}
|
|
136
|
+
const content = head[at]!.attributes?.content;
|
|
137
|
+
const path = isString(content) ? localPath(content, context.siteUrl) : null;
|
|
138
|
+
if (path === null) {
|
|
139
|
+
return head;
|
|
140
|
+
}
|
|
141
|
+
const absolute = resolveImagePath(path, context.projectRoot, context.mounts);
|
|
142
|
+
if (!existsSync(absolute) || !statSync(absolute).isFile()) {
|
|
143
|
+
return head;
|
|
144
|
+
}
|
|
145
|
+
const size = await readSize(absolute);
|
|
146
|
+
if (size === null) {
|
|
147
|
+
return head;
|
|
148
|
+
}
|
|
149
|
+
const meta = (property: string, value: number): JxHeadEntry => ({
|
|
150
|
+
attributes: { content: String(value), property },
|
|
151
|
+
tagName: "meta",
|
|
152
|
+
});
|
|
153
|
+
return [
|
|
154
|
+
...head.slice(0, at + 1),
|
|
155
|
+
meta("og:image:width", size.width),
|
|
156
|
+
meta("og:image:height", size.height),
|
|
157
|
+
...head.slice(at + 1),
|
|
158
|
+
];
|
|
159
|
+
}
|