From e21c61d82b63a5fbd3f72dc3176a7b419a436120 Mon Sep 17 00:00:00 2001 From: Tim Fabian Date: Sat, 21 Nov 2026 05:36:06 +0100 Subject: [PATCH] improved robots.txt, sitemap and localization for SEO --- cspell.words.txt | 5 +- projects/ngx-auth/package.json | 4 +- projects/ngx-change-sets/package.json | 4 +- projects/ngx-ecommerce/package.json | 4 +- projects/ngx-entity/package.json | 8 +- projects/ngx-error-handling/package.json | 4 +- projects/ngx-navigation/README.md | 69 ++- .../footer/footer.component.spec.ts | 6 +- .../language-switcher-config.provider.ts | 2 +- .../language-switcher-href.type.ts | 9 +- .../language-switcher-language.model.ts | 5 + .../language-switcher.component.spec.ts | 42 +- .../language-switcher.component.ts | 4 +- .../navbar/navbar.component.spec.ts | 6 + .../navigation/nav-route-data.model.ts | 17 +- .../navigation/nav-sitemap-entry.model.ts | 14 + .../ngx-navigation/navigation/public-api.ts | 1 + projects/ngx-navigation/package.json | 10 +- .../ngx-navigation/seo-server/ng-package.json | 5 + .../ngx-navigation/seo-server/public-api.ts | 7 + .../seo-server/seo-app-engine.model.ts | 13 + .../seo-server/seo-localized-page.model.ts | 24 ++ .../seo-server/seo-page.model.ts | 25 ++ .../seo-server/seo-robots-options.model.ts | 17 + .../seo-server/seo-server-config.model.ts | 39 ++ .../seo-server/seo-server.utilities.spec.ts | 376 ++++++++++++++++ .../seo-server/seo-server.utilities.ts | 401 ++++++++++++++++++ .../seo-server/seo-site.model.ts | 16 + projects/ngx-navigation/seo/public-api.ts | 5 + .../seo/seo-config-changes.model.ts | 2 +- .../ngx-navigation/seo/seo-config.model.ts | 10 +- .../ngx-navigation/seo/seo-locale.model.ts | 14 + .../seo/seo-page-route.model.ts | 15 + .../ngx-navigation/seo/seo-route.utilities.ts | 87 ++++ .../seo/seo-sitemap-context.model.ts | 12 + .../ngx-navigation/seo/seo-url.utilities.ts | 35 ++ projects/ngx-navigation/seo/seo.provider.ts | 27 +- .../ngx-navigation/seo/seo.service.spec.ts | 50 ++- projects/ngx-navigation/seo/seo.service.ts | 56 ++- projects/ngx-persistence-logger/package.json | 4 +- projects/ngx-pwa/package.json | 4 +- projects/ngx-tracking/package.json | 4 +- .../error-handler-testing.utilities.ts | 18 + .../testing/error-handler/ng-package.json | 5 + projects/testing/error-handler/public-api.ts | 1 + projects/testing/package.json | 1 + projects/ui/button/button.component.spec.ts | 5 +- projects/ui/gallery/gallery.component.spec.ts | 5 +- projects/ui/iframe/iframe.component.spec.ts | 5 +- projects/ui/package.json | 2 +- 50 files changed, 1450 insertions(+), 54 deletions(-) create mode 100644 projects/ngx-navigation/navigation/nav-sitemap-entry.model.ts create mode 100644 projects/ngx-navigation/seo-server/ng-package.json create mode 100644 projects/ngx-navigation/seo-server/public-api.ts create mode 100644 projects/ngx-navigation/seo-server/seo-app-engine.model.ts create mode 100644 projects/ngx-navigation/seo-server/seo-localized-page.model.ts create mode 100644 projects/ngx-navigation/seo-server/seo-page.model.ts create mode 100644 projects/ngx-navigation/seo-server/seo-robots-options.model.ts create mode 100644 projects/ngx-navigation/seo-server/seo-server-config.model.ts create mode 100644 projects/ngx-navigation/seo-server/seo-server.utilities.spec.ts create mode 100644 projects/ngx-navigation/seo-server/seo-server.utilities.ts create mode 100644 projects/ngx-navigation/seo-server/seo-site.model.ts create mode 100644 projects/ngx-navigation/seo/seo-locale.model.ts create mode 100644 projects/ngx-navigation/seo/seo-page-route.model.ts create mode 100644 projects/ngx-navigation/seo/seo-route.utilities.ts create mode 100644 projects/ngx-navigation/seo/seo-sitemap-context.model.ts create mode 100644 projects/ngx-navigation/seo/seo-url.utilities.ts create mode 100644 projects/testing/error-handler/error-handler-testing.utilities.ts create mode 100644 projects/testing/error-handler/ng-package.json create mode 100644 projects/testing/error-handler/public-api.ts diff --git a/cspell.words.txt b/cspell.words.txt index c7bff97..ce60301 100644 --- a/cspell.words.txt +++ b/cspell.words.txt @@ -44,4 +44,7 @@ prerendered noteref alan aria-valuenow -uppercased \ No newline at end of file +uppercased +llms +sitemapindex +prerenders \ No newline at end of file diff --git a/projects/ngx-auth/package.json b/projects/ngx-auth/package.json index 9d9f832..0c0a3dd 100644 --- a/projects/ngx-auth/package.json +++ b/projects/ngx-auth/package.json @@ -1,6 +1,6 @@ { "name": "@service-soft/ngx-auth", - "version": "22.2.0", + "version": "22.3.0", "license": "MIT", "repository": { "type": "git", @@ -23,7 +23,7 @@ "@angular/core": "^22.2.0", "@angular/router": "^22.2.0", "@fortawesome/free-solid-svg-icons": "^7.3.1", - "@service-soft/ui": "^22.2.0", + "@service-soft/ui": "^22.3.0", "tailwindcss": "^4.3.3", "uqr": "^0.1.3", "zibri-contract": "^3.2.0" diff --git a/projects/ngx-change-sets/package.json b/projects/ngx-change-sets/package.json index 2361b43..1147ca6 100644 --- a/projects/ngx-change-sets/package.json +++ b/projects/ngx-change-sets/package.json @@ -1,6 +1,6 @@ { "name": "@service-soft/ngx-change-sets", - "version": "22.2.0", + "version": "22.3.0", "license": "MIT", "repository": { "type": "git", @@ -22,7 +22,7 @@ "@angular/common": "^22.2.0", "@angular/core": "^22.2.0", "@fortawesome/free-solid-svg-icons": "^7.3.1", - "@service-soft/ui": "^22.2.0", + "@service-soft/ui": "^22.3.0", "tailwindcss": "^4.3.3", "zibri-contract": "^3.1.0" }, diff --git a/projects/ngx-ecommerce/package.json b/projects/ngx-ecommerce/package.json index 133f28f..eddc6e0 100644 --- a/projects/ngx-ecommerce/package.json +++ b/projects/ngx-ecommerce/package.json @@ -1,6 +1,6 @@ { "name": "@service-soft/ngx-ecommerce", - "version": "22.2.0", + "version": "22.3.0", "license": "MIT", "repository": { "type": "git", @@ -22,7 +22,7 @@ "@angular/common": "^22.2.0", "@angular/core": "^22.2.0", "@fortawesome/free-solid-svg-icons": "^7.3.1", - "@service-soft/ui": "^22.2.0", + "@service-soft/ui": "^22.3.0", "tailwindcss": "^4.3.3" }, "sideEffects": false diff --git a/projects/ngx-entity/package.json b/projects/ngx-entity/package.json index 4b46d4b..0d372c1 100644 --- a/projects/ngx-entity/package.json +++ b/projects/ngx-entity/package.json @@ -1,6 +1,6 @@ { "name": "@service-soft/ngx-entity", - "version": "22.2.0", + "version": "22.3.0", "license": "MIT", "repository": { "type": "git", @@ -22,9 +22,9 @@ "@angular/common": "^22.2.0", "@angular/core": "^22.2.0", "@angular/router": "^22.2.0", - "@service-soft/ngx-error-handling": "^22.2.0", - "@service-soft/ngx-pwa": "^22.2.0", - "@service-soft/ui": "^22.2.0", + "@service-soft/ngx-error-handling": "^22.3.0", + "@service-soft/ngx-pwa": "^22.3.0", + "@service-soft/ui": "^22.3.0", "tailwindcss": "^4.3.3", "zibri-contract": "^3.1.0" }, diff --git a/projects/ngx-error-handling/package.json b/projects/ngx-error-handling/package.json index 7c04da3..4fdfd42 100644 --- a/projects/ngx-error-handling/package.json +++ b/projects/ngx-error-handling/package.json @@ -1,6 +1,6 @@ { "name": "@service-soft/ngx-error-handling", - "version": "22.2.0", + "version": "22.3.0", "license": "MIT", "repository": { "type": "git", @@ -21,7 +21,7 @@ "peerDependencies": { "@angular/common": "^22.2.0", "@angular/core": "^22.2.0", - "@service-soft/ui": "^22.2.0", + "@service-soft/ui": "^22.3.0", "tailwindcss": "^4.3.3", "zibri-contract": "^3.1.0" }, diff --git a/projects/ngx-navigation/README.md b/projects/ngx-navigation/README.md index 17fb734..9a28715 100644 --- a/projects/ngx-navigation/README.md +++ b/projects/ngx-navigation/README.md @@ -21,12 +21,14 @@ It is built on [@service-soft/ui](https://www.npmjs.com/package/@service-soft/ui - [Switching the language](#switching-the-language) - [The page for unknown urls](#the-page-for-unknown-urls) - [SEO](#seo) + - [Several languages](#several-languages) + - [The server: sitemap, robots.txt and llms.txt](#the-server-sitemap-robotstxt-and-llmstxt) - [Configuration](#configuration) - [Moving from ngx-material-navigation](#moving-from-ngx-material-navigation) - [License](#license) # Requirements -Angular 22 with its router, and Tailwind CSS 4. +Angular 22 with its router, and Tailwind CSS 4. `@angular/ssr` for the [server part of the SEO](#the-server-sitemap-robotstxt-and-llmstxt). ```sh npm install @service-soft/ngx-navigation @service-soft/ui @@ -248,12 +250,12 @@ protected readonly languages: LanguageSwitcherLanguage[] = [ | Input | Values | Default | |---|---|---| -| `languages` | `LanguageSwitcherLanguage[]` | required — `code`, `label` and `href`, a fixed address or a function of the url of the current page; the `href` of the config when it has none | +| `languages` | `LanguageSwitcherLanguage[]` | required — `code`, `label`, `subPath`, the path its build is served below, its code when it has none, and `href`, a fixed address or a function of the url of the current page; the `href` of the config when it has none | | `current` | `string` | the `LOCALE_ID` of the app — the code of the language of the page; `en` counts for `en-US` when no code is the same | | `appearance` | `'menu'` \| `'list'` | `'menu'` — a button with a globe and the current language that opens a [menu](https://www.npmjs.com/package/@service-soft/ui#menu) of all of them, or a row of links | | `label` | `string` | `'Language'` — what screen readers call it; the button is named "Language: English" | -The link to the current page in a language has its code as `hreflang` and `lang`, so search engines know the page in that language, and screen readers read its name in it. The one of the current language is marked with a check in the menu, underlined in the row, and tells screen readers that it is the current page. The links are plain hrefs, which load the page in the other language. By default they go to `/`, like `/de/orders?page=2`, where Angular's i18n puts the build of every language; change that for all languages with `provideLanguageSwitcherConfig({ href: (url, code) => … })`, and the `label`, the `icon` and the `appearance` there as well. Inside of a `ui-menu`, like a menu of the navbar as a `custom` element, its links are items of that menu. +The link to the current page in a language has its code as `hreflang` and `lang`, so search engines know the page in that language, and screen readers read its name in it. The one of the current language is marked with a check in the menu, underlined in the row, and tells screen readers that it is the current page. The links are plain hrefs, which load the page in the other language. By default they go to `/`, like `/de/orders?page=2`, where Angular's i18n puts the build of every language. Give a language whose path isn't its code its `subPath`, like `{ code: 'de-CH', label: 'Deutsch', subPath: 'de' }`, the same as the `subPath` of its [SEO locale](#several-languages). Change the links for all languages with `provideLanguageSwitcherConfig({ href: (url, code, subPath) => … })`, and the `label`, the `icon` and the `appearance` there as well. Inside of a `ui-menu`, like a menu of the navbar as a `custom` element, its links are items of that menu. # The page for unknown urls `NotFoundComponent` is the page of the route for every other path, a centered [result](https://www.npmjs.com/package/@service-soft/ui#result) of `@service-soft/ui` with an icon, a heading, a text and a link back: @@ -296,6 +298,63 @@ const routes: NavRoute[] = [{ Each value comes from the deepest route that has it, and `NavRouteData` types them. A tag the page has no value for is removed, so none of the page before survives a navigation; leave them out of your `index.html`. The JSON-LD of the site itself, like its `Organization`, can stay there: only the one of the pages is replaced. +## Several languages +For a site that Angular i18n builds in several languages, give `locales` the languages, the source language first, each with its code and the `subPath` its build is served below: + +```ts +provideSeoConfig({ origin: 'https://club.example', locales: [{ code: 'en', subPath: 'en' }, { code: 'de', subPath: 'de' }] }) +``` + +Each build knows its language by its `LOCALE_ID`. Then the canonical url of a page has its language, like `https://club.example/de/teams`. Every page also links to itself in each language with ``, and to its url without a language as `x-default`, which the server redirects by the language of the visitor. `og:locale` is the language, like `de_CH`, and `og:locale:alternate` names the others. With one language, or none given, pages have no alternates and no prefix. + +## The server: sitemap, robots.txt and llms.txt +`SeoServerUtilities` of `@service-soft/ngx-navigation/seo-server` gives the server of the site what it tells about all of its pages. That entry point needs `@angular/ssr`, an optional peer dependency. `resolvePages` finds them in the routes of the app, so the sitemap has every page, however it renders: + +- the routes of the router config, children and lazily loaded children included; +- without redirects, the route of unknown urls, matchers, and routes whose `robots` holds `noindex`; +- the render mode of each page by the first of the server routes that matches it, `RenderMode.Server` when none does; +- for a route with parameters, the pages Angular prerendered for it, and the ones `sitemap` in its data lists, like the articles of a database. A route with parameters that has neither is returned in `unlistedRoutes`, so the server can log it. + + `sitemap` runs in the app, in an injection context of its root, so it reads them like the pages do. For that, `resolvePages` has the app engine render one page on the server, which hands the app a `REQUEST_CONTEXT` that only the server can give. `provideSeoConfig` runs every `sitemap` before that page renders. The page is an unknown url, so it needs the route of unknown urls to render on the server, which a 404 needs anyway: `{ path: '**', renderMode: RenderMode.Server, status: 404 }`. Without it, the first page without parameters that renders on the server is used, and `resolvePages` throws when there is none; +- the title and description of each page in each language, read from its html as the app engine answers it, prerendered or rendered once. A page only a browser renders, `RenderMode.Client`, has neither, as search engines see little more of it. + +```ts +{ path: 'news/:article', title: 'Article', component: ArticlePage, data: { + sitemap: async () => { + // inject before the first await, as in every injection context + const articles: Article[] = await firstValueFrom(inject(ArticleService).findAll()); + return articles.map(article => ({ path: `/news/${article.slug}`, lastModified: new Date(article.updatedAt) })); + } +} } +``` + +`lastModified` of the data, or of an entry of `sitemap`, is a `Date`, which the sitemap writes as the `` of the page in the format search engines read, like `2026-11-01T00:00:00.000Z`. It is left out when it isn't known: search engines ignore one that is always today. An invalid date throws, naming the page. + +```ts +const appEngine: AngularNodeAppEngine = new AngularNodeAppEngine(); +const locales: SeoLocale[] = [{ code: 'en', subPath: 'en' }, { code: 'de', subPath: 'de' }]; +const site: Promise = SeoServerUtilities.resolvePages({ + origin: 'https://club.example', + routes, + serverRoutes, + // written next to the browser and server folders by the build + prerenderedRoutes: Object.keys(JSON.parse(readFileSync(join(import.meta.dirname, '../prerendered-routes.json'), 'utf8')).routes), + appEngine, + locales +}); +``` + +The app engine renders each page of the site once for that, at the url of `origin`, so its host has to be one the app engine accepts. + +| Method | Gives | +|---|---| +| `resolveSitemapFiles(pages, origin)` | the files of the sitemap by their path: every page in every language, with `xhtml:link` alternates and `x-default` when there are several. Over 50,000 urls or 50 MB, `/sitemap.xml` is an index of `/sitemap-1.xml`, `/sitemap-2.xml` and so on | +| `resolveRobotsTxt({ allowed, disallowedCrawlers, sitemapUrl })` | the robots.txt: everything allowed or, like on a stage, disallowed, the crawlers that may not read the site, and the sitemap | +| `resolveLlmsTxt(pages, locale, locales, origin)` | the [llms.txt](https://llmstxt.org) of a language: the name and description of the start page and every page that renders on the server, and where the other languages have theirs. `/llms.txt` is the one of the source language, `//llms.txt` the one of another | +| `findTrailingSlashRedirect(url)` | the url without a slash at the end of its path, for a 301, so each page has one url | +| `findLocaleRedirect(url, acceptLanguage, locales)` | for a url without a language, the same page in the language the visitor prefers, for a 302 with `Vary: Accept-Language`; none for the robots.txt, the llms.txt and the sitemap | +| `resolvePreferredLocale(acceptLanguage, locales)` | the language of the site the visitor prefers, by its code or its primary language, like `de` for `de-AT`, the source language when they accept none | + # Configuration Every part reads its defaults and texts from a config, which `provideXConfig` changes, in the application config for the whole app or in a component or route for only that part of it: @@ -306,9 +365,9 @@ Every part reads its defaults and texts from a config, which `provideXConfig` ch | | `labels` | `navigation: 'Navigation'`, `openNavigation: 'Open the navigation'` | | `provideNavigationConfig` | `labels` | `home: 'Home'` — the first step of the breadcrumbs, `anchors: 'On this page'` — what screen readers call the links to the sections | | | `routeCondition` | every link shows — see [conditions and actions](#conditions-and-actions) | -| `provideSeoConfig` | `origin`, `defaultImage` | required, none — see [SEO](#seo) | +| `provideSeoConfig` | `origin`, `defaultImage`, `locales` | required, none, `[]` — see [SEO](#seo) | | `provideNotFoundConfig` | `title`, `message`, `homeLabel`, `homeRoute`, `icon` | `'Page not found'`, a sentence, `'Back to the start page'`, `'/'`, `faSignsPost` | -| `provideLanguageSwitcherConfig` | `appearance`, `label`, `icon`, `href` | `'menu'`, `'Language'`, `faGlobe`, `(url, code) => '/' + code + url` | +| `provideLanguageSwitcherConfig` | `appearance`, `label`, `icon`, `href` | `'menu'`, `'Language'`, `faGlobe`, `(url, code, subPath) => '/' + subPath + url` | | `provideBreadcrumbsConfig` of `@service-soft/ui/breadcrumbs` | `label` | `'Breadcrumbs'` — what screen readers call the breadcrumbs | | `provideDrawerConfig` of `@service-soft/ui/drawer` | `side` | `'start'` — the edge the drawer slides in from | diff --git a/projects/ngx-navigation/footer/footer.component.spec.ts b/projects/ngx-navigation/footer/footer.component.spec.ts index e898895..45d7aae 100644 --- a/projects/ngx-navigation/footer/footer.component.spec.ts +++ b/projects/ngx-navigation/footer/footer.component.spec.ts @@ -3,6 +3,7 @@ import { provideRouter } from '@angular/router'; import { NavLinkComponent } from '@service-soft/ngx-navigation/nav-link'; import { NavTextComponent } from '@service-soft/ngx-navigation/nav-text'; import { FooterRow } from '@service-soft/ngx-navigation/navigation'; +import { ErrorHandlerTestingUtilities } from 'testing/error-handler'; import { describe, expect, test } from 'vitest'; import { FooterComponent } from './footer.component'; @@ -35,11 +36,14 @@ describe('FooterComponent', () => { }); test('throws in development builds for a type without a component', async () => { - TestBed.configureTestingModule({ providers: [provideRouter([])] }); + // the error handler of the app gets it first, whose default would log it + const errors: unknown[] = []; + TestBed.configureTestingModule({ providers: [provideRouter([]), ErrorHandlerTestingUtilities.provideErrorList(errors)] }); const fixture: ComponentFixture = TestBed.createComponent(FooterComponent); fixture.componentRef.setInput('rows', ROWS); fixture.componentRef.setInput('components', { link: NavLinkComponent }); await expect(fixture.whenStable()).rejects.toThrow('The footer needs a component for "text"'); + expect(errors).toHaveLength(1); }); }); \ No newline at end of file diff --git a/projects/ngx-navigation/language-switcher/language-switcher-config.provider.ts b/projects/ngx-navigation/language-switcher/language-switcher-config.provider.ts index 22ce97f..8ef9bd1 100644 --- a/projects/ngx-navigation/language-switcher/language-switcher-config.provider.ts +++ b/projects/ngx-navigation/language-switcher/language-switcher-config.provider.ts @@ -8,7 +8,7 @@ const DEFAULT_LANGUAGE_SWITCHER_CONFIG: LanguageSwitcherConfig = { label: 'Language', icon: faGlobe, // a build for every language under its own path, like Angular's i18n makes them: /de/orders and /en/orders. - href: (url, code) => `/${code}${url}` + href: (url, code, subPath) => `/${subPath}${url}` }; /** diff --git a/projects/ngx-navigation/language-switcher/language-switcher-href.type.ts b/projects/ngx-navigation/language-switcher/language-switcher-href.type.ts index 9a1d137..ad41de7 100644 --- a/projects/ngx-navigation/language-switcher/language-switcher-href.type.ts +++ b/projects/ngx-navigation/language-switcher/language-switcher-href.type.ts @@ -1,8 +1,9 @@ /** - * Builds the address of the current page in a language, like `(url, code) => '/' + code + url` for an app that has a - * build for every language under its own path, as Angular's i18n makes them. + * Builds the address of the current page in a language, like `(url, code, subPath) => '/' + subPath + url` for an app + * that has a build for every language under its own path, as Angular's i18n makes them. * @param url - The url of the current page inside the app, with its query and fragment, like '/orders?page=2'. - * @param code - The code of the language, like 'de'. + * @param code - The code of the language, like 'de-CH'. + * @param subPath - The path the build of the language is served below, like 'de', its code when it has none. * @returns The href of the link to the page in that language. */ -export type LanguageSwitcherHref = (url: string, code: string) => string; \ No newline at end of file +export type LanguageSwitcherHref = (url: string, code: string, subPath: string) => string; \ No newline at end of file diff --git a/projects/ngx-navigation/language-switcher/language-switcher-language.model.ts b/projects/ngx-navigation/language-switcher/language-switcher-language.model.ts index 9e3102b..7b646d6 100644 --- a/projects/ngx-navigation/language-switcher/language-switcher-language.model.ts +++ b/projects/ngx-navigation/language-switcher/language-switcher-language.model.ts @@ -12,6 +12,11 @@ export type LanguageSwitcherLanguage = { * The name of the language in the language itself, like 'Deutsch', which is how its speakers find it. */ label: string, + /** + * The path the build of the language is served below, like 'de' for /de/orders of a language with the code 'de-CH', + * as the i18n.locales of angular.json name it, and the subPath of its SeoLocale. Its code when it has none. + */ + subPath?: string, /** * Where its link goes: a fixed address, or one built from the url of the current page. The href of * provideLanguageSwitcherConfig when it has none. diff --git a/projects/ngx-navigation/language-switcher/language-switcher.component.spec.ts b/projects/ngx-navigation/language-switcher/language-switcher.component.spec.ts index 827cc6b..b1635c2 100644 --- a/projects/ngx-navigation/language-switcher/language-switcher.component.spec.ts +++ b/projects/ngx-navigation/language-switcher/language-switcher.component.spec.ts @@ -1,4 +1,4 @@ -import { Component } from '@angular/core'; +import { Component, LOCALE_ID } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideRouter } from '@angular/router'; import { RouterTestingHarness } from '@angular/router/testing'; @@ -26,6 +26,19 @@ class PageComponent { readonly languages: LanguageSwitcherLanguage[] = LANGUAGES; } +@Component({ + selector: 'ngx-regional-page', + template: '', + imports: [LanguageSwitcherComponent] +}) +class RegionalPageComponent { + // languages of a region, whose builds Angular i18n serves below a shorter path + readonly languages: LanguageSwitcherLanguage[] = [ + { code: 'de-CH', label: 'Deutsch', subPath: 'de' }, + { code: 'fr-CH', label: 'Français', subPath: 'fr' } + ]; +} + // the text, the href, the hreflang, the lang and the aria-current of a link. type LinkAttributes = [string, ...(string | undefined)[]]; @@ -76,4 +89,31 @@ describe('LanguageSwitcherComponent', () => { expect(menu?.querySelector('button')).toBeNull(); expect(menu?.querySelectorAll('a[ui-menu-link]').length).toBe(4); }); + + test('links to the path a language is served below, and names it by its code', async () => { + TestBed.configureTestingModule({ + providers: [provideRouter([{ path: '**', component: RegionalPageComponent }]), { provide: LOCALE_ID, useValue: 'fr-CH' }] + }); + const [list] = await render(); + + expect(findLinks(list)).toEqual([ + ['Deutsch', '/de/orders?page=2', 'de-CH', 'de-CH', undefined], + ['Français', '/fr/orders?page=2', 'fr-CH', 'fr-CH', 'page'] + ]); + }); + + test('gives the href of the config the code and the path of a language', async () => { + TestBed.configureTestingModule({ + providers: [ + provideRouter([{ path: '**', component: RegionalPageComponent }]), + provideLanguageSwitcherConfig({ href: (url, code, subPath) => `https://${subPath}.example.ch${url}#${code}` }) + ] + }); + const [list] = await render(); + + expect(findLinks(list).map(([, href]) => href)).toEqual([ + 'https://de.example.ch/orders?page=2#de-CH', + 'https://fr.example.ch/orders?page=2#fr-CH' + ]); + }); }); \ No newline at end of file diff --git a/projects/ngx-navigation/language-switcher/language-switcher.component.ts b/projects/ngx-navigation/language-switcher/language-switcher.component.ts index 8add48b..e086360 100644 --- a/projects/ngx-navigation/language-switcher/language-switcher.component.ts +++ b/projects/ngx-navigation/language-switcher/language-switcher.component.ts @@ -83,7 +83,9 @@ export class LanguageSwitcherComponent { protected readonly currentItem: Signal = computed(() => this.items().find(item => item.isCurrent)); private resolveHref(language: LanguageSwitcherLanguage, url: string): string { - return typeof language.href === 'string' ? language.href : (language.href ?? this.config.href)(url, language.code); + return typeof language.href === 'string' + ? language.href + : (language.href ?? this.config.href)(url, language.code, language.subPath ?? language.code); } // codes are compared without case, as 'en-gb' and 'en-GB' are the same language. diff --git a/projects/ngx-navigation/navbar/navbar.component.spec.ts b/projects/ngx-navigation/navbar/navbar.component.spec.ts index 14a7d2e..1bf780b 100644 --- a/projects/ngx-navigation/navbar/navbar.component.spec.ts +++ b/projects/ngx-navigation/navbar/navbar.component.spec.ts @@ -9,6 +9,7 @@ import { NavTitleComponent } from '@service-soft/ngx-navigation/nav-title'; import { NavbarRow, NavLink, NavRouteCondition, provideNavigationConfig } from '@service-soft/ngx-navigation/navigation'; import { MenuComponent, MenuItemComponent } from '@service-soft/ui/menu'; import { DialogTestingUtilities } from 'testing/dialog'; +import { ErrorHandlerTestingUtilities } from 'testing/error-handler'; import { afterEach, beforeEach, describe, expect, test } from 'vitest'; import { provideNavbarConfig } from './navbar-config.provider'; @@ -216,13 +217,18 @@ describe('NavbarComponent', () => { test('throws in development builds for a type without a component, and for a component nothing uses', async () => { const { button, ...withoutButton } = COMPONENTS; expect(button).toBe(NavButtonComponent); + // the error handler of the app gets them first, whose default would log them + const errors: unknown[] = []; + TestBed.configureTestingModule({ providers: [ErrorHandlerTestingUtilities.provideErrorList(errors)] }); // the button is hidden by its condition, but it may show later, so it needs its component anyway await expect(render(ROWS, withoutButton)) .rejects.toThrow('The navbar needs a component for "button", which are used but missing in its components.'); TestBed.resetTestingModule(); + TestBed.configureTestingModule({ providers: [ErrorHandlerTestingUtilities.provideErrorList(errors)] }); await expect(render([{ elements: [{ type: 'link', name: 'Orders', route: 'orders' }] }], { link: NavLinkComponent, menu: NavMenuComponent })) .rejects.toThrow('The navbar has a component for "menu", which nothing uses.'); + expect(errors).toHaveLength(2); }); test('shows a custom component inside a menu, as menu items there and as itself in the drawer', async () => { diff --git a/projects/ngx-navigation/navigation/nav-route-data.model.ts b/projects/ngx-navigation/navigation/nav-route-data.model.ts index 204aec1..e6a4b42 100644 --- a/projects/ngx-navigation/navigation/nav-route-data.model.ts +++ b/projects/ngx-navigation/navigation/nav-route-data.model.ts @@ -2,6 +2,7 @@ import { Data } from '@angular/router'; import { NavAnchor } from './nav-anchor.model'; import { NavBreadcrumbConfig } from './nav-breadcrumb-config.model'; +import { NavSitemapEntry } from './nav-sitemap-entry.model'; import { NavStructuredData } from './nav-structured-data.type'; /** @@ -27,12 +28,24 @@ export type NavRouteData = Data & { structuredData?: NavStructuredData, /** * What search engines may do with the page, like 'noindex' for a thank-you page, written as its meta robots by - * provideSeoConfig. + * provideSeoConfig. A page with noindex is left out of the sitemap of `@service-soft/ngx-navigation/seo-server`. */ robots?: string, /** * The image a shared link of the page shows, absolute or relative to the origin of provideSeoConfig, written as its * og:image. */ - image?: string + image?: string, + /** + * When the content of the page last changed, which the sitemap of `@service-soft/ngx-navigation/seo-server` lists + * in the format search engines read. A page without one has no date there. + */ + lastModified?: Date, + /** + * The pages of a route with parameters, for the sitemap, like the products of an api. Runs in an injection context + * of the app, as the server renders a page for the sitemap, so it can inject what it reads them with, like the + * HttpClient; the providers of the root, not the ones of a route. Without it, only the pages Angular prerendered + * for the route are listed. + */ + sitemap?: () => Promise }; \ No newline at end of file diff --git a/projects/ngx-navigation/navigation/nav-sitemap-entry.model.ts b/projects/ngx-navigation/navigation/nav-sitemap-entry.model.ts new file mode 100644 index 0000000..d0731fe --- /dev/null +++ b/projects/ngx-navigation/navigation/nav-sitemap-entry.model.ts @@ -0,0 +1,14 @@ +/** + * A page of a route with parameters, as the sitemap lists it, like the page of one product of an api. + */ +export type NavSitemapEntry = { + /** + * The path of the page without its language, like '/products/42'. + */ + path: string, + /** + * When the content of the page last changed, which the sitemap lists in the format search engines read. Search + * engines only trust a date that is always right, so a page without a known date has none. + */ + lastModified?: Date +}; \ No newline at end of file diff --git a/projects/ngx-navigation/navigation/public-api.ts b/projects/ngx-navigation/navigation/public-api.ts index 5df2e4a..28a9a0c 100644 --- a/projects/ngx-navigation/navigation/public-api.ts +++ b/projects/ngx-navigation/navigation/public-api.ts @@ -19,6 +19,7 @@ export * from './nav-route-data.model'; export * from './nav-route-target.model'; export * from './nav-route.model'; export * from './nav-routes-source.model'; +export * from './nav-sitemap-entry.model'; export * from './nav-structured-data.type'; export * from './nav-target.type'; export * from './nav-text.model'; diff --git a/projects/ngx-navigation/package.json b/projects/ngx-navigation/package.json index 3ca244a..01b1307 100644 --- a/projects/ngx-navigation/package.json +++ b/projects/ngx-navigation/package.json @@ -1,6 +1,6 @@ { "name": "@service-soft/ngx-navigation", - "version": "22.2.0", + "version": "22.3.0", "license": "MIT", "repository": { "type": "git", @@ -23,9 +23,15 @@ "@angular/core": "^22.2.0", "@angular/platform-browser": "^22.2.0", "@angular/router": "^22.2.0", + "@angular/ssr": "^22.2.0", "@fortawesome/free-solid-svg-icons": "^7.3.1", - "@service-soft/ui": "^22.2.0", + "@service-soft/ui": "^22.3.0", "tailwindcss": "^4.3.3" }, + "peerDependenciesMeta": { + "@angular/ssr": { + "optional": true + } + }, "sideEffects": false } \ No newline at end of file diff --git a/projects/ngx-navigation/seo-server/ng-package.json b/projects/ngx-navigation/seo-server/ng-package.json new file mode 100644 index 0000000..70e0a80 --- /dev/null +++ b/projects/ngx-navigation/seo-server/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} \ No newline at end of file diff --git a/projects/ngx-navigation/seo-server/public-api.ts b/projects/ngx-navigation/seo-server/public-api.ts new file mode 100644 index 0000000..e7bdefe --- /dev/null +++ b/projects/ngx-navigation/seo-server/public-api.ts @@ -0,0 +1,7 @@ +export * from './seo-app-engine.model'; +export * from './seo-localized-page.model'; +export * from './seo-page.model'; +export * from './seo-robots-options.model'; +export * from './seo-server-config.model'; +export * from './seo-server.utilities'; +export * from './seo-site.model'; \ No newline at end of file diff --git a/projects/ngx-navigation/seo-server/seo-app-engine.model.ts b/projects/ngx-navigation/seo-server/seo-app-engine.model.ts new file mode 100644 index 0000000..436dd0b --- /dev/null +++ b/projects/ngx-navigation/seo-server/seo-app-engine.model.ts @@ -0,0 +1,13 @@ +/** + * What renders a page on the server, like the AngularNodeAppEngine of @angular/ssr/node, which reads the title and the + * description of a page rendered for each request, and has the app run the data.sitemap of its routes. + */ +export type SeoAppEngine = { + /** + * Renders the page of a request. + * @param request - The request of the page. + * @param requestContext - What the app gets as its REQUEST_CONTEXT, when it renders the page for the request. + * @returns The page, or null for a request that is no page of the app. + */ + handle: (request: Request, requestContext?: unknown) => Promise +}; \ No newline at end of file diff --git a/projects/ngx-navigation/seo-server/seo-localized-page.model.ts b/projects/ngx-navigation/seo-server/seo-localized-page.model.ts new file mode 100644 index 0000000..bc15cbd --- /dev/null +++ b/projects/ngx-navigation/seo-server/seo-localized-page.model.ts @@ -0,0 +1,24 @@ +import { SeoLocale } from '@service-soft/ngx-navigation/seo'; + +/** + * A page of a site in one of its languages. + */ +export type SeoLocalizedPage = { + /** + * The language. + */ + locale: SeoLocale, + /** + * The absolute url of the page in the language. + */ + url: string, + /** + * The title of the page in the language, as it renders it. Undefined for a page only a browser renders. + */ + title: string | undefined, + /** + * The description of the page in the language, as it renders it. Undefined for a page without one, or only a + * browser renders. + */ + description: string | undefined +}; \ No newline at end of file diff --git a/projects/ngx-navigation/seo-server/seo-page.model.ts b/projects/ngx-navigation/seo-server/seo-page.model.ts new file mode 100644 index 0000000..185e46b --- /dev/null +++ b/projects/ngx-navigation/seo-server/seo-page.model.ts @@ -0,0 +1,25 @@ +import { RenderMode } from '@angular/ssr'; + +import { SeoLocalizedPage } from './seo-localized-page.model'; + +/** + * A page of a site that search engines may index, in every language of the site. + */ +export type SeoPage = { + /** + * The path of the page without its language, like '/imprint', or '/' for the start page. + */ + path: string, + /** + * How Angular renders the page: when the site is built, for each request, or only in the browser. + */ + renderMode: RenderMode, + /** + * When the content of the page last changed, from the data of its route. Undefined when not known. + */ + lastModified: Date | undefined, + /** + * The page in each language of the site, in the order of the languages. + */ + localized: SeoLocalizedPage[] +}; \ No newline at end of file diff --git a/projects/ngx-navigation/seo-server/seo-robots-options.model.ts b/projects/ngx-navigation/seo-server/seo-robots-options.model.ts new file mode 100644 index 0000000..7deae67 --- /dev/null +++ b/projects/ngx-navigation/seo-server/seo-robots-options.model.ts @@ -0,0 +1,17 @@ +/** + * What the robots.txt of resolveRobotsTxt says. + */ +export type SeoRobotsOptions = { + /** + * Whether search engines may read the site, false for one like stage that is no site of its own. + */ + allowed: boolean, + /** + * The crawlers that may read nothing even so, like the ones that collect content to train AI models. + */ + disallowedCrawlers: string[], + /** + * The absolute url of the sitemap. + */ + sitemapUrl: string +}; \ No newline at end of file diff --git a/projects/ngx-navigation/seo-server/seo-server-config.model.ts b/projects/ngx-navigation/seo-server/seo-server-config.model.ts new file mode 100644 index 0000000..ee01114 --- /dev/null +++ b/projects/ngx-navigation/seo-server/seo-server-config.model.ts @@ -0,0 +1,39 @@ +import { Routes } from '@angular/router'; +import { ServerRoute } from '@angular/ssr'; +import { SeoLocale } from '@service-soft/ngx-navigation/seo'; + +import { SeoAppEngine } from './seo-app-engine.model'; + +/** + * Where resolvePages finds the pages of a site: its routes, how Angular renders them, and what its build wrote. + */ +export type SeoServerConfig = { + /** + * The origin of the site, like 'https://example.com', without a slash at its end. + */ + origin: string, + /** + * The routes of the app, the same that provideRouter gets. + */ + routes: Routes, + /** + * The server routes of the app, the same that withRoutes of provideServerRendering gets, which say how each page + * renders. + */ + serverRoutes: ServerRoute[], + /** + * The urls Angular prerendered, with their language, as the keys of the routes of the prerendered-routes.json its + * build writes, like '/en/teams/u12'. They list the pages of a route with parameters that prerenders. + */ + prerenderedRoutes: string[], + /** + * What answers each page, prerendered or rendered for the request, to read its title and its description in each + * language: the AngularNodeAppEngine, which serves the prerendered pages of its build as well. + */ + appEngine: SeoAppEngine, + /** + * The languages of the site, as Angular i18n builds them, the source language first. For a site with one language, + * one with an empty subPath. + */ + locales: SeoLocale[] +}; \ No newline at end of file diff --git a/projects/ngx-navigation/seo-server/seo-server.utilities.spec.ts b/projects/ngx-navigation/seo-server/seo-server.utilities.spec.ts new file mode 100644 index 0000000..5e881d2 --- /dev/null +++ b/projects/ngx-navigation/seo-server/seo-server.utilities.spec.ts @@ -0,0 +1,376 @@ +import { ApplicationInitStatus, Component, inject, InjectionToken, REQUEST_CONTEXT } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideRouter, Routes } from '@angular/router'; +import { RenderMode, ServerRoute } from '@angular/ssr'; +import { NavSitemapEntry } from '@service-soft/ngx-navigation/navigation'; +import { provideSeoConfig, SeoLocale, SeoUrlUtilities } from '@service-soft/ngx-navigation/seo'; +import { describe, expect, test } from 'vitest'; + +import { SeoAppEngine } from './seo-app-engine.model'; +import { SeoPage } from './seo-page.model'; +import { SeoServerUtilities } from './seo-server.utilities'; +import { SeoSite } from './seo-site.model'; + +@Component({ selector: 'ngx-page', template: '' }) +class PageComponent {} + +const ORIGIN: string = 'https://club.example'; + +const EN: SeoLocale = { code: 'en', subPath: 'en' }; +const DE: SeoLocale = { code: 'de', subPath: 'de' }; +const LOCALES: SeoLocale[] = [EN, DE]; + +// what the app reads its articles with, like a service of the api +const ARTICLES: InjectionToken = new InjectionToken('ARTICLES'); + +const ARTICLE_ENTRIES: NavSitemapEntry[] = [{ path: '/news/opening/', lastModified: new Date('2026-10-01') }, { path: '/news/season' }]; + +// loaded lazily, as the module of a feature exports them +const TEAM_ROUTES: Routes = [ + { path: '', component: PageComponent }, + { path: ':team', component: PageComponent } +]; + +const ROUTES: Routes = [ + { path: '', component: PageComponent, data: { lastModified: new Date('2026-11-01') } }, + { path: 'home', redirectTo: '' }, + { path: 'imprint', component: PageComponent, data: { robots: 'NOINDEX, follow' } }, + { path: 'news', component: PageComponent }, + { path: 'shop', component: PageComponent }, + { path: 'teams', loadChildren: () => Promise.resolve({ default: TEAM_ROUTES }) }, + { + path: 'news/:article', + loadComponent: () => Promise.resolve(PageComponent), + // listed by the route in the app, as the articles are in a database; its prerendered page too, once + data: { sitemap: () => Promise.resolve(inject(ARTICLES)) } + }, + // neither prerendered nor listed + { path: 'members/:member', component: PageComponent }, + { path: '**', component: PageComponent } +]; + +// the first that matches decides, as with @angular/ssr +const SERVER_ROUTES: ServerRoute[] = [ + { path: 'shop', renderMode: RenderMode.Client }, + { path: 'news', renderMode: RenderMode.Server }, + { path: 'news/:article', renderMode: RenderMode.Server }, + { path: '**', renderMode: RenderMode.Prerender } +]; + +// the keys of the routes of the prerendered-routes.json of a build of both languages +const PRERENDERED_ROUTES: string[] = ['/en', '/de', '/en/teams', '/de/teams', '/en/teams/juniors', '/de/teams/juniors', '/de/news/season']; + +// the html of each page as the app engine answers it, by its url +const PAGES: Record = { + 'https://club.example/en': page('Sports club', 'The sports club of the town.'), + 'https://club.example/de': page('Sportverein', 'Der Sportverein der Stadt.'), + 'https://club.example/en/news': page('News & dates', 'What's new: "everything" <here>'), + 'https://club.example/de/news': page('Neuigkeiten', undefined), + 'https://club.example/en/teams': page('Teams', 'Every team.'), + 'https://club.example/de/teams': page('Mannschaften', 'Jede Mannschaft.'), + 'https://club.example/en/teams/juniors': page('Juniors', undefined), + 'https://club.example/de/teams/juniors': page('Junioren', undefined), + 'https://club.example/en/news/opening': page('Opening', undefined), + 'https://club.example/de/news/opening': page('Eröffnung', undefined), + 'https://club.example/en/news/season': page('Season', undefined) +}; + +function page(title: string, description: string | undefined): string { + const meta: string = description == undefined ? '' : ``; + return `${title}${meta}`; +} + +// answers the html of PAGES and, like the AngularNodeAppEngine for a page it renders on the server, starts the app +// with the context of a request as its REQUEST_CONTEXT +function createAppEngine(requests: string[], routes: Routes = ROUTES): SeoAppEngine { + return { + handle: async (request, requestContext) => { + requests.push(request.url); + if (requestContext != undefined) { + TestBed.configureTestingModule({ + providers: [ + provideRouter(routes), + provideSeoConfig({ origin: ORIGIN, locales: LOCALES }), + { provide: REQUEST_CONTEXT, useValue: requestContext }, + { provide: ARTICLES, useValue: ARTICLE_ENTRIES } + ] + }); + // the page renders once the app is initialized + await TestBed.inject(ApplicationInitStatus).donePromise; + } + const html: string | undefined = PAGES[request.url]; + return html == undefined ? new Response('Not found', { status: 404 }) : new Response(html); + } + }; +} + +function createPage(path: string, locales: SeoLocale[], lastModified?: Date): SeoPage { + return { + path, + renderMode: RenderMode.Prerender, + lastModified, + localized: locales.map(locale => ({ + locale, + url: SeoUrlUtilities.resolveUrl(ORIGIN, path, locale), + title: `${path} in ${locale.code}`, + description: undefined + })) + }; +} + +describe('SeoServerUtilities', () => { + test('finds every page of the routes however it renders, in every language, without the ones not to index', async () => { + const requests: string[] = []; + const site: SeoSite = await SeoServerUtilities.resolvePages({ + origin: ORIGIN, + routes: ROUTES, + serverRoutes: SERVER_ROUTES, + prerenderedRoutes: PRERENDERED_ROUTES, + appEngine: createAppEngine(requests), + locales: LOCALES + }); + + expect(site.pages.map(p => [p.path, p.renderMode, p.lastModified])).toEqual([ + ['/', RenderMode.Prerender, new Date('2026-11-01')], + ['/news', RenderMode.Server, undefined], + ['/shop', RenderMode.Client, undefined], + ['/teams', RenderMode.Prerender, undefined], + ['/teams/juniors', RenderMode.Prerender, undefined], + ['/news/opening', RenderMode.Server, new Date('2026-10-01')], + ['/news/season', RenderMode.Server, undefined] + ]); + expect(site.unlistedRoutes).toEqual(['/members/:member']); + // data.sitemap ran in the app, rendered for the first page without parameters that renders on the server, as + // the route of unknown urls is prerendered here + expect(requests[0]).toBe('https://club.example/en/news'); + + expect(site.pages[0]?.localized).toEqual([ + { locale: EN, url: 'https://club.example/en', title: 'Sports club', description: 'The sports club of the town.' }, + { locale: DE, url: 'https://club.example/de', title: 'Sportverein', description: 'Der Sportverein der Stadt.' } + ]); + // the texts as the html holds them, decoded + expect(site.pages[1]?.localized).toEqual([ + { locale: EN, url: 'https://club.example/en/news', title: 'News & dates', description: 'What\'s new: "everything" ' }, + { locale: DE, url: 'https://club.example/de/news', title: 'Neuigkeiten', description: undefined } + ]); + // a page only a browser renders has no texts, and is not rendered for them + expect(site.pages[2]?.localized).toEqual([ + { locale: EN, url: 'https://club.example/en/shop', title: undefined, description: undefined }, + { locale: DE, url: 'https://club.example/de/shop', title: undefined, description: undefined } + ]); + expect(requests.filter(url => url.includes('/shop'))).toEqual([]); + // a page the app engine doesn't answer has no texts either + expect(site.pages[6]?.localized[1]).toEqual({ locale: DE, url: 'https://club.example/de/news/season', title: undefined, description: undefined }); + }); + + test('finds the pages of a site of one language at the urls without a prefix', async () => { + const site: SeoSite = await SeoServerUtilities.resolvePages({ + origin: ORIGIN, + routes: [{ path: '', component: PageComponent }, { path: 'teams/:team', component: PageComponent }], + serverRoutes: [{ path: '**', renderMode: RenderMode.Prerender }], + prerenderedRoutes: ['/', '/teams/juniors'], + appEngine: createAppEngine([]), + locales: [{ code: 'en-US', subPath: '' }] + }); + + expect(site.pages.map(p => p.localized.map(l => l.url))).toEqual([['https://club.example/'], ['https://club.example/teams/juniors']]); + expect(site.unlistedRoutes).toEqual([]); + }); + + test('runs data.sitemap in the app as the route of unknown urls renders on the server', async () => { + const requests: string[] = []; + const routes: Routes = [ + { path: 'news/:article', component: PageComponent, data: { sitemap: () => Promise.resolve(inject(ARTICLES)) } }, + { path: '**', component: PageComponent } + ]; + const site: SeoSite = await SeoServerUtilities.resolvePages({ + origin: ORIGIN, + routes, + serverRoutes: [{ path: '**', renderMode: RenderMode.Server, status: 404 }], + prerenderedRoutes: [], + appEngine: createAppEngine(requests, routes), + locales: LOCALES + }); + + expect(requests[0]).toBe('https://club.example/en/__ngx-seo-sitemap'); + expect(site.pages.map(p => [p.path, p.lastModified])).toEqual([['/news/opening', new Date('2026-10-01')], ['/news/season', undefined]]); + }); + + test('tells why data.sitemap cannot run when no page renders on the server', async () => { + const routes: Routes = [ + { path: '', component: PageComponent }, + { path: 'news/:article', component: PageComponent, data: { sitemap: () => Promise.resolve(inject(ARTICLES)) } } + ]; + const pages: Promise = SeoServerUtilities.resolvePages({ + origin: ORIGIN, + routes, + serverRoutes: [{ path: '**', renderMode: RenderMode.Prerender }], + prerenderedRoutes: [], + appEngine: createAppEngine([], routes), + locales: LOCALES + }); + + await expect(pages).rejects.toThrow('which needs one with RenderMode.Server'); + }); + + test('resolves a sitemap with each page in every language, linked to the others and to its url without a language', () => { + const files: Record = SeoServerUtilities.resolveSitemapFiles( + [createPage('/', LOCALES, new Date('2026-11-01')), createPage('/q&a', LOCALES)], + ORIGIN + ); + + expect(Object.keys(files)).toEqual(['/sitemap.xml']); + expect(files['/sitemap.xml']).toBe([ + '', + '', + ' ', + ' https://club.example/en', + ' ', + ' ', + ' ', + ' 2026-11-01T00:00:00.000Z', + ' ', + ' ', + ' https://club.example/de', + ' ', + ' ', + ' ', + ' 2026-11-01T00:00:00.000Z', + ' ', + ' ', + ' https://club.example/en/q&a', + ' ', + ' ', + ' ', + ' ', + ' ', + ' https://club.example/de/q&a', + ' ', + ' ', + ' ', + ' ', + '' + ].join('\n')); + }); + + test('resolves a sitemap without alternates for a site of one language', () => { + const files: Record = SeoServerUtilities.resolveSitemapFiles([createPage('/', [{ code: 'en', subPath: '' }])], ORIGIN); + + expect(files['/sitemap.xml']).toContain('https://club.example/'); + expect(files['/sitemap.xml']).not.toContain('xhtml:link'); + expect(files['/sitemap.xml']).not.toContain('lastmod'); + }); + + test('tells which page has a lastModified that is no valid date', () => { + // like the date of an api that new Date could not read + const pages: SeoPage[] = [createPage('/news', LOCALES, new Date('yesterday'))]; + + expect(() => SeoServerUtilities.resolveSitemapFiles(pages, ORIGIN)).toThrow('The lastModified of /news is no valid date.'); + }); + + test('splits a sitemap of more than 50,000 urls into parts below an index', () => { + const pages: SeoPage[] = Array.from({ length: 50_001 }, (_, index) => createPage(`/page-${index}`, [{ code: 'en', subPath: '' }])); + const files: Record = SeoServerUtilities.resolveSitemapFiles(pages, ORIGIN); + + expect(Object.keys(files).sort()).toEqual(['/sitemap-1.xml', '/sitemap-2.xml', '/sitemap.xml']); + expect(files['/sitemap.xml']).toBe([ + '', + '', + ' https://club.example/sitemap-1.xml', + ' https://club.example/sitemap-2.xml', + '' + ].join('\n')); + expect(files['/sitemap-1.xml']?.match(//g)).toHaveLength(50_000); + expect(files['/sitemap-2.xml']?.match(//g)).toHaveLength(1); + expect(files['/sitemap-2.xml']).toContain('https://club.example/page-50000'); + }); + + test('resolves a robots.txt that allows or disallows everything, blocks the crawlers given and links the sitemap', () => { + expect(SeoServerUtilities.resolveRobotsTxt({ + allowed: true, + disallowedCrawlers: ['GPTBot', 'CCBot'], + sitemapUrl: 'https://club.example/sitemap.xml' + })).toBe([ + 'User-agent: *', + 'Allow: /', + '', + 'User-agent: GPTBot', + 'Disallow: /', + '', + 'User-agent: CCBot', + 'Disallow: /', + '', + 'Sitemap: https://club.example/sitemap.xml' + ].join('\n')); + expect(SeoServerUtilities.resolveRobotsTxt({ allowed: false, disallowedCrawlers: [], sitemapUrl: 'https://stage.club.example/sitemap.xml' })) + .toBe('User-agent: *\nDisallow: /\n\nSitemap: https://stage.club.example/sitemap.xml'); + }); + + test('resolves an llms.txt per language of the pages that render on the server, linking the other languages', () => { + const home: SeoPage = createPage('/', LOCALES); + home.localized = home.localized.map(l => ({ ...l, description: `About the club in ${l.locale.code}` })); + const shop: SeoPage = { ...createPage('/shop', LOCALES), renderMode: RenderMode.Client }; + shop.localized = shop.localized.map(l => ({ ...l, title: undefined })); + const pages: SeoPage[] = [home, createPage('/teams', LOCALES), shop]; + + expect(SeoServerUtilities.resolveLlmsTxt(pages, DE, LOCALES, ORIGIN)).toBe([ + '# / in de', + '', + '> About the club in de', + '', + '## Pages', + '', + '- [/ in de](https://club.example/de): About the club in de', + '- [/teams in de](https://club.example/de/teams)', + '', + '## Languages', + '', + '- [en](https://club.example/llms.txt)' + ].join('\n')); + expect(SeoServerUtilities.resolveLlmsTxt(pages, EN, LOCALES, ORIGIN)).toContain('- [de](https://club.example/de/llms.txt)'); + // a site of one language, without a start page, names itself by its origin + expect(SeoServerUtilities.resolveLlmsTxt([createPage('/teams', [EN])], EN, [EN], ORIGIN)) + .toBe('# https://club.example\n\n## Pages\n\n- [/teams in en](https://club.example/en/teams)'); + }); + + test('resolves the language a visitor prefers by the Accept-Language of their browser', () => { + const locales: SeoLocale[] = [{ code: 'en-US', subPath: 'en' }, { code: 'de', subPath: 'de' }, { code: 'fr-CH', subPath: 'fr' }]; + + expect(SeoServerUtilities.resolvePreferredLocale('de-AT,de;q=0.9,en;q=0.8', locales).code).toBe('de'); + // by its quality rather than its place + expect(SeoServerUtilities.resolvePreferredLocale('en;q=0.5, fr-ch;q=0.9', locales).code).toBe('fr-CH'); + // the language of a code the site has another region of + expect(SeoServerUtilities.resolvePreferredLocale('fr-FR', locales).code).toBe('fr-CH'); + // one the visitor refuses, and none at all, are the source language + expect(SeoServerUtilities.resolvePreferredLocale('de;q=0, it', locales).code).toBe('en-US'); + expect(SeoServerUtilities.resolvePreferredLocale('*', locales).code).toBe('en-US'); + expect(SeoServerUtilities.resolvePreferredLocale(undefined, locales).code).toBe('en-US'); + expect(() => SeoServerUtilities.resolvePreferredLocale('de', [])).toThrow('The site needs at least one language.'); + }); + + test('redirects an url without a language to the one the visitor prefers', () => { + expect(SeoServerUtilities.findLocaleRedirect('/', 'de-DE', LOCALES)).toBe('/de'); + expect(SeoServerUtilities.findLocaleRedirect('/teams/juniors?season=2026', 'fr, en', LOCALES)).toBe('/en/teams/juniors?season=2026'); + expect(SeoServerUtilities.findLocaleRedirect('/teams', undefined, LOCALES)).toBe('/en/teams'); + // an url with its language, and the files of the whole site + expect(SeoServerUtilities.findLocaleRedirect('/de/teams', 'en', LOCALES)).toBeUndefined(); + expect(SeoServerUtilities.findLocaleRedirect('/en', 'de', LOCALES)).toBeUndefined(); + expect(SeoServerUtilities.findLocaleRedirect('/robots.txt', 'de', LOCALES)).toBeUndefined(); + expect(SeoServerUtilities.findLocaleRedirect('/llms.txt', 'de', LOCALES)).toBeUndefined(); + expect(SeoServerUtilities.findLocaleRedirect('/sitemap.xml', 'de', LOCALES)).toBeUndefined(); + expect(SeoServerUtilities.findLocaleRedirect('/sitemap-2.xml', 'de', LOCALES)).toBeUndefined(); + // a segment that only starts like a language + expect(SeoServerUtilities.findLocaleRedirect('/english', 'de', LOCALES)).toBe('/de/english'); + // a site of one language + expect(SeoServerUtilities.findLocaleRedirect('/teams', 'de', [EN])).toBeUndefined(); + }); + + test('redirects an url with a slash at the end of its path to the one without it', () => { + expect(SeoServerUtilities.findTrailingSlashRedirect('/teams/')).toBe('/teams'); + expect(SeoServerUtilities.findTrailingSlashRedirect('/de/teams//?season=2026')).toBe('/de/teams?season=2026'); + expect(SeoServerUtilities.findTrailingSlashRedirect('/de/')).toBe('/de'); + expect(SeoServerUtilities.findTrailingSlashRedirect('/')).toBeUndefined(); + expect(SeoServerUtilities.findTrailingSlashRedirect('/?season=2026')).toBeUndefined(); + expect(SeoServerUtilities.findTrailingSlashRedirect('/teams?next=/')).toBeUndefined(); + }); +}); \ No newline at end of file diff --git a/projects/ngx-navigation/seo-server/seo-server.utilities.ts b/projects/ngx-navigation/seo-server/seo-server.utilities.ts new file mode 100644 index 0000000..c86e217 --- /dev/null +++ b/projects/ngx-navigation/seo-server/seo-server.utilities.ts @@ -0,0 +1,401 @@ +import { RenderMode, ServerRoute } from '@angular/ssr'; +import { NavSitemapEntry } from '@service-soft/ngx-navigation/navigation'; +import { SeoLocale, SeoPageRoute, SeoRouteUtilities, SeoSitemapContext, SeoUrlUtilities } from '@service-soft/ngx-navigation/seo'; + +import { SeoLocalizedPage } from './seo-localized-page.model'; +import { SeoPage } from './seo-page.model'; +import { SeoRobotsOptions } from './seo-robots-options.model'; +import { SeoServerConfig } from './seo-server-config.model'; +import { SeoSite } from './seo-site.model'; + +/** + * The title and the description of a page as its html holds them. + */ +type PageTexts = Pick; + +// what search engines read of one sitemap at most, see https://www.sitemaps.org/protocol.html +const MAX_SITEMAP_URLS: number = 50_000; +const MAX_SITEMAP_BYTES: number = 50 * 1024 * 1024; + +const SITEMAP_PATH: string = '/sitemap.xml'; + +// the page resolvePages has the app render to run the data.sitemap of its routes: an unknown one, which the route of +// unknown urls renders on the server, to answer 404 +const SITEMAP_REQUEST_PATH: string = '/__ngx-seo-sitemap'; + +// the files a server answers itself, which are the same in every language and redirect to none +const SITE_FILES: string[] = ['/robots.txt', '/llms.txt']; + +const XML_ESCAPES: Record = { '&': '&', '<': '<', '>': '>', '"': '"', '\'': ''' }; + +const HTML_ENTITIES: Record = { '<': '<', '>': '>', '"': '"', ''': '\'', '&': '&' }; + +/** + * What a website tells search engines and AI assistants about all of its pages, for its server: the sitemap, the + * robots.txt and the llms.txt, and the redirects that give each page one url. Built from the routes of the app, so a + * page is found however Angular renders it, and in every language Angular i18n builds. + */ +export abstract class SeoServerUtilities { + /** + * Finds every page of a site that search engines may index, in every language: the routes of the router config, + * children and lazily loaded children included, without redirects, without the route of unknown urls and without + * routes whose data.robots holds noindex. A route with parameters gets the pages Angular prerendered for it, and the + * ones its data.sitemap lists, which the app runs as the app engine renders a page on the server. Its title and + * description in each language are read from the page as that language renders it, as the app engine answers it: + * prerendered, or rendered once now. A page only a browser renders has neither. + * @param config - Where the pages are found. + * @returns The pages, and the routes with parameters whose pages could not be listed. + * @throws {Error} When a route has a data.sitemap, but no page renders on the server to run it. + */ + static async resolvePages(config: SeoServerConfig): Promise { + const prerenderedPaths: string[] = this.findPrerenderedPaths(config); + const routes: SeoPageRoute[] = await SeoRouteUtilities.findPageRoutes(config.routes); + const listed: Record = await this.resolveListedPages(config, routes); + const pages: SeoPage[] = []; + const unlistedRoutes: string[] = []; + for (const route of routes) { + const renderMode: RenderMode = this.findRenderMode(config.serverRoutes, route.path); + const entries: NavSitemapEntry[] = this.resolveEntries(route, listed[route.path] ?? [], prerenderedPaths); + if (!entries.length) { + unlistedRoutes.push(`/${route.path}`); + } + for (const entry of entries) { + pages.push({ + path: entry.path, + renderMode, + lastModified: entry.lastModified ?? route.data.lastModified, + localized: await Promise.all( + config.locales.map(locale => this.resolveLocalizedPage(config, entry.path, locale, renderMode)) + ) + }); + } + } + return { pages, unlistedRoutes }; + } + + /** + * Resolves the sitemap of a site: one url per page and language, with the url of the page in every other language + * and its url without a language as x-default, and the date of its content when it is known. Over 50,000 urls or + * 50 MB, /sitemap.xml is an index of the parts /sitemap-1.xml, /sitemap-2.xml and so on. + * @param pages - The pages of the site. + * @param origin - The origin of the site, which the index links its parts with. + * @returns Each file of the sitemap, by its path. + */ + static resolveSitemapFiles(pages: SeoPage[], origin: string): Record { + const entries: string[] = pages.flatMap(page => page.localized.map(localized => this.resolveSitemapEntry(page, localized))); + const parts: string[][] = this.splitSitemap(entries); + if (parts.length === 1) { + return { [SITEMAP_PATH]: this.resolveUrlSet(parts[0] ?? []) }; + } + const files: Record = {}; + const sitemaps: string[] = parts.map((part, index) => { + const partPath: string = `/sitemap-${index + 1}.xml`; + const partUrl: string = this.escapeXml(origin + partPath); + files[partPath] = this.resolveUrlSet(part); + return ` ${partUrl}`; + }); + files[SITEMAP_PATH] = [ + '', + '', + ...sitemaps, + '' + ].join('\n'); + return files; + } + + /** + * Resolves the robots.txt of a site: whether search engines may read it, the crawlers that may not, and where its + * sitemap is. + * @param options - What it says. + * @returns The robots.txt. + */ + static resolveRobotsTxt(options: SeoRobotsOptions): string { + return [ + 'User-agent: *', + `${options.allowed ? 'Allow' : 'Disallow'}: /`, + '', + ...options.disallowedCrawlers.flatMap(crawler => [`User-agent: ${crawler}`, 'Disallow: /', '']), + `Sitemap: ${options.sitemapUrl}` + ].join('\n'); + } + + /** + * Resolves the llms.txt of a site in one language, see https://llmstxt.org: what the site is, and its pages that + * render on the server, which assistants read without running a script. Lists where the other languages have + * theirs: /llms.txt is the one of the source language, //llms.txt the one of another. + * @param pages - The pages of the site. + * @param locale - The language. + * @param locales - Every language of the site, the source language first. + * @param origin - The origin of the site. + * @returns The llms.txt, in markdown. + */ + static resolveLlmsTxt(pages: SeoPage[], locale: SeoLocale, locales: SeoLocale[], origin: string): string { + const localized: SeoLocalizedPage[] = pages + .flatMap(page => page.localized.filter(l => l.locale.code === locale.code && l.title != undefined)); + const home: SeoLocalizedPage | undefined = pages + .find(page => page.path === '/') + ?.localized.find(l => l.locale.code === locale.code); + const others: SeoLocale[] = locales.filter(l => l.code !== locale.code); + return [ + `# ${home?.title ?? origin}`, + ...home?.description == undefined ? [] : ['', `> ${home.description}`], + '', + '## Pages', + '', + ...localized.map(page => `- [${page.title}](${page.url})${page.description == undefined ? '' : ': ' + page.description}`), + ...others.length + ? ['', '## Languages', '', ...others.map(l => `- [${l.code}](${this.resolveLlmsTxtUrl(l, locales, origin)})`)] + : [] + ].join('\n'); + } + + /** + * Resolves the language a visitor prefers, by the Accept-Language header of their browser: the first language of + * the site they accept, by its code or by the language of it, like 'de' for 'de-AT'. + * @param acceptLanguage - The Accept-Language header, like 'de-AT,de;q=0.9,en;q=0.8'. + * @param locales - The languages of the site, the source language first. + * @returns The language, the source language when the visitor accepts none of them. + * @throws {Error} When the site has no language. + */ + static resolvePreferredLocale(acceptLanguage: string | undefined, locales: SeoLocale[]): SeoLocale { + const source: SeoLocale | undefined = locales[0]; + if (source == undefined) { + throw new Error('The site needs at least one language.'); + } + const accepted: string[] = (acceptLanguage ?? '') + .split(',') + .map(part => part.trim().split(';q=')) + .map(([tag = '', quality = '1']) => ({ tag: tag.toLowerCase(), quality: Number(quality) })) + .filter(language => language.tag !== '' && language.tag !== '*' && language.quality > 0) + .sort((a, b) => b.quality - a.quality) + .map(language => language.tag); + for (const tag of accepted) { + const locale: SeoLocale | undefined = locales.find(l => l.code.toLowerCase() === tag) + ?? locales.find(l => l.code.toLowerCase().split('-')[0] === tag.split('-')[0]); + if (locale != undefined) { + return locale; + } + } + return source; + } + + /** + * Finds where an url without a language redirects to, for a site in several languages: the same page in the + * language the visitor prefers. Answer it with a 302 and Vary: Accept-Language, so search engines index each + * language at its own url. + * @param url - The path of the request, with its query. + * @param acceptLanguage - The Accept-Language header of the request. + * @param locales - The languages of the site, the source language first. + * @returns The url to redirect to, or undefined for an url that has its language, a file of the whole site or a site + * with one language. + */ + static findLocaleRedirect(url: string, acceptLanguage: string | undefined, locales: SeoLocale[]): string | undefined { + if (locales.length < 2) { + return undefined; + } + const pagePath: string = SeoUrlUtilities.normalizePath(url); + const firstSegment: string = pagePath.split('/')[1] ?? ''; + if (locales.some(locale => locale.subPath === firstSegment) || SITE_FILES.includes(pagePath) || this.isSitemapPath(pagePath)) { + return undefined; + } + const query: string = url.includes('?') ? url.slice(url.indexOf('?')) : ''; + const target: SeoLocale = this.resolvePreferredLocale(acceptLanguage, locales); + return `${new URL(SeoUrlUtilities.resolveUrl('http://localhost', pagePath, target)).pathname}${query}`; + } + + /** + * Finds where an url with a slash at the end of its path redirects to: the url without it, the query kept, so each + * page has one url. Answer it with a 301. + * @param url - The path of the request, with its query. + * @returns The url to redirect to, or undefined for one without a slash at its end and the start page. + */ + static findTrailingSlashRedirect(url: string): string | undefined { + const queryStart: number = url.indexOf('?'); + const urlPath: string = queryStart === -1 ? url : url.slice(0, queryStart); + if (urlPath === '/' || !urlPath.endsWith('/')) { + return undefined; + } + return `${SeoUrlUtilities.normalizePath(urlPath)}${queryStart === -1 ? '' : url.slice(queryStart)}`; + } + + // the data.sitemap of the routes, which the app runs as it renders a page on the server for a request with the + // context. Only a page rendered for each request gets it: the route of unknown urls, or else a page without + // parameters that renders on the server + private static async resolveListedPages(config: SeoServerConfig, routes: SeoPageRoute[]): Promise> { + if (!routes.some(route => route.data.sitemap != undefined)) { + return {}; + } + const candidates: string[] = [ + SITEMAP_REQUEST_PATH, + ...routes.filter(route => !this.hasParameters(route.path)).map(route => `/${route.path}`) + ].filter(candidate => this.findRenderMode(config.serverRoutes, candidate) === RenderMode.Server); + for (const candidate of candidates) { + const context: SeoSitemapContext = { ngxSeoSitemap: undefined }; + const url: string = SeoUrlUtilities.resolveUrl(config.origin, candidate, config.locales[0]); + const response: Response | null = await config.appEngine.handle(new Request(url), context); + // the app has run them once the page is rendered + await response?.text(); + if (context.ngxSeoSitemap != undefined) { + return context.ngxSeoSitemap; + } + } + throw new Error('The data.sitemap of a route runs in the app as the server renders a page, which needs one with ' + + 'RenderMode.Server, like the route of unknown urls: { path: \'**\', renderMode: RenderMode.Server, status: 404 }. ' + + 'And the app needs provideSeoConfig.'); + } + + // the pages of a route: the one of its path, or the ones of its parameters, listed or prerendered + private static resolveEntries(route: SeoPageRoute, listed: NavSitemapEntry[], prerenderedPaths: string[]): NavSitemapEntry[] { + if (!this.hasParameters(route.path)) { + return [{ path: `/${route.path}` }]; + } + const prerendered: NavSitemapEntry[] = prerenderedPaths + .filter(prerenderedPath => this.matchesPattern(route.path, prerenderedPath)) + .filter(prerenderedPath => !listed.some(entry => SeoUrlUtilities.normalizePath(entry.path) === prerenderedPath)) + .map(prerenderedPath => ({ path: prerenderedPath })); + return [...listed.map(entry => ({ ...entry, path: SeoUrlUtilities.normalizePath(entry.path) })), ...prerendered]; + } + + private static hasParameters(routePath: string): boolean { + return routePath.split('/').some(segment => segment.startsWith(':')); + } + + private static async resolveLocalizedPage( + config: SeoServerConfig, + pagePath: string, + locale: SeoLocale, + renderMode: RenderMode + ): Promise { + const url: string = SeoUrlUtilities.resolveUrl(config.origin, pagePath, locale); + const texts: PageTexts = renderMode === RenderMode.Client + ? { title: undefined, description: undefined } + : await this.resolvePageTexts(config, url); + return { locale, url, ...texts }; + } + + // the page as the app engine answers it: its prerendered html, or the page rendered now + private static async resolvePageTexts(config: SeoServerConfig, url: string): Promise { + const response: Response | null = await config.appEngine.handle(new Request(url)); + return response?.ok === true ? this.findPageTexts(await response.text()) : { title: undefined, description: undefined }; + } + + private static findPageTexts(html: string): PageTexts { + const title: string | undefined = /([^<]*)<\/title>/.exec(html)?.[1]; + const description: string | undefined = /<meta name="description" content="([^"]*)"/.exec(html)?.[1]; + return { + title: title == undefined ? undefined : this.decodeHtml(title), + description: description == undefined ? undefined : this.decodeHtml(description) + }; + } + + // the paths of the prerendered pages without their language, which the routes with parameters are matched against + private static findPrerenderedPaths(config: SeoServerConfig): string[] { + const subPaths: string[] = config.locales.map(locale => locale.subPath).filter(subPath => subPath !== ''); + const paths: string[] = config.prerenderedRoutes.map(route => { + const segments: string[] = route.split('/').filter(segment => segment !== ''); + const withoutLocale: string[] = subPaths.includes(segments[0] ?? '') ? segments.slice(1) : segments; + return `/${withoutLocale.join('/')}`; + }); + return [...new Set(paths)]; + } + + // by the first server route that matches, like the router of @angular/ssr finds it, and on the server when none does + private static findRenderMode(serverRoutes: ServerRoute[], routePath: string): RenderMode { + return serverRoutes.find(serverRoute => this.matchesPattern(serverRoute.path, routePath))?.renderMode ?? RenderMode.Server; + } + + // whether a path matches a pattern of routes, like 'teams/:team', '*' or '**'. A parameter of the path matches a + // parameter or any segment of the pattern + private static matchesPattern(pattern: string, routePath: string): boolean { + const patternSegments: string[] = pattern.split('/').filter(segment => segment !== ''); + const pathSegments: string[] = routePath.split('/').filter(segment => segment !== ''); + for (const [index, segment] of patternSegments.entries()) { + if (segment === '**') { + return true; + } + const pathSegment: string | undefined = pathSegments[index]; + if (pathSegment == undefined) { + return false; + } + if (segment !== '*' && !segment.startsWith(':') && segment !== pathSegment) { + return false; + } + } + return patternSegments.length === pathSegments.length; + } + + private static resolveSitemapEntry(page: SeoPage, localized: SeoLocalizedPage): string { + // alternates only mean something with more than one language + const alternates: string[] = page.localized.length < 2 + ? [] + : [ + ...page.localized.map(other => this.resolveAlternate(other.locale.code, other.url)), + this.resolveAlternate('x-default', SeoUrlUtilities.resolveUrl(new URL(localized.url).origin, page.path, undefined)) + ]; + return [ + ' <url>', + ` <loc>${this.escapeXml(localized.url)}</loc>`, + ...alternates, + ...page.lastModified == undefined + ? [] + : [` <lastmod>${this.resolveLastModified(page.path, page.lastModified)}</lastmod>`], + ' </url>' + ].join('\n'); + } + + // the W3C datetime of the sitemap protocol, like 2026-11-01T00:00:00.000Z + private static resolveLastModified(path: string, lastModified: Date): string { + // like a date of an api that new Date could not read + if (Number.isNaN(lastModified.getTime())) { + throw new Error(`The lastModified of ${path} is no valid date.`); + } + return lastModified.toISOString(); + } + + private static resolveAlternate(hreflang: string, href: string): string { + return ` <xhtml:link rel="alternate" hreflang="${this.escapeXml(hreflang)}" href="${this.escapeXml(href)}"/>`; + } + + private static resolveUrlSet(entries: string[]): string { + return [ + '<?xml version="1.0" encoding="UTF-8"?>', + '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">', + ...entries, + '</urlset>' + ].join('\n'); + } + + // parts of at most 50,000 urls and 50 MB each, measured in bytes as the file is sent + private static splitSitemap(entries: string[]): string[][] { + const parts: string[][] = [[]]; + let bytes: number = 0; + for (const entry of entries) { + const entryBytes: number = new TextEncoder().encode(entry).length + 1; + const current: string[] = parts.at(-1) ?? []; + if (current.length >= MAX_SITEMAP_URLS || bytes + entryBytes > MAX_SITEMAP_BYTES - 1024) { + parts.push([entry]); + bytes = entryBytes; + continue; + } + current.push(entry); + bytes += entryBytes; + } + return parts; + } + + private static resolveLlmsTxtUrl(locale: SeoLocale, locales: SeoLocale[], origin: string): string { + return locale === locales[0] || locale.subPath === '' ? `${origin}/llms.txt` : `${origin}/${locale.subPath}/llms.txt`; + } + + private static isSitemapPath(pagePath: string): boolean { + return /^\/sitemap(-\d+)?\.xml$/.test(pagePath); + } + + private static escapeXml(value: string): string { + return value.replaceAll(/[&<>"']/g, character => XML_ESCAPES[character] ?? character); + } + + private static decodeHtml(value: string): string { + return value.replaceAll(/&(lt|gt|quot|#39|amp);/g, entity => HTML_ENTITIES[entity] ?? entity); + } +} \ No newline at end of file diff --git a/projects/ngx-navigation/seo-server/seo-site.model.ts b/projects/ngx-navigation/seo-server/seo-site.model.ts new file mode 100644 index 0000000..72b7473 --- /dev/null +++ b/projects/ngx-navigation/seo-server/seo-site.model.ts @@ -0,0 +1,16 @@ +import { SeoPage } from './seo-page.model'; + +/** + * The pages of a site, as resolvePages finds them. + */ +export type SeoSite = { + /** + * Every page search engines may index. + */ + pages: SeoPage[], + /** + * The routes with parameters whose pages could not be listed: Angular prerendered none of them, and their data has + * no sitemap. Their pages are missing from the sitemap, which a server can warn about. + */ + unlistedRoutes: string[] +}; \ No newline at end of file diff --git a/projects/ngx-navigation/seo/public-api.ts b/projects/ngx-navigation/seo/public-api.ts index 2260e5f..8e973b6 100644 --- a/projects/ngx-navigation/seo/public-api.ts +++ b/projects/ngx-navigation/seo/public-api.ts @@ -1,4 +1,9 @@ export * from './seo-config-changes.model'; export * from './seo-config.model'; export * from './seo-config.provider'; +export * from './seo-locale.model'; +export * from './seo-page-route.model'; +export * from './seo-route.utilities'; +export * from './seo-sitemap-context.model'; +export * from './seo-url.utilities'; export * from './seo.provider'; \ No newline at end of file diff --git a/projects/ngx-navigation/seo/seo-config-changes.model.ts b/projects/ngx-navigation/seo/seo-config-changes.model.ts index f40f5cd..f4773d9 100644 --- a/projects/ngx-navigation/seo/seo-config-changes.model.ts +++ b/projects/ngx-navigation/seo/seo-config-changes.model.ts @@ -1,6 +1,6 @@ import { SeoConfig } from './seo-config.model'; /** - * What provideSeoConfig is given: the origin, and a default image if you like. + * What provideSeoConfig is given: the origin, and a default image and the languages of the site if you like. */ export type SeoConfigChanges = Pick<SeoConfig, 'origin'> & Partial<Omit<SeoConfig, 'origin'>>; \ No newline at end of file diff --git a/projects/ngx-navigation/seo/seo-config.model.ts b/projects/ngx-navigation/seo/seo-config.model.ts index 97f62e5..82cf504 100644 --- a/projects/ngx-navigation/seo/seo-config.model.ts +++ b/projects/ngx-navigation/seo/seo-config.model.ts @@ -1,3 +1,5 @@ +import { SeoLocale } from './seo-locale.model'; + /** * What every page tells search engines and AI assistants about itself, next to the data of its route. Set it with * provideSeoConfig. @@ -12,5 +14,11 @@ export type SeoConfig = { * The image a shared link shows for a page without an `image` in its data, absolute or relative to the origin. * None when undefined. */ - defaultImage: string | undefined + defaultImage: string | undefined, + /** + * The languages of the site, as Angular i18n builds them, the source language first. With more than one, a page + * links to itself in each with hreflang, and to its url without a language as x-default. Empty for a site with one + * language, whose pages have no prefix. + */ + locales: SeoLocale[] }; \ No newline at end of file diff --git a/projects/ngx-navigation/seo/seo-locale.model.ts b/projects/ngx-navigation/seo/seo-locale.model.ts new file mode 100644 index 0000000..edf0aac --- /dev/null +++ b/projects/ngx-navigation/seo/seo-locale.model.ts @@ -0,0 +1,14 @@ +/** + * A language of a site, as Angular i18n builds it: its code, and the path its pages are served below. + */ +export type SeoLocale = { + /** + * The code of the language, like 'en' or 'de-CH', which hreflang names it by. + */ + code: string, + /** + * The path of its pages, like 'en' for /en/imprint, as the i18n.locales of angular.json name it. Empty for a site + * with one language, whose pages have no prefix. + */ + subPath: string +}; \ No newline at end of file diff --git a/projects/ngx-navigation/seo/seo-page-route.model.ts b/projects/ngx-navigation/seo/seo-page-route.model.ts new file mode 100644 index 0000000..bf5522c --- /dev/null +++ b/projects/ngx-navigation/seo/seo-page-route.model.ts @@ -0,0 +1,15 @@ +import { NavRouteData } from '@service-soft/ngx-navigation/navigation'; + +/** + * A route of the router config that renders a page, with the path of its parents and the data of all of them. + */ +export type SeoPageRoute = { + /** + * The path of the route below the start page, like 'teams/:team', '' for the start page. + */ + path: string, + /** + * Its data, with the data of its parents below it, like the router merges it. + */ + data: NavRouteData +}; \ No newline at end of file diff --git a/projects/ngx-navigation/seo/seo-route.utilities.ts b/projects/ngx-navigation/seo/seo-route.utilities.ts new file mode 100644 index 0000000..5bb3027 --- /dev/null +++ b/projects/ngx-navigation/seo/seo-route.utilities.ts @@ -0,0 +1,87 @@ +import { EnvironmentInjector, runInInjectionContext } from '@angular/core'; +import { Route, Routes } from '@angular/router'; +import { NavRouteData, NavSitemapEntry } from '@service-soft/ngx-navigation/navigation'; + +import { SeoPageRoute } from './seo-page-route.model'; +import { SeoSitemapContext } from './seo-sitemap-context.model'; + +/** + * Finds the pages of the routes of an app, the same way in the app and on its server, which lists them for the + * sitemap. + */ +export abstract class SeoRouteUtilities { + /** + * Finds the routes that render a page search engines may index, depth first: children and lazily loaded children + * included, without redirects, without the route of unknown urls and matchers, and without routes whose data.robots + * holds noindex. + * @param routes - The routes of the app, the same that provideRouter gets. + * @returns The routes of the pages, by their whole path. + */ + static async findPageRoutes(routes: Routes): Promise<SeoPageRoute[]> { + return this.findChildPageRoutes(routes, '', {}); + } + + /** + * Resolves the pages that the data.sitemap of each route lists, in an injection context of the app, so they can + * inject what they read them with, like the HttpClient. + * @param routes - The routes of the app. + * @param injector - The injector of the app. + * @returns The pages, by the path of their route, like 'news/:article'. + */ + static async resolveListedPages(routes: Routes, injector: EnvironmentInjector): Promise<Record<string, NavSitemapEntry[]>> { + const listed: Record<string, NavSitemapEntry[]> = {}; + for (const route of await this.findPageRoutes(routes)) { + const sitemap: NavRouteData['sitemap'] = route.data.sitemap; + if (sitemap != undefined) { + listed[route.path] = await runInInjectionContext(injector, sitemap); + } + } + return listed; + } + + /** + * Whether the REQUEST_CONTEXT of a request is the one SeoServerUtilities.resolvePages renders a page with, to run + * the data.sitemap of the routes. + * @param context - The REQUEST_CONTEXT, null in the browser and for a page rendered for any other request. + * @returns Whether it is. + */ + static isSitemapContext(context: unknown): context is SeoSitemapContext { + return typeof context === 'object' && context != undefined && 'ngxSeoSitemap' in context; + } + + private static async findChildPageRoutes(routes: Routes, parentPath: string, parentData: NavRouteData): Promise<SeoPageRoute[]> { + const pages: SeoPageRoute[] = []; + for (const route of routes) { + if (route.redirectTo != undefined || route.path?.includes('**') === true || route.matcher != undefined) { + continue; + } + const routePath: string = [parentPath, route.path ?? ''].filter(segment => segment !== '').join('/'); + const data: NavRouteData = { ...parentData, ...route.data }; + if (data.robots?.toLowerCase().includes('noindex') === true) { + continue; + } + if (route.component != undefined || route.loadComponent != undefined) { + pages.push({ path: routePath, data }); + } + pages.push(...await this.findChildPageRoutes(await this.resolveChildren(route), routePath, data)); + } + // a parent with a component and a child of the empty path render the same page + return [...new Map(pages.map(page => [page.path, page])).values()]; + } + + private static async resolveChildren(route: Route): Promise<Routes> { + if (route.children != undefined) { + return route.children; + } + if (route.loadChildren == undefined) { + return []; + } + const loaded: unknown = await route.loadChildren(); + // the routes themselves, or the module that exports them as its default + if (Array.isArray(loaded)) { + return loaded as Routes; + } + const exported: unknown = typeof loaded === 'object' && loaded != undefined && 'default' in loaded ? loaded.default : undefined; + return Array.isArray(exported) ? exported as Routes : []; + } +} \ No newline at end of file diff --git a/projects/ngx-navigation/seo/seo-sitemap-context.model.ts b/projects/ngx-navigation/seo/seo-sitemap-context.model.ts new file mode 100644 index 0000000..d53c5e2 --- /dev/null +++ b/projects/ngx-navigation/seo/seo-sitemap-context.model.ts @@ -0,0 +1,12 @@ +import { NavSitemapEntry } from '@service-soft/ngx-navigation/navigation'; + +/** + * The REQUEST_CONTEXT of the request SeoServerUtilities.resolvePages renders a page for, in which provideSeoConfig runs + * the data.sitemap of every route in the app, before the page renders. + */ +export type SeoSitemapContext = { + /** + * The pages data.sitemap lists, by the path of their route, like 'news/:article'. Undefined until the app ran them. + */ + ngxSeoSitemap: Record<string, NavSitemapEntry[]> | undefined +}; \ No newline at end of file diff --git a/projects/ngx-navigation/seo/seo-url.utilities.ts b/projects/ngx-navigation/seo/seo-url.utilities.ts new file mode 100644 index 0000000..4e8828d --- /dev/null +++ b/projects/ngx-navigation/seo/seo-url.utilities.ts @@ -0,0 +1,35 @@ +import { SeoLocale } from './seo-locale.model'; + +/** + * Builds the urls of the pages of a site the same way in the browser and on the server, so the canonical url of a page + * and the url of the sitemap are always the same one: one url per page, without a slash at its end. + */ +export abstract class SeoUrlUtilities { + /** + * Resolves the url of a page in a language, like 'https://example.com/de/imprint'. + * @param origin - The origin of the site, without a slash at its end. + * @param path - The path of the page without its language, like '/imprint', or '/' for the start page. + * @param locale - The language, or undefined for the url without one, which redirects by the language of the visitor. + * @returns The absolute url. + */ + static resolveUrl(origin: string, path: string, locale: SeoLocale | undefined): string { + const prefix: string = locale == undefined || locale.subPath === '' ? '' : `/${locale.subPath}`; + const pagePath: string = this.normalizePath(path); + // the start page of a language is /en, without a slash, like every other page; the start page of the site is / + if (pagePath === '/') { + return prefix === '' ? `${origin}/` : `${origin}${prefix}`; + } + return `${origin}${prefix}${pagePath}`; + } + + /** + * Gets the path of a page without its query, its hash and a slash at its end, like '/imprint' of '/imprint/?a=1'. + * @param url - The path of the page as the router or a request has it. + * @returns The path, '/' for the start page. + */ + static normalizePath(url: string): string { + const path: string = url.split(/[?#]/)[0] ?? ''; + const trimmed: string = path.replace(/\/+$/, ''); + return trimmed === '' ? '/' : trimmed.startsWith('/') ? trimmed : `/${trimmed}`; + } +} \ No newline at end of file diff --git a/projects/ngx-navigation/seo/seo.provider.ts b/projects/ngx-navigation/seo/seo.provider.ts index 5b12ba3..e0011de 100644 --- a/projects/ngx-navigation/seo/seo.provider.ts +++ b/projects/ngx-navigation/seo/seo.provider.ts @@ -1,26 +1,41 @@ -import { EnvironmentProviders, inject, makeEnvironmentProviders, provideAppInitializer } from '@angular/core'; +import { EnvironmentInjector, EnvironmentProviders, inject, makeEnvironmentProviders, provideAppInitializer, REQUEST_CONTEXT } from '@angular/core'; +import { Router } from '@angular/router'; import { SeoConfigChanges } from './seo-config-changes.model'; import { SeoConfig } from './seo-config.model'; import { SEO_CONFIG } from './seo-config.provider'; +import { SeoRouteUtilities } from './seo-route.utilities'; import { SeoService } from './seo.service'; /** * Writes what each page tells search engines and AI assistants about itself into the head of the document, on every * navigation and on the server too, so the prerendered html holds it: the description, the canonical url, the - * structured data, the robots and the og tags of a shared link, from the NavRouteData of its routes. Provide it in - * the application config: `provideSeoConfig({ origin: 'https://example.com' })`. - * @param config - The origin of the site, and a default image if you like. + * structured data, the robots, the og tags of a shared link and, for a site in several languages, the url of the page + * in each of them, from the NavRouteData of its routes. On the server, it also runs the data.sitemap of the routes for + * SeoServerUtilities.resolvePages of `@service-soft/ngx-navigation/seo-server`. Provide it in the application config: + * `provideSeoConfig({ origin: 'https://example.com' })`, with `locales` for a site Angular i18n builds in several + * languages. + * @param config - The origin of the site, a default image and the languages if you like. * @returns The providers for the SEO. */ export function provideSeoConfig(config: SeoConfigChanges): EnvironmentProviders { // no merging with a parent injector: the tags are the ones of the document, which only the root injector writes. - const seoConfig: SeoConfig = { origin: config.origin.replace(/\/+$/, ''), defaultImage: config.defaultImage }; + const seoConfig: SeoConfig = { + origin: config.origin.replace(/\/+$/, ''), + defaultImage: config.defaultImage, + locales: config.locales ?? [] + }; return makeEnvironmentProviders([ { provide: SEO_CONFIG, useValue: seoConfig }, // before the first navigation, whose tags the service writes as well - provideAppInitializer(() => { + provideAppInitializer(async () => { inject(SeoService); + // only the request resolvePages renders a page for has it, which nobody outside of the server can send + const context: unknown = inject(REQUEST_CONTEXT); + if (SeoRouteUtilities.isSitemapContext(context)) { + // the page renders once they are done + context.ngxSeoSitemap = await SeoRouteUtilities.resolveListedPages(inject(Router).config, inject(EnvironmentInjector)); + } }) ]); } \ No newline at end of file diff --git a/projects/ngx-navigation/seo/seo.service.spec.ts b/projects/ngx-navigation/seo/seo.service.spec.ts index 1186a7a..c36302f 100644 --- a/projects/ngx-navigation/seo/seo.service.spec.ts +++ b/projects/ngx-navigation/seo/seo.service.spec.ts @@ -1,4 +1,4 @@ -import { Component } from '@angular/core'; +import { Component, LOCALE_ID } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideRouter, Router } from '@angular/router'; import { NavRoute } from '@service-soft/ngx-navigation/navigation'; @@ -49,6 +49,11 @@ function findContent(selector: string): string | undefined { return document.head.querySelector(selector)?.getAttribute('content') ?? undefined; } +function findAlternates(): [string | null, string | null][] { + return [...document.head.querySelectorAll('link[rel="alternate"][hreflang]')] + .map(link => [link.getAttribute('hreflang'), link.getAttribute('href')]); +} + function findStructuredData(): unknown[] { return [...document.head.querySelectorAll('script[type="application/ld+json"]')].map(script => JSON.parse(script.textContent) as unknown); } @@ -103,4 +108,47 @@ describe('provideSeoConfig', () => { expect(findStructuredData()).toEqual([{ '@type': 'SportsTeam', name: 'juniors' }]); expect(findContent('meta[property="og:title"]')).toBe('Team'); }); + + test('links a page in a site of several languages to itself in each, and to its url without a language', async () => { + // the build of the German language, which Angular i18n gives its own LOCALE_ID and serves below /de + TestBed.configureTestingModule({ + providers: [ + provideRouter(ROUTES), + provideSeoConfig({ origin: 'https://club.example', locales: [{ code: 'en', subPath: 'en' }, { code: 'de-CH', subPath: 'de' }] }), + { provide: LOCALE_ID, useValue: 'de-ch' } + ] + }); + const router: Router = TestBed.inject(Router); + await router.navigateByUrl('/teams/juniors?season=2026'); + + expect(document.head.querySelector('link[rel="canonical"]')?.getAttribute('href')).toBe('https://club.example/de/teams/juniors'); + expect(findAlternates()).toEqual([ + ['en', 'https://club.example/en/teams/juniors'], + ['de-CH', 'https://club.example/de/teams/juniors'], + ['x-default', 'https://club.example/teams/juniors'] + ]); + expect(findContent('meta[property="og:url"]')).toBe('https://club.example/de/teams/juniors'); + expect(findContent('meta[property="og:locale"]')).toBe('de_CH'); + expect([...document.head.querySelectorAll('meta[property="og:locale:alternate"]')].map(meta => meta.getAttribute('content'))) + .toEqual(['en']); + + // the start page of a language has no slash at its end, the one of the whole site is / + await router.navigateByUrl('/'); + expect(document.head.querySelector('link[rel="canonical"]')?.getAttribute('href')).toBe('https://club.example/de'); + expect(findAlternates()).toEqual([ + ['en', 'https://club.example/en'], + ['de-CH', 'https://club.example/de'], + ['x-default', 'https://club.example/'] + ]); + expect(document.head.querySelectorAll('meta[property="og:locale:alternate"]')).toHaveLength(1); + }); + + test('writes no alternates for a site of one language', async () => { + const router: Router = setup(); + await router.navigateByUrl('/imprint'); + + expect(findAlternates()).toEqual([]); + expect(document.head.querySelector('link[rel="canonical"]')?.getAttribute('href')).toBe('https://club.example/imprint'); + expect(findContent('meta[property="og:locale"]')).toBeUndefined(); + }); }); \ No newline at end of file diff --git a/projects/ngx-navigation/seo/seo.service.ts b/projects/ngx-navigation/seo/seo.service.ts index 87b6990..39c7791 100644 --- a/projects/ngx-navigation/seo/seo.service.ts +++ b/projects/ngx-navigation/seo/seo.service.ts @@ -1,5 +1,5 @@ import { DOCUMENT } from '@angular/common'; -import { EnvironmentInjector, inject, runInInjectionContext, Service } from '@angular/core'; +import { EnvironmentInjector, inject, LOCALE_ID, runInInjectionContext, Service } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { Meta } from '@angular/platform-browser'; import { ActivatedRouteSnapshot, NavigationEnd, Router, RouterStateSnapshot, TitleStrategy } from '@angular/router'; @@ -8,10 +8,14 @@ import { filter } from 'rxjs'; import { SeoConfig } from './seo-config.model'; import { SEO_CONFIG } from './seo-config.provider'; +import { SeoLocale } from './seo-locale.model'; +import { SeoUrlUtilities } from './seo-url.utilities'; // marks the JSON-LD of the page, so a navigation replaces it, and leaves alone the one of the site in its index.html. const STRUCTURED_DATA_ATTRIBUTE: string = 'data-ngx-seo'; +const HREFLANG_ATTRIBUTE: string = 'hreflang'; + // '<' as a json escape: a backslash (92) and u003c, which every json parser reads as '<' again. const ESCAPED_LESS_THAN: string = `${String.fromCodePoint(92)}u003c`; @@ -33,6 +37,9 @@ export class SeoService { private readonly config: SeoConfig = inject(SEO_CONFIG); + // the language this build of the site is in, which Angular i18n gives every build its own LOCALE_ID for + private readonly locale: SeoLocale | undefined = this.findLocale(inject(LOCALE_ID)); + constructor() { this.router.events .pipe(filter(event => event instanceof NavigationEnd), takeUntilDestroyed()) @@ -42,7 +49,9 @@ export class SeoService { // every tag is written or removed on every navigation, so none of the page before survives it. private writeTags(snapshot: RouterStateSnapshot, url: string): void { const [route, data] = this.findPage(snapshot.root); - const canonicalUrl: string = `${this.config.origin}${url.split(/[?#]/)[0] ?? ''}`; + // the router of a build of one language knows the path without it, below the base href of its language + const path: string = SeoUrlUtilities.normalizePath(url); + const canonicalUrl: string = SeoUrlUtilities.resolveUrl(this.config.origin, path, this.locale); const image: string | undefined = data.image ?? this.config.defaultImage; // the title of the route rather than of the document, which the router only sets after this navigation ended this.writeMeta('property', 'og:title', this.titleStrategy.buildTitle(snapshot)); @@ -52,6 +61,8 @@ export class SeoService { this.writeMeta('property', 'og:url', canonicalUrl); this.writeMeta('property', 'og:image', image == undefined ? undefined : new URL(image, `${this.config.origin}/`).href); this.writeCanonicalUrl(canonicalUrl); + this.writeAlternates(path); + this.writeLocale(); const structuredData: NavRouteData['structuredData'] = data.structuredData; this.writeStructuredData(typeof structuredData === 'function' ? runInInjectionContext(this.injector, () => structuredData(route)) @@ -88,6 +99,47 @@ export class SeoService { link.setAttribute('href', url); } + // the page in every language and, as x-default, its url without one, which redirects by the language of the visitor. + // Absolute, as search engines take nothing else, and only with more than one language, where they mean something + private writeAlternates(path: string): void { + for (const link of this.document.head.querySelectorAll(`link[rel="alternate"][${HREFLANG_ATTRIBUTE}]`)) { + this.document.head.removeChild(link); + } + if (this.config.locales.length < 2) { + return; + } + // each language by its code, and x-default as the url without one + const alternates: [string, string][] = [...this.config.locales, undefined] + .map(locale => [locale?.code ?? 'x-default', SeoUrlUtilities.resolveUrl(this.config.origin, path, locale)]); + for (const [hreflang, href] of alternates) { + const link: HTMLLinkElement = this.document.createElement('link'); + link.setAttribute('rel', 'alternate'); + link.setAttribute(HREFLANG_ATTRIBUTE, hreflang); + link.setAttribute('href', href); + this.document.head.appendChild(link); + } + } + + // og takes the language with an underscore, like en_US, and lists the other languages one tag each + private writeLocale(): void { + for (const tag of this.meta.getTags('property="og:locale:alternate"')) { + this.meta.removeTagElement(tag); + } + if (this.locale == undefined) { + this.meta.removeTag('property="og:locale"'); + return; + } + this.meta.updateTag({ property: 'og:locale', content: this.locale.code.replace('-', '_') }); + for (const locale of this.config.locales.filter(l => l !== this.locale)) { + this.meta.addTag({ property: 'og:locale:alternate', content: locale.code.replace('-', '_') }); + } + } + + // codes are compared without case, as 'en-gb' and 'en-GB' are the same language + private findLocale(localeId: string): SeoLocale | undefined { + return this.config.locales.find(locale => locale.code.toLowerCase() === localeId.toLowerCase()); + } + private writeStructuredData(structuredData: Record<string, unknown> | undefined): void { const previous: HTMLScriptElement | null = this.document.head.querySelector(`script[${STRUCTURED_DATA_ATTRIBUTE}]`); if (previous != undefined) { diff --git a/projects/ngx-persistence-logger/package.json b/projects/ngx-persistence-logger/package.json index 79606a1..0c20ac9 100644 --- a/projects/ngx-persistence-logger/package.json +++ b/projects/ngx-persistence-logger/package.json @@ -1,6 +1,6 @@ { "name": "@service-soft/ngx-persistence-logger", - "version": "22.2.0", + "version": "22.3.0", "license": "MIT", "repository": { "type": "git", @@ -22,7 +22,7 @@ "@angular/common": "^22.2.0", "@angular/core": "^22.2.0", "@fortawesome/free-solid-svg-icons": "^7.3.1", - "@service-soft/ui": "^22.2.0", + "@service-soft/ui": "^22.3.0", "tailwindcss": "^4.3.3", "zibri-contract": "^3.1.0" }, diff --git a/projects/ngx-pwa/package.json b/projects/ngx-pwa/package.json index e067062..812dc98 100644 --- a/projects/ngx-pwa/package.json +++ b/projects/ngx-pwa/package.json @@ -1,6 +1,6 @@ { "name": "@service-soft/ngx-pwa", - "version": "22.2.0", + "version": "22.3.0", "license": "MIT", "repository": { "type": "git", @@ -23,7 +23,7 @@ "@angular/core": "^22.2.0", "@angular/service-worker": "^22.2.0", "@fortawesome/free-solid-svg-icons": "^7.3.1", - "@service-soft/ui": "^22.2.0", + "@service-soft/ui": "^22.3.0", "tailwindcss": "^4.3.3" }, "peerDependenciesMeta": { diff --git a/projects/ngx-tracking/package.json b/projects/ngx-tracking/package.json index 7302058..03c70ae 100644 --- a/projects/ngx-tracking/package.json +++ b/projects/ngx-tracking/package.json @@ -1,6 +1,6 @@ { "name": "@service-soft/ngx-tracking", - "version": "22.2.0", + "version": "22.3.0", "license": "MIT", "repository": { "type": "git", @@ -23,7 +23,7 @@ "@angular/core": "^22.2.0", "@angular/router": "^22.2.0", "@fortawesome/free-solid-svg-icons": "^7.3.1", - "@service-soft/ui": "^22.2.0", + "@service-soft/ui": "^22.3.0", "tailwindcss": "^4.3.3" }, "peerDependenciesMeta": { diff --git a/projects/testing/error-handler/error-handler-testing.utilities.ts b/projects/testing/error-handler/error-handler-testing.utilities.ts new file mode 100644 index 0000000..850311b --- /dev/null +++ b/projects/testing/error-handler/error-handler-testing.utilities.ts @@ -0,0 +1,18 @@ +import { ErrorHandler, Provider } from '@angular/core'; + +/** + * Utilities for testing errors that an app reports to its error handler. + */ +export abstract class ErrorHandlerTestingUtilities { + /** + * Provides an error handler that adds every error the app reports to a list, in place of the default one of + * Angular, which logs them. A test that expects an error then logs nothing and can check what was reported. + * In a test, errors of change detection also still make fixture.whenStable() fail. + * @param errors - The list the errors are added to. + * @returns The provider, for the providers of TestBed.configureTestingModule. + */ + static provideErrorList(errors: unknown[]): Provider { + const errorHandler: ErrorHandler = { handleError: (error: unknown) => errors.push(error) }; + return { provide: ErrorHandler, useValue: errorHandler }; + } +} \ No newline at end of file diff --git a/projects/testing/error-handler/ng-package.json b/projects/testing/error-handler/ng-package.json new file mode 100644 index 0000000..70e0a80 --- /dev/null +++ b/projects/testing/error-handler/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} \ No newline at end of file diff --git a/projects/testing/error-handler/public-api.ts b/projects/testing/error-handler/public-api.ts new file mode 100644 index 0000000..55aea53 --- /dev/null +++ b/projects/testing/error-handler/public-api.ts @@ -0,0 +1 @@ +export * from './error-handler-testing.utilities'; \ No newline at end of file diff --git a/projects/testing/package.json b/projects/testing/package.json index c1f4564..5485a57 100644 --- a/projects/testing/package.json +++ b/projects/testing/package.json @@ -8,6 +8,7 @@ }, "peerDependencies": { "@angular/common": "^22.2.0", + "@angular/core": "^22.2.0", "@tailwindcss/postcss": "^4.3.3", "rxjs": "^7.8.0", "postcss": "^8.5.0", diff --git a/projects/ui/button/button.component.spec.ts b/projects/ui/button/button.component.spec.ts index 5acc37e..73fa00b 100644 --- a/projects/ui/button/button.component.spec.ts +++ b/projects/ui/button/button.component.spec.ts @@ -1,5 +1,6 @@ -import { Component, ErrorHandler } from '@angular/core'; +import { Component } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ErrorHandlerTestingUtilities } from 'testing/error-handler'; import { describe, expect, test } from 'vitest'; import { provideButtonConfig } from './button-config.provider'; @@ -136,7 +137,7 @@ describe('ButtonComponent', () => { test('reports an icon-only button without a name to the error handler', async () => { const errors: unknown[] = []; - TestBed.configureTestingModule({ providers: [{ provide: ErrorHandler, useValue: { handleError: (error: unknown) => errors.push(error) } }] }); + TestBed.configureTestingModule({ providers: [ErrorHandlerTestingUtilities.provideErrorList(errors)] }); await render(UnlabeledIconHostComponent); expect(errors).toEqual([new Error('An iconOnly ui-button needs an aria-label or aria-labelledby, it has no text that screen readers could read.')]); diff --git a/projects/ui/gallery/gallery.component.spec.ts b/projects/ui/gallery/gallery.component.spec.ts index b978096..f863789 100644 --- a/projects/ui/gallery/gallery.component.spec.ts +++ b/projects/ui/gallery/gallery.component.spec.ts @@ -1,5 +1,6 @@ -import { Component, ErrorHandler, signal, WritableSignal } from '@angular/core'; +import { Component, signal, WritableSignal } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ErrorHandlerTestingUtilities } from 'testing/error-handler'; import { beforeEach, describe, expect, test } from 'vitest'; import { provideGalleryConfig } from './gallery-config.provider'; @@ -114,7 +115,7 @@ describe('GalleryComponent', () => { test('reports a picture without an alt to the error handler', async () => { const errors: unknown[] = []; - TestBed.configureTestingModule({ providers: [{ provide: ErrorHandler, useValue: { handleError: (error: unknown) => errors.push(error) } }] }); + TestBed.configureTestingModule({ providers: [ErrorHandlerTestingUtilities.provideErrorList(errors)] }); const [fixture] = await render(); fixture.componentInstance.images.set([{ src: '/photos/stage.jpg', alt: ' ' }]); await fixture.whenStable(); diff --git a/projects/ui/iframe/iframe.component.spec.ts b/projects/ui/iframe/iframe.component.spec.ts index ac1baeb..c217d40 100644 --- a/projects/ui/iframe/iframe.component.spec.ts +++ b/projects/ui/iframe/iframe.component.spec.ts @@ -1,5 +1,6 @@ -import { Component, ErrorHandler, signal, WritableSignal } from '@angular/core'; +import { Component, signal, WritableSignal } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ErrorHandlerTestingUtilities } from 'testing/error-handler'; import { describe, expect, test } from 'vitest'; import { IframeComponent } from './iframe.component'; @@ -39,7 +40,7 @@ describe('IframeComponent', () => { test('refuses a url that would run script in the page', async () => { const errors: unknown[] = []; - TestBed.configureTestingModule({ providers: [{ provide: ErrorHandler, useValue: { handleError: (error: unknown) => errors.push(error) } }] }); + TestBed.configureTestingModule({ providers: [ErrorHandlerTestingUtilities.provideErrorList(errors)] }); const [fixture, iframe] = await render(); fixture.componentInstance.src.set('javascript:alert(1)'); await fixture.whenStable().catch((error: unknown) => errors.push(error)); diff --git a/projects/ui/package.json b/projects/ui/package.json index 438c005..ceda394 100644 --- a/projects/ui/package.json +++ b/projects/ui/package.json @@ -1,6 +1,6 @@ { "name": "@service-soft/ui", - "version": "22.2.0", + "version": "22.3.0", "license": "MIT", "repository": { "type": "git",