From 19cb032a84b1a327d93e99208da5afd29d18c009 Mon Sep 17 00:00:00 2001 From: Muhammad Sohail Date: Mon, 16 Nov 2026 16:34:40 +0500 Subject: [PATCH 01/40] feat(portal): load the script addresses listed in portal.scripts Each entry is { src }, an https address. The loader inserts them after the vendor tags, in list order and not async, under the same hold on an OAuth answer. The key a start runs once by covers the list, so a config save under portal serve reloads with exactly the new one. An inserted tag is now found by its src attribute as written: a selector built from a customer's address misses on a backslash, and the script would be inserted again on every page view. Co-Authored-By: Claude Fable 5.2 --- portal-template/src/lib/analytics.ts | 16 +- portal-template/src/lib/portal-analytics.ts | 2 +- portal-template/src/lib/portal-types.ts | 6 + portal-template/src/lib/vendor-tags.ts | 17 +- src/types/portal/config/fields.ts | 10 ++ src/types/portal/config/script.ts | 45 +++++ src/types/portal/portal-config.ts | 34 ++-- .../portal-project-service.test.ts | 13 ++ test/portal-template/analytics.test.ts | 159 +++++++++++++----- test/types/portal/portal-config.test.ts | 87 +++++++++- 10 files changed, 315 insertions(+), 74 deletions(-) create mode 100644 src/types/portal/config/script.ts diff --git a/portal-template/src/lib/analytics.ts b/portal-template/src/lib/analytics.ts index 10e59cff..2cd81970 100644 --- a/portal-template/src/lib/analytics.ts +++ b/portal-template/src/lib/analytics.ts @@ -1,5 +1,5 @@ import { isOAuthCallbackPath } from './oauth-callback'; -import type { PortalAnalytics } from './portal-types'; +import type { PortalAnalytics, PortalScript } from './portal-types'; import { type Adapter, adapters, insertTags } from './vendor-tags'; /** The query parameters an ad or mail platform reads from an address itself; a customer adds names and removes none. */ @@ -63,29 +63,29 @@ export class Analytics { private previousPageView: string | null = null; private lastNotFound: string | null = null; - public constructor(private readonly settings: PortalAnalytics) { + public constructor(private readonly settings: PortalAnalytics, private readonly scripts: PortalScript[]) { this.live = Object.values(adapters) .map((build) => build(settings)) .filter((adapter) => adapter !== null); } public start(): void { - const settings = JSON.stringify(this.settings); - if (window.portalAnalyticsStarted === settings) return; - // Other vendors after a config save: only a fresh page holds exactly their tags. + const started = JSON.stringify([this.settings, this.scripts]); + if (window.portalAnalyticsStarted === started) return; + // Other vendors or scripts after a config save: only a fresh page holds exactly their tags. if (window.portalAnalyticsStarted !== undefined) { window.location.reload(); return; } - window.portalAnalyticsStarted = settings; + window.portalAnalyticsStarted = started; const dataLayer = (window.dataLayer ??= []); for (const adapter of this.live) adapter.setup(dataLayer); - insertTags(this.live); + insertTags(this.live, this.scripts); } /** The tags held back while the address held an OAuth answer, once something has taken it out. */ public loadTags(): void { - insertTags(this.live); + insertTags(this.live, this.scripts); } /** `href` is the page the event belongs to, when the caller saw the address move on first. */ diff --git a/portal-template/src/lib/portal-analytics.ts b/portal-template/src/lib/portal-analytics.ts index d23527eb..83f6aebb 100644 --- a/portal-template/src/lib/portal-analytics.ts +++ b/portal-template/src/lib/portal-analytics.ts @@ -2,7 +2,7 @@ import { Analytics } from './analytics'; import { portal } from './portal'; import { markPlaygroundDialogs } from './replay-markers'; -export const analytics = new Analytics(portal.analytics); +export const analytics = new Analytics(portal.analytics, portal.scripts); // When the bundle starts, before React and before any vendor tag. Never during prerendering. if (typeof window !== 'undefined') { markPlaygroundDialogs(); diff --git a/portal-template/src/lib/portal-types.ts b/portal-template/src/lib/portal-types.ts index cbc8cc0e..7ff1fbde 100644 --- a/portal-template/src/lib/portal-types.ts +++ b/portal-template/src/lib/portal-types.ts @@ -48,6 +48,10 @@ export interface PortalSeo { googleSiteVerification: string | null; } +export interface PortalScript { + src: string; +} + export interface Portal { name: string; description: string | null; @@ -61,4 +65,6 @@ export interface Portal { pageActions: boolean; analytics: PortalAnalytics; seo: PortalSeo; + /** In the order the block lists them, which is the order the browser runs them in. */ + scripts: PortalScript[]; } diff --git a/portal-template/src/lib/vendor-tags.ts b/portal-template/src/lib/vendor-tags.ts index 76f7922e..cbf67770 100644 --- a/portal-template/src/lib/vendor-tags.ts +++ b/portal-template/src/lib/vendor-tags.ts @@ -1,5 +1,5 @@ import { holdsOAuthAnswer } from './oauth-callback'; -import type { PortalAnalytics } from './portal-types'; +import type { PortalAnalytics, PortalScript } from './portal-types'; type Gtag = (...command: unknown[]) => void; @@ -55,12 +55,19 @@ export const adapters: { [V in Vendor]: (settings: PortalAnalytics) => Adapter | }; /** None while the address holds an OAuth answer, which the tags read for themselves; each once, so a later call adds the rest. */ -export function insertTags(live: Adapter[]): void { +export function insertTags(live: Adapter[], scripts: PortalScript[]): void { if (holdsOAuthAnswer(window.location)) return; - for (const { script: src } of live) { - if (document.head.querySelector(`script[src="${src}"]`) !== null) continue; + // A listed script is not async, so the browser runs them in the order listed, whichever arrives first. + const wanted = [ + ...live.map(({ script: src }) => ({ src, async: true })), + ...scripts.map(({ src }) => ({ src, async: false })) + ]; + for (const { src, async } of wanted) { + // Compared as written, since a selector built from a customer's address breaks on a backslash. + const inserted = Array.from(document.head.querySelectorAll('script'), (script) => script.getAttribute('src')); + if (inserted.includes(src)) continue; const script = document.createElement('script'); - script.async = true; + script.async = async; script.src = src; document.head.append(script); } diff --git a/src/types/portal/config/fields.ts b/src/types/portal/config/fields.ts index ef581704..01f86cb0 100644 --- a/src/types/portal/config/fields.ts +++ b/src/types/portal/config/fields.ts @@ -104,3 +104,13 @@ export function nonEmptyString(value: unknown, path: string): Parsed { ? ok(value.trim()) : err([`'${path}' must be a non-empty string.`]); } + +const HTTPS_ADDRESS = /^https:\/\/\S+$/i; + +// https, since what it names is fetched and run; parsed, so it holds no space or quote wherever it is written out. +export function httpsAddress(value: unknown, path: string, example: string): Parsed { + const url = typeof value === 'string' && HTTPS_ADDRESS.test(value) ? UrlPath.create(value) : undefined; + return url === undefined + ? err([`'${path}' must be an address starting with 'https://', with no spaces, for example '${example}'.`]) + : ok(new UrlPath(new URL(`${url}`).href)); +} diff --git a/src/types/portal/config/script.ts b/src/types/portal/config/script.ts new file mode 100644 index 00000000..ea7e96f0 --- /dev/null +++ b/src/types/portal/config/script.ts @@ -0,0 +1,45 @@ +import { err, ok, Result } from 'neverthrow'; +import { isJsonObject } from '../../../utils/json-utils.js'; +import { UrlPath } from '../../file/urlPath.js'; +import { allOf, httpsAddress, Parsed, required, unknownKeys } from './fields.js'; + +const KNOWN = ['src']; + +const EXAMPLE = 'https://cdn.example.com/widget.js'; + +export interface PortalScript { + src: string; +} + +/** A script of the customer's own, which the portal loads on every page. */ +export class Script { + private constructor(private readonly address: UrlPath) {} + + public static parseList(value: unknown, path: string): Parsed { + if (value === undefined) { + return ok([]); + } + if (!Array.isArray(value)) { + return err([`'${path}' must be a list of scripts.`]); + } + return Result.combineWithAllErrors(value.map((script, index) => Script.parse(script, `${path}[${index}]`))).mapErr( + (errors) => errors.flat() + ); + } + + public identity(): PortalScript { + return { src: this.address.toString() }; + } + + private static parse(value: unknown, path: string): Parsed