@easy-web/core 1.9.1 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -6
- package/dist/contracts/capabilities.d.ts +3 -0
- package/dist/contracts/capabilities.d.ts.map +1 -1
- package/dist/contracts/content-composition.d.ts +16 -0
- package/dist/contracts/content-composition.d.ts.map +1 -1
- package/dist/contracts/content-composition.js +8 -0
- package/dist/contracts/content-composition.js.map +1 -1
- package/dist/contracts/index.d.ts +1 -0
- package/dist/contracts/index.d.ts.map +1 -1
- package/dist/contracts/index.js +1 -0
- package/dist/contracts/index.js.map +1 -1
- package/dist/contracts/ordering.d.ts +6 -0
- package/dist/contracts/ordering.d.ts.map +1 -0
- package/dist/contracts/ordering.js +22 -0
- package/dist/contracts/ordering.js.map +1 -0
- package/dist/contracts/traits.d.ts +4 -0
- package/dist/contracts/traits.d.ts.map +1 -1
- package/dist/contracts/traits.js +3 -1
- package/dist/contracts/traits.js.map +1 -1
- package/dist/recipes/content-site.d.ts +8 -0
- package/dist/recipes/content-site.d.ts.map +1 -1
- package/dist/recipes/content-site.js +226 -42
- package/dist/recipes/content-site.js.map +1 -1
- package/dist/recipes/shell-recipe.d.ts +4 -0
- package/dist/recipes/shell-recipe.d.ts.map +1 -1
- package/dist/recipes/shell-recipe.js +127 -6
- package/dist/recipes/shell-recipe.js.map +1 -1
- package/dist/seo/index.d.ts +5 -0
- package/dist/seo/index.d.ts.map +1 -1
- package/dist/seo/index.js +7 -3
- package/dist/seo/index.js.map +1 -1
- package/dist/seo/rendered-sitemap-alternates.d.ts +7 -0
- package/dist/seo/rendered-sitemap-alternates.d.ts.map +1 -0
- package/dist/seo/rendered-sitemap-alternates.js +232 -0
- package/dist/seo/rendered-sitemap-alternates.js.map +1 -0
- package/package.json +1 -1
- package/src/contracts/__tests__/content-composition.test.ts +17 -0
- package/src/contracts/__tests__/ordering.test.ts +34 -0
- package/src/contracts/capabilities.ts +4 -0
- package/src/contracts/content-composition.ts +8 -0
- package/src/contracts/index.ts +1 -0
- package/src/contracts/ordering.ts +33 -0
- package/src/contracts/traits.ts +4 -1
- package/src/recipes/__tests__/content-site.test.ts +98 -2
- package/src/recipes/__tests__/shell-recipe.test.ts +23 -0
- package/src/recipes/content-site.ts +227 -48
- package/src/recipes/shell-recipe.ts +132 -6
- package/src/seo/__tests__/integration.test.ts +28 -0
- package/src/seo/__tests__/rendered-sitemap-alternates.test.ts +127 -0
- package/src/seo/__tests__/sitemap-options.test.ts +7 -7
- package/src/seo/index.ts +17 -3
- package/src/seo/rendered-sitemap-alternates.ts +231 -0
- package/src/type-tests/contracts.ts +6 -0
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join, sep } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import type { AstroConfig } from 'astro';
|
|
6
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
7
|
+
import { synchronizeRenderedSitemapAlternates } from '../rendered-sitemap-alternates.js';
|
|
8
|
+
|
|
9
|
+
let root: string;
|
|
10
|
+
|
|
11
|
+
afterEach(async () => {
|
|
12
|
+
if (root) await rm(root, { recursive: true, force: true });
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
function html(locale: string, canonical: string, alternates: Readonly<Record<string, string>>): string {
|
|
16
|
+
const links = Object.entries(alternates).map(([lang, href]) =>
|
|
17
|
+
`<link rel="alternate" hreflang="${lang}" href="${href}"/>`,
|
|
18
|
+
).join('');
|
|
19
|
+
return `<!doctype html><html lang="${locale}"><head><link rel="canonical" href="${canonical}"/>${links}</head><body></body></html>`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function fixture() {
|
|
23
|
+
root = await mkdtemp(join(tmpdir(), 'easy-web-sitemap-locales-'));
|
|
24
|
+
await mkdir(join(root, 'beitraege', 'beispiel'), { recursive: true });
|
|
25
|
+
await mkdir(join(root, 'entries', 'example'), { recursive: true });
|
|
26
|
+
const de = 'https://example.test/docs/beitraege/beispiel/';
|
|
27
|
+
const en = 'https://example.test/docs/entries/example/';
|
|
28
|
+
const alternates = { de, en, 'x-default': de };
|
|
29
|
+
await writeFile(join(root, 'beitraege', 'beispiel', 'index.html'), html('de', de, alternates));
|
|
30
|
+
await writeFile(join(root, 'entries', 'example', 'index.html'), html('en', en, alternates));
|
|
31
|
+
await writeFile(join(root, 'sitemap-0.xml'), `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"><url><loc>${de}</loc></url><url><loc>${en}</loc></url></urlset>`);
|
|
32
|
+
const config = {
|
|
33
|
+
site: new URL('https://example.test'),
|
|
34
|
+
base: '/docs',
|
|
35
|
+
trailingSlash: 'always',
|
|
36
|
+
build: { format: 'directory' },
|
|
37
|
+
} as AstroConfig;
|
|
38
|
+
return { config, de, en };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
describe('rendered sitemap alternates', () => {
|
|
42
|
+
it('copies reciprocal, built head alternates into the sitemap with base paths', async () => {
|
|
43
|
+
const { config, de, en } = await fixture();
|
|
44
|
+
await synchronizeRenderedSitemapAlternates(pathToFileURL(`${root}${sep}`), config, ['de', 'en'], 'de');
|
|
45
|
+
const sitemap = await readFile(join(root, 'sitemap-0.xml'), 'utf8');
|
|
46
|
+
expect(sitemap).toContain(`<xhtml:link rel="alternate" hreflang="de" href="${de}"/>`);
|
|
47
|
+
expect(sitemap).toContain(`<xhtml:link rel="alternate" hreflang="en" href="${en}"/>`);
|
|
48
|
+
expect(sitemap).not.toContain('hreflang="x-default"');
|
|
49
|
+
expect(sitemap.match(/hreflang="de"/g)).toHaveLength(2);
|
|
50
|
+
expect(sitemap.match(/hreflang="en"/g)).toHaveLength(2);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('removes sitemap alternates that are not present in the rendered page head', async () => {
|
|
54
|
+
const { config, en } = await fixture();
|
|
55
|
+
const untranslated = 'https://example.test/docs/beitraege/only-in-de/';
|
|
56
|
+
await mkdir(join(root, 'beitraege', 'only-in-de'), { recursive: true });
|
|
57
|
+
await writeFile(join(root, 'beitraege', 'only-in-de', 'index.html'), html('de', untranslated, {}));
|
|
58
|
+
const sitemapPath = join(root, 'sitemap-0.xml');
|
|
59
|
+
const sitemap = await readFile(sitemapPath, 'utf8');
|
|
60
|
+
const autoPaired = `<url><loc>${untranslated}</loc><xhtml:link rel="alternate" hreflang="en" href="${en}"/></url>`;
|
|
61
|
+
await writeFile(sitemapPath, sitemap.replace('</urlset>', `${autoPaired}</urlset>`));
|
|
62
|
+
|
|
63
|
+
await synchronizeRenderedSitemapAlternates(pathToFileURL(`${root}${sep}`), config, ['de', 'en'], 'de');
|
|
64
|
+
|
|
65
|
+
const updated = await readFile(sitemapPath, 'utf8');
|
|
66
|
+
const entry = updated.match(/<url>[\s\S]*?<\/url>/g)?.find((block) => block.includes(untranslated));
|
|
67
|
+
expect(entry).toContain(`<loc>${untranslated}</loc>`);
|
|
68
|
+
expect(entry).not.toContain('xhtml:link');
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('rejects alternates to missing built pages and non-reciprocal locale groups', async () => {
|
|
72
|
+
const { config, de, en } = await fixture();
|
|
73
|
+
await writeFile(join(root, 'entries', 'example', 'index.html'), html('en', en, { en }));
|
|
74
|
+
await expect(synchronizeRenderedSitemapAlternates(pathToFileURL(`${root}${sep}`), config, ['de', 'en'], 'de'))
|
|
75
|
+
.rejects.toThrow('not reciprocal');
|
|
76
|
+
const missing = 'https://example.test/docs/missing/';
|
|
77
|
+
await writeFile(join(root, 'beitraege', 'beispiel', 'index.html'), html('de', de, { de: missing, en: missing }));
|
|
78
|
+
await writeFile(join(root, 'entries', 'example', 'index.html'), html('en', en, { de: missing, en: missing }));
|
|
79
|
+
await expect(synchronizeRenderedSitemapAlternates(pathToFileURL(`${root}${sep}`), config, ['de', 'en'], 'de'))
|
|
80
|
+
.rejects.toThrow('no built canonical page');
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('rejects URLs outside the configured site or base path', async () => {
|
|
84
|
+
const { config, de, en } = await fixture();
|
|
85
|
+
const outsideOrigin = 'https://outside.test/docs/beitraege/beispiel/';
|
|
86
|
+
await writeFile(join(root, 'beitraege', 'beispiel', 'index.html'), html('de', de, { de, en: outsideOrigin }));
|
|
87
|
+
await writeFile(join(root, 'entries', 'example', 'index.html'), html('en', en, { de, en: outsideOrigin }));
|
|
88
|
+
await expect(synchronizeRenderedSitemapAlternates(pathToFileURL(`${root}${sep}`), config, ['de', 'en'], 'de'))
|
|
89
|
+
.rejects.toThrow('configured site origin');
|
|
90
|
+
const outsideBase = 'https://example.test/beitraege/beispiel/';
|
|
91
|
+
await writeFile(join(root, 'beitraege', 'beispiel', 'index.html'), html('de', de, { de, en: outsideBase }));
|
|
92
|
+
await writeFile(join(root, 'entries', 'example', 'index.html'), html('en', en, { de, en: outsideBase }));
|
|
93
|
+
await expect(synchronizeRenderedSitemapAlternates(pathToFileURL(`${root}${sep}`), config, ['de', 'en'], 'de'))
|
|
94
|
+
.rejects.toThrow('outside the configured base path');
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('rejects canonical URLs that do not identify their built page', async () => {
|
|
98
|
+
const { config, de, en } = await fixture();
|
|
99
|
+
const wrongCanonical = 'https://example.test/docs/entries/example/';
|
|
100
|
+
await writeFile(join(root, 'beitraege', 'beispiel', 'index.html'), html('de', wrongCanonical, { de, en }));
|
|
101
|
+
await expect(synchronizeRenderedSitemapAlternates(pathToFileURL(`${root}${sep}`), config, ['de', 'en'], 'de'))
|
|
102
|
+
.rejects.toThrow('does not match built page');
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('matches file-format pages and sitemap URLs with a base path and no trailing slash', async () => {
|
|
106
|
+
root = await mkdtemp(join(tmpdir(), 'easy-web-sitemap-file-locales-'));
|
|
107
|
+
await mkdir(join(root, 'beitraege'), { recursive: true });
|
|
108
|
+
await mkdir(join(root, 'entries'), { recursive: true });
|
|
109
|
+
const de = 'https://example.test/docs/beitraege/beispiel';
|
|
110
|
+
const en = 'https://example.test/docs/entries/example';
|
|
111
|
+
const alternates = { de, en, 'x-default': de };
|
|
112
|
+
await writeFile(join(root, 'beitraege', 'beispiel.html'), html('de', de, alternates));
|
|
113
|
+
await writeFile(join(root, 'entries', 'example.html'), html('en', en, alternates));
|
|
114
|
+
await writeFile(join(root, 'sitemap-0.xml'), `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"><url><loc>${de}</loc></url><url><loc>${en}</loc></url></urlset>`);
|
|
115
|
+
const config = {
|
|
116
|
+
site: new URL('https://example.test'),
|
|
117
|
+
base: '/docs',
|
|
118
|
+
trailingSlash: 'never',
|
|
119
|
+
build: { format: 'file' },
|
|
120
|
+
} as AstroConfig;
|
|
121
|
+
|
|
122
|
+
await synchronizeRenderedSitemapAlternates(pathToFileURL(`${root}${sep}`), config, ['de', 'en'], 'de');
|
|
123
|
+
const sitemap = await readFile(join(root, 'sitemap-0.xml'), 'utf8');
|
|
124
|
+
expect(sitemap).toContain(`<xhtml:link rel="alternate" hreflang="de" href="${de}"/>`);
|
|
125
|
+
expect(sitemap).toContain(`<xhtml:link rel="alternate" hreflang="en" href="${en}"/>`);
|
|
126
|
+
});
|
|
127
|
+
});
|
|
@@ -332,7 +332,7 @@ describe('localizedPaths validation', () => {
|
|
|
332
332
|
...baseConfig(),
|
|
333
333
|
i18n: undefined,
|
|
334
334
|
}),
|
|
335
|
-
).toThrow(/
|
|
335
|
+
).toThrow(/require `i18n` to be configured/)
|
|
336
336
|
})
|
|
337
337
|
|
|
338
338
|
it('accepts a valid group', () => {
|
|
@@ -366,7 +366,7 @@ describe('localizedPaths build-time verification', () => {
|
|
|
366
366
|
expect(names).toEqual(['@astrojs/sitemap', '@easy-web/seo:localized-paths-validation'])
|
|
367
367
|
})
|
|
368
368
|
|
|
369
|
-
it('fails the build when a declared path was never emitted', () => {
|
|
369
|
+
it('fails the build when a declared path was never emitted', async () => {
|
|
370
370
|
const { updateConfig } = run(
|
|
371
371
|
easyWebSeo({
|
|
372
372
|
sitemapLocales: { de: 'de-DE', en: 'en-US' },
|
|
@@ -375,12 +375,12 @@ describe('localizedPaths build-time verification', () => {
|
|
|
375
375
|
)
|
|
376
376
|
|
|
377
377
|
const validator = registeredValidator(updateConfig)[1] as Integration
|
|
378
|
-
const done = validator.hooks['astro:build:done'] as unknown as () => void
|
|
378
|
+
const done = validator.hooks['astro:build:done'] as unknown as (args: { dir: URL }) => Promise<void>
|
|
379
379
|
|
|
380
|
-
expect((
|
|
380
|
+
await expect(done({ dir: new URL('file:///tmp/') })).rejects.toThrow(/no such page was built/)
|
|
381
381
|
})
|
|
382
382
|
|
|
383
|
-
it('passes when every declared path was emitted', () => {
|
|
383
|
+
it('passes when every declared path was emitted', async () => {
|
|
384
384
|
const { updateConfig } = run(
|
|
385
385
|
easyWebSeo({
|
|
386
386
|
sitemapLocales: { de: 'de-DE', en: 'en-US' },
|
|
@@ -393,8 +393,8 @@ describe('localizedPaths build-time verification', () => {
|
|
|
393
393
|
serialize({ url: `${SITE}/en/privacy/` })
|
|
394
394
|
|
|
395
395
|
const validator = registeredValidator(updateConfig)[1] as Integration
|
|
396
|
-
const done = validator.hooks['astro:build:done'] as unknown as () => void
|
|
396
|
+
const done = validator.hooks['astro:build:done'] as unknown as (args: { dir: URL }) => Promise<void>
|
|
397
397
|
|
|
398
|
-
expect((
|
|
398
|
+
await expect(done({ dir: new URL('file:///tmp/') })).resolves.toBeUndefined()
|
|
399
399
|
})
|
|
400
400
|
})
|
package/src/seo/index.ts
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
import { createCrawlPolicy, isDisallowedPath } from './crawl-policy.js'
|
|
12
12
|
import { buildInfoManifest } from './build-info.js'
|
|
13
13
|
import { buildInfoOptionsSchema, serializeBuildInfo, type BuildInfoOptions } from './build-info-manifest.js'
|
|
14
|
+
import { synchronizeRenderedSitemapAlternates } from './rendered-sitemap-alternates.js'
|
|
14
15
|
|
|
15
16
|
export type { BuildInfoOptions, BuildInfoPackageId, BuildInfoManifest } from './build-info-manifest.js'
|
|
16
17
|
|
|
@@ -33,6 +34,11 @@ export type Options = {
|
|
|
33
34
|
* A stale or misspelled entry fails the build rather than degrading quietly.
|
|
34
35
|
*/
|
|
35
36
|
localizedPaths?: readonly LocalizedPathGroup[]
|
|
37
|
+
/**
|
|
38
|
+
* Reconcile sitemap alternates with rendered canonical/hreflang links after
|
|
39
|
+
* build. Intended for generated content whose translated slugs are CMS-owned.
|
|
40
|
+
*/
|
|
41
|
+
synchronizeRenderedAlternates?: boolean
|
|
36
42
|
/** Composed with the built-in crawl policy using AND semantics; cannot re-admit blocked paths. */
|
|
37
43
|
filter?: (page: string) => boolean
|
|
38
44
|
}
|
|
@@ -143,9 +149,9 @@ export default function easyWebSeo(options: Options = {}): AstroIntegration {
|
|
|
143
149
|
|
|
144
150
|
const declaredGroups = options.localizedPaths ?? []
|
|
145
151
|
|
|
146
|
-
if (declaredGroups.length > 0 && !sitemapI18n) {
|
|
152
|
+
if ((declaredGroups.length > 0 || options.synchronizeRenderedAlternates) && !sitemapI18n) {
|
|
147
153
|
throw new Error(
|
|
148
|
-
'@easy-web/seo:
|
|
154
|
+
'@easy-web/seo: localized alternates require `i18n` to be configured in astro.config.mjs.'
|
|
149
155
|
)
|
|
150
156
|
}
|
|
151
157
|
|
|
@@ -228,7 +234,7 @@ export default function easyWebSeo(options: Options = {}): AstroIntegration {
|
|
|
228
234
|
const validatorIntegration: AstroIntegration = {
|
|
229
235
|
name: '@easy-web/seo:localized-paths-validation',
|
|
230
236
|
hooks: {
|
|
231
|
-
'astro:build:done': () => {
|
|
237
|
+
'astro:build:done': async ({ dir }) => {
|
|
232
238
|
const missing = [...declaredUrls].filter((url) => !seenUrls.has(url))
|
|
233
239
|
const failures = [
|
|
234
240
|
...missing.map(
|
|
@@ -243,6 +249,14 @@ export default function easyWebSeo(options: Options = {}): AstroIntegration {
|
|
|
243
249
|
`@easy-web/seo: invalid \`localizedPaths\`:\n- ${failures.join('\n- ')}`
|
|
244
250
|
)
|
|
245
251
|
}
|
|
252
|
+
if (options.synchronizeRenderedAlternates) {
|
|
253
|
+
await synchronizeRenderedSitemapAlternates(
|
|
254
|
+
dir,
|
|
255
|
+
config,
|
|
256
|
+
localeIds,
|
|
257
|
+
config.i18n!.defaultLocale,
|
|
258
|
+
)
|
|
259
|
+
}
|
|
246
260
|
},
|
|
247
261
|
},
|
|
248
262
|
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { readdir, readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { join, relative, sep } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import type { AstroConfig } from 'astro';
|
|
5
|
+
import { normalizeLocalizedPath, toServedPath } from '../i18n/index.js';
|
|
6
|
+
|
|
7
|
+
interface RenderedPage {
|
|
8
|
+
readonly url: string;
|
|
9
|
+
readonly locale: string;
|
|
10
|
+
readonly alternates: ReadonlyMap<string, string>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function decodeHtml(value: string): string {
|
|
14
|
+
return value.replaceAll('&', '&').replaceAll('"', '"').replaceAll(''', "'").replaceAll('<', '<').replaceAll('>', '>');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function decodeXml(value: string): string {
|
|
18
|
+
return decodeHtml(value);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function escapeXml(value: string): string {
|
|
22
|
+
return value.replaceAll('&', '&').replaceAll('"', '"').replaceAll('<', '<').replaceAll('>', '>');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function attributes(tag: string): Map<string, string> {
|
|
26
|
+
const values = new Map<string, string>();
|
|
27
|
+
for (const match of tag.matchAll(/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) {
|
|
28
|
+
values.set(match[1]!.toLowerCase(), decodeHtml(match[2] ?? match[3] ?? ''));
|
|
29
|
+
}
|
|
30
|
+
return values;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function canonicalOf(html: string): string | undefined {
|
|
34
|
+
let canonical: string | undefined;
|
|
35
|
+
for (const tag of html.matchAll(/<link\b[^>]*>/gi)) {
|
|
36
|
+
const attrs = attributes(tag[0]);
|
|
37
|
+
if (attrs.get('rel')?.toLowerCase() !== 'canonical') continue;
|
|
38
|
+
const href = attrs.get('href');
|
|
39
|
+
if (!href) throw new Error('Rendered canonical link is missing href');
|
|
40
|
+
if (canonical) throw new Error('Rendered HTML page has multiple canonical links');
|
|
41
|
+
canonical = href;
|
|
42
|
+
}
|
|
43
|
+
return canonical;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function renderedAlternates(html: string): Map<string, string> {
|
|
47
|
+
const alternates = new Map<string, string>();
|
|
48
|
+
for (const tag of html.matchAll(/<link\b[^>]*>/gi)) {
|
|
49
|
+
const attrs = attributes(tag[0]);
|
|
50
|
+
if (attrs.get('rel')?.toLowerCase() !== 'alternate') continue;
|
|
51
|
+
const language = attrs.get('hreflang');
|
|
52
|
+
const href = attrs.get('href');
|
|
53
|
+
if (!language || !href) continue;
|
|
54
|
+
if (alternates.has(language)) throw new Error(`Duplicate rendered hreflang "${language}"`);
|
|
55
|
+
alternates.set(language, href);
|
|
56
|
+
}
|
|
57
|
+
return alternates;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function htmlFiles(directory: string, parent = ''): Promise<string[]> {
|
|
61
|
+
const files: string[] = [];
|
|
62
|
+
for (const entry of await readdir(join(directory, parent), { withFileTypes: true })) {
|
|
63
|
+
const path = parent ? `${parent}${sep}${entry.name}` : entry.name;
|
|
64
|
+
if (entry.isDirectory()) files.push(...await htmlFiles(directory, path));
|
|
65
|
+
else if (entry.isFile() && entry.name.endsWith('.html')) files.push(path);
|
|
66
|
+
}
|
|
67
|
+
return files;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function absoluteUrl(value: string, config: AstroConfig, label: string): URL {
|
|
71
|
+
const site = new URL(config.site!);
|
|
72
|
+
const url = new URL(value, site);
|
|
73
|
+
if (url.origin !== site.origin) throw new Error(`${label} must use the configured site origin: ${value}`);
|
|
74
|
+
if (url.username || url.password || url.search || url.hash) {
|
|
75
|
+
throw new Error(`${label} must not contain credentials, a query string or a fragment: ${value}`);
|
|
76
|
+
}
|
|
77
|
+
const base = normalizeLocalizedPath(config.base);
|
|
78
|
+
if (base !== '/' && url.pathname !== base && !url.pathname.startsWith(`${base}/`)) {
|
|
79
|
+
throw new Error(`${label} is outside the configured base path "${base}": ${value}`);
|
|
80
|
+
}
|
|
81
|
+
return url;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function servedUrlForHtml(file: string, config: AstroConfig): string {
|
|
85
|
+
const segments = file.split(sep);
|
|
86
|
+
const last = segments.at(-1)!;
|
|
87
|
+
if (last === 'index.html') segments.pop();
|
|
88
|
+
else if (last.endsWith('.html')) segments[segments.length - 1] = last.slice(0, -5);
|
|
89
|
+
const route = normalizeLocalizedPath(segments.join('/'));
|
|
90
|
+
const base = normalizeLocalizedPath(config.base);
|
|
91
|
+
const withoutPhysicalBase = base !== '/' && (route === base || route.startsWith(`${base}/`))
|
|
92
|
+
? route.slice(base.length) || '/'
|
|
93
|
+
: route;
|
|
94
|
+
const pathname = `${base === '/' ? '' : base}${withoutPhysicalBase}`;
|
|
95
|
+
const style = config.trailingSlash === 'never'
|
|
96
|
+
|| (config.trailingSlash === 'ignore' && config.build.format === 'file')
|
|
97
|
+
? 'never'
|
|
98
|
+
: 'always';
|
|
99
|
+
const site = new URL(config.site!);
|
|
100
|
+
return new URL(toServedPath(pathname, style), site).href;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function localeFromHtml(html: string, file: string): string {
|
|
104
|
+
const tag = /<html\b[^>]*>/i.exec(html)?.[0];
|
|
105
|
+
const locale = tag ? attributes(tag).get('lang') : undefined;
|
|
106
|
+
if (!locale) throw new Error(`Rendered HTML page is missing <html lang>: ${file}`);
|
|
107
|
+
return locale;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function sitemapUrlBlocks(xml: string, file: string): Map<string, string> {
|
|
111
|
+
const blocks = new Map<string, string>();
|
|
112
|
+
for (const match of xml.matchAll(/<url\b[^>]*>[\s\S]*?<\/url>/g)) {
|
|
113
|
+
const location = /<loc>([\s\S]*?)<\/loc>/.exec(match[0])?.[1];
|
|
114
|
+
if (!location) throw new Error(`Sitemap entry in ${file} is missing <loc>`);
|
|
115
|
+
const url = decodeXml(location.trim());
|
|
116
|
+
if (blocks.has(url)) throw new Error(`Duplicate sitemap URL: ${url}`);
|
|
117
|
+
blocks.set(url, match[0]);
|
|
118
|
+
}
|
|
119
|
+
return blocks;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Reconciles sitemap alternates with rendered pages only when explicitly enabled.
|
|
124
|
+
* Rendered head links are validated against built canonicals before changing XML.
|
|
125
|
+
*/
|
|
126
|
+
export async function synchronizeRenderedSitemapAlternates(
|
|
127
|
+
outputDirectory: URL,
|
|
128
|
+
config: AstroConfig,
|
|
129
|
+
locales: readonly string[],
|
|
130
|
+
defaultLocale: string,
|
|
131
|
+
): Promise<void> {
|
|
132
|
+
const root = fileURLToPath(outputDirectory);
|
|
133
|
+
const pages = new Map<string, RenderedPage>();
|
|
134
|
+
for (const file of await htmlFiles(root)) {
|
|
135
|
+
const html = await readFile(join(root, file), 'utf8');
|
|
136
|
+
const canonical = canonicalOf(html);
|
|
137
|
+
if (!canonical) continue;
|
|
138
|
+
const url = absoluteUrl(canonical, config, `Canonical in ${file}`).href;
|
|
139
|
+
const expected = servedUrlForHtml(relative(root, join(root, file)), config);
|
|
140
|
+
if (url !== expected) throw new Error(`Rendered canonical does not match built page ${file}: expected ${expected}, got ${url}`);
|
|
141
|
+
const page: RenderedPage = { url, locale: localeFromHtml(html, file), alternates: renderedAlternates(html) };
|
|
142
|
+
if (pages.has(url)) throw new Error(`Multiple built HTML files share the canonical URL: ${url}`);
|
|
143
|
+
pages.set(url, page);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const groups = new Map<string, readonly { readonly lang: string; readonly href: string }[]>();
|
|
147
|
+
for (const page of pages.values()) {
|
|
148
|
+
const declared = [...page.alternates].filter(([lang]) => lang !== 'x-default');
|
|
149
|
+
if (declared.length === 1) {
|
|
150
|
+
throw new Error(`Rendered alternates for ${page.url} must include at least two locales`);
|
|
151
|
+
}
|
|
152
|
+
if (declared.length < 2) continue;
|
|
153
|
+
if (!locales.includes(page.locale)) throw new Error(`Rendered page ${page.url} has unconfigured lang="${page.locale}"`);
|
|
154
|
+
const links = declared.map(([lang, href]) => {
|
|
155
|
+
if (!locales.includes(lang)) throw new Error(`Rendered hreflang "${lang}" on ${page.url} is not a configured locale`);
|
|
156
|
+
const target = absoluteUrl(href, config, `Rendered hreflang "${lang}" on ${page.url}`).href;
|
|
157
|
+
const targetPage = pages.get(target);
|
|
158
|
+
if (!targetPage) throw new Error(`Rendered hreflang "${lang}" points to no built canonical page: ${target}`);
|
|
159
|
+
if (targetPage.locale !== lang) throw new Error(`Rendered hreflang "${lang}" points to a page with lang="${targetPage.locale}": ${target}`);
|
|
160
|
+
return { lang, href: target };
|
|
161
|
+
});
|
|
162
|
+
if (!links.some(({ lang }) => lang === page.locale)) {
|
|
163
|
+
throw new Error(`Rendered alternates for ${page.url} omit its own locale "${page.locale}"`);
|
|
164
|
+
}
|
|
165
|
+
if (links.find(({ lang }) => lang === page.locale)?.href !== page.url) {
|
|
166
|
+
throw new Error(`Rendered hreflang "${page.locale}" must point to its own canonical URL: ${page.url}`);
|
|
167
|
+
}
|
|
168
|
+
for (const link of links) {
|
|
169
|
+
const targetPage = pages.get(link.href)!;
|
|
170
|
+
if (targetPage.alternates.get(page.locale) !== page.url) {
|
|
171
|
+
throw new Error(`Rendered hreflang group is not reciprocal between ${page.url} and ${link.href}`);
|
|
172
|
+
}
|
|
173
|
+
const targetAlternates = [...targetPage.alternates].filter(([lang]) => lang !== 'x-default');
|
|
174
|
+
if (targetAlternates.length !== links.length
|
|
175
|
+
|| links.some(({ lang, href }) => targetPage.alternates.get(lang) !== href)) {
|
|
176
|
+
throw new Error(`Rendered hreflang group is inconsistent between ${page.url} and ${link.href}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const defaultHref = page.alternates.get('x-default');
|
|
180
|
+
if (defaultHref) {
|
|
181
|
+
const target = absoluteUrl(defaultHref, config, 'Rendered x-default alternate').href;
|
|
182
|
+
const targetPage = pages.get(target);
|
|
183
|
+
if (!targetPage || targetPage.locale !== defaultLocale) {
|
|
184
|
+
throw new Error(`Rendered x-default must point to a built ${defaultLocale} page: ${target}`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
groups.set(page.url, links);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const files = (await readdir(root, { withFileTypes: true }))
|
|
191
|
+
.filter((entry) => entry.isFile() && /^sitemap-\d+\.xml$/.test(entry.name))
|
|
192
|
+
.map((entry) => entry.name);
|
|
193
|
+
if (files.length === 0) {
|
|
194
|
+
if (groups.size > 0) throw new Error('Rendered hreflang groups exist but no numbered sitemap was built');
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
const sitemapLocations = new Set<string>();
|
|
198
|
+
const sitemapBlocks = new Map<string, Map<string, string>>();
|
|
199
|
+
for (const file of files) {
|
|
200
|
+
const xml = await readFile(join(root, file), 'utf8');
|
|
201
|
+
const blocks = sitemapUrlBlocks(xml, file);
|
|
202
|
+
for (const url of blocks.keys()) {
|
|
203
|
+
if (sitemapLocations.has(url)) throw new Error(`Sitemap URL appears more than once: ${url}`);
|
|
204
|
+
sitemapLocations.add(url);
|
|
205
|
+
}
|
|
206
|
+
sitemapBlocks.set(file, blocks);
|
|
207
|
+
}
|
|
208
|
+
for (const [url, links] of groups) {
|
|
209
|
+
if (!sitemapLocations.has(url)) throw new Error(`Rendered alternate page is excluded from the sitemap: ${url}`);
|
|
210
|
+
for (const link of links) {
|
|
211
|
+
if (!sitemapLocations.has(link.href)) throw new Error(`Rendered alternate target is excluded from the sitemap: ${link.href}`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
for (const file of files) {
|
|
215
|
+
const path = join(root, file);
|
|
216
|
+
let xml = await readFile(path, 'utf8');
|
|
217
|
+
const blocks = sitemapBlocks.get(file)!;
|
|
218
|
+
for (const [url, existing] of blocks) {
|
|
219
|
+
if (!pages.has(url)) continue;
|
|
220
|
+
const replaced = existing.replace(/<xhtml:link\b[^>]*\/>/g, '');
|
|
221
|
+
const tags = (groups.get(url) ?? []).map(({ lang, href }) =>
|
|
222
|
+
`<xhtml:link rel="alternate" hreflang="${escapeXml(lang)}" href="${escapeXml(href)}"/>`,
|
|
223
|
+
).join('');
|
|
224
|
+
const updated = replaced.replace('</url>', `${tags}</url>`);
|
|
225
|
+
xml = xml.replace(existing, updated);
|
|
226
|
+
blocks.set(url, updated);
|
|
227
|
+
if (!xml.includes(escapeXml(url))) throw new Error(`Updated sitemap no longer contains ${url}`);
|
|
228
|
+
}
|
|
229
|
+
await writeFile(path, xml);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { assertImplements } from '../contracts/implements.js';
|
|
2
|
+
import type { HasOptionalOrder, HasOrder } from '../contracts/capabilities.js';
|
|
2
3
|
import type { DecorativeImage, Event, Product } from '../contracts/types.js';
|
|
3
4
|
|
|
4
5
|
const product: Product = {
|
|
@@ -24,6 +25,11 @@ const _decorativeImage: DecorativeImage = { src: '/divider.svg', decorative: tru
|
|
|
24
25
|
assertImplements<{ title: string }, Event>();
|
|
25
26
|
|
|
26
27
|
assertImplements<{ title: string; startDate: Date }, Event>();
|
|
28
|
+
assertImplements<{ order: number }, HasOrder>();
|
|
29
|
+
assertImplements<{ order?: number }, HasOptionalOrder>();
|
|
30
|
+
|
|
31
|
+
// @ts-expect-error The published HasOrder contract remains required.
|
|
32
|
+
assertImplements<Record<string, never>, HasOrder>();
|
|
27
33
|
|
|
28
34
|
void product;
|
|
29
35
|
void productWithoutImage;
|