Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
19cb032
feat(portal): load the script addresses listed in portal.scripts
Nov 16, 2026
2580c4e
feat(portal): load script files from src/static through portal.scripts
Nov 16, 2026
bf320b4
feat(portal): leave analytics and marketing scripts out under --no-an…
Nov 16, 2026
7849475
feat(portal): let scripts subscribe to portal events through window.a…
Nov 16, 2026
cea1bc0
feat(portal): describe portal.scripts in the schema
Nov 16, 2026
6782e26
test(portal): prove listed scripts in a built portal
Nov 16, 2026
a0c6d99
test(portal): keep the build test's fixture script clean under the li…
Nov 16, 2026
5f22073
fix(portal): give scripts subscribe alone at window.apimatic.analytics
Nov 17, 2026
88fe45d
refactor(portal): make the event feed's delivery a static helper
Nov 17, 2026
8d11751
refactor(portal): read the head's scripts once for each insert
Nov 17, 2026
6ed31b3
refactor(portal): loop over the feed's subscribers without copying them
Nov 17, 2026
310f38a
chore: merge dev into sohail/portal-scripts
Nov 17, 2026
d9058be
fix(portal): call a subscriber on its own, not on the feed's record
Nov 17, 2026
ddbad82
fix(portal): hold the feed under a symbol, not a named global
Nov 17, 2026
78505ad
fix(portal): insert a script once, even after it leaves the page
Nov 17, 2026
97946a2
fix(portal): start on a page that made window.apimatic read-only
Nov 17, 2026
bc7ec36
fix(portal): refuse an https address with no host, as the schema does
Nov 17, 2026
e50ac0a
refactor(portal): list a script's static files, not one or null
Nov 17, 2026
5f1d49d
docs(portal): say --no-analytics drops scripts with no category
Nov 17, 2026
07ee1f4
refactor(portal): let names say what two comments restated
Nov 17, 2026
3df7c3d
docs(portal): say in the schema that scripts stay off the OAuth callback
Nov 17, 2026
17ddf35
fix(portal): hand no event to the scripts --no-analytics keeps
Nov 17, 2026
1547e42
feat(portal): queue Consent Mode defaults ahead of the Google tags
Nov 17, 2026
440f0b2
feat(portal): describe portal.analytics.googleConsentMode in the schema
Nov 17, 2026
94c5897
test(portal): prove the Consent Mode defaults in a built portal
Nov 17, 2026
be9556c
fix(portal): keep the reader's language in GA4 by renaming the event key
Nov 18, 2026
5ad3cfe
fix(portal): name the search event's picked result picked_result
Nov 18, 2026
367cf0b
fix(portal): ask for a category on every listed script
Nov 18, 2026
95780b1
refactor(portal): name the analytics state a window shares after the …
Nov 18, 2026
37db2b4
fix(portal): read the window's analytics state once, in start()
Nov 18, 2026
9a6e19b
fix(portal): take window.gtag for a gtag only when it is a function
Nov 18, 2026
7b49143
test(portal): make the consent mode's build check able to fail
Nov 18, 2026
a895b2c
fix(portal): keep the consent default in a build made with --no-analy…
Nov 18, 2026
eb200e9
docs(portal): say in the schema what googleConsentMode does not cover
Nov 18, 2026
a3a04d3
fix(portal): load no second copy of a script the host already injects
Nov 18, 2026
f751809
fix(portal): add analytics to a host's own window.apimatic object
Nov 18, 2026
ae99bcc
fix(portal): refuse a backslash where an https address has its host
Nov 18, 2026
37dcd1b
refactor(portal): set window.gtag before returning it
Nov 18, 2026
b9450b7
fix(portal): write no event to the data layer in a build made with --…
Nov 18, 2026
6792fa8
refactor(portal): name the identity's event switch events, not eventFeed
Nov 18, 2026
3fc4fdd
docs(ai): weigh a function's boilerplate against its body in characters
mrafnadeem-apimatic Nov 18, 2026
15aaf82
docs(portal): name the sign-in token in the schema's description of s…
Nov 19, 2026
144c6b7
docs(portal): say in plain words that Consent Mode leaves listed scri…
Nov 19, 2026
482418b
docs(portal): define each script category in the schema
Nov 19, 2026
665c8ef
refactor(portal): inline three helpers whose boilerplate outweighs th…
Nov 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .ai/instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ Supporting: **Types** (`src/types/`) for value objects, context objects, and dom
- **No private instance methods** — a class has `private readonly` fields and public methods; a helper is a `private static` method or a module-level function.
- **No middlemen** — a method does something with each argument (reads it, transforms it, or combines it with the object's own state); no method only forwards to another call, and no layer re-exposes a service one to one.
- **Functional core, imperative shell** — a step reads every fact it needs first, decides as a pure function over that data, then does its I/O. `execute` is the script of the run and the only place that speaks; prompts word the data they are handed and decide nothing; a value with several outcomes (`ShareHook`, `SnapshotFetch`, `ActionResult`) offers `match` over named handlers, so a caller that leaves one out fails to compile; contexts answer data and never print.
- **Good code is not more functions** — a step's logic stays together where it reads as one thing; a function is split out only when it is used twice, when it separates a decision from I/O, or when its name says something the reader would otherwise work out. A one-line call does not get a wrapper.
- **Good code is not more functions** — a step's logic stays together where it reads as one thing; a function is split out only when it is used twice, when it separates a decision from I/O, or when its name says something the reader would otherwise work out. Even then, a function or method whose boilerplate (its doc comment, signature and closing brace) has more characters than its body is an unnecessary abstraction, such as a wrapper around a one-line call: inline it.
- **One prompts class per action** — wording is repeated per class rather than shared through a prompt module.
- **Flag descriptions match the docs** — a flag's `description` (which the generated README carries) and its row in apimatic-docs' CLI Reference (`v4/src/content/apimatic-cli/cli-reference.mdx`) say the same words; change both, or flag the mismatch.
- **Telemetry** — After `outro(result)`, commands optionally track failures via `result.match({ success: () => {}, failed: async () => { await new TelemetryService(configDir).trackEvent(new SomeFailedEvent(...), shell) }, cancelled: () => {}, actionRequired: () => {} })`. Event classes extend `DomainEvent` (`src/types/events/`). Only the `failed` handler is populated; the others are no-ops.
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,8 @@ FLAGS
-i, --input=<value> [default: ./] path to the parent directory containing the 'src' directory, which includes
API specifications and configuration files.
-k, --auth-key=<value> override current authentication state with an authentication key.
--no-analytics leave out the Google Tag Manager and Google Analytics tags set in 'portal.analytics'.
--no-analytics leave out the tags set in 'portal.analytics' and each script in 'portal.scripts' whose
category is 'analytics' or 'marketing', and hand no event to the scripts that stay.
--zip write the generated portal as a .zip archive.

DESCRIPTION
Expand Down Expand Up @@ -347,7 +348,8 @@ FLAGS
-k, --auth-key=<value> override current authentication state with an authentication key.
-o, --open open the portal in the default browser.
-p, --port=23513 [default: 23513] port to serve the portal on.
--no-analytics leave out the Google Tag Manager and Google Analytics tags set in 'portal.analytics'.
--no-analytics leave out the tags set in 'portal.analytics' and each script in 'portal.scripts' whose
category is 'analytics' or 'marketing', and hand no event to the scripts that stay.

DESCRIPTION
Preview your API Documentation Portal with live reload.
Expand Down
54 changes: 51 additions & 3 deletions apimatic.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@
"description": "A path relative to 'src' inside the 'static' directory, for example 'static/images/logo.png'.",
"pattern": "^\\s*(?:\\.[\\\\/])?static(?:[\\\\/](?!\\.{1,2}(?:[\\\\/]|\\s*$))[^\\\\/]*[^\\\\/\\s][^\\\\/]*)+\\s*$"
},
"httpsAddress": {
"type": "string",
"description": "An address starting with 'https://' and a host, with no spaces.",
"pattern": "^[hH][tT][tT][pP][sS]://[^\\s/\\\\?#]+(?:[/?#]\\S*)?$"
},
"color": {
"type": "string",
"description": "#rgb or #rrggbb, for example '#1d4ed8'.",
Expand Down Expand Up @@ -226,6 +231,19 @@
}
}
},
"googleConsentMode": {
"type": "object",
"description": "Starts Google's own tags in Google's Consent Mode: they load at once, set no cookies and mark every hit as denied until your consent tool calls gtag('consent', 'update'). Other vendors' tags inside a Google Tag Manager container need consent checks of their own there. Set it when a consent banner decides what is tracked. It does not affect which scripts in 'portal.scripts' are loaded, or when.",
"additionalProperties": false,
"required": ["default"],
"properties": {
"default": {
"type": "string",
"enum": ["denied"],
"description": "What the tags take a reader's answer to be until your consent tool gives one."
}
}
},
"keepQueryParams": {
"type": "array",
"description": "Your own link tags to keep in reported page addresses. Campaign (utm_), ad-click and cross-domain tags are kept already; every other query parameter is dropped.",
Expand All @@ -250,10 +268,40 @@
}
}
},
"scripts": {
"type": "array",
"description": "Other vendors' scripts and widgets, loaded on every page in the listed order, except the OAuth callback page. They get the portal's events from window.apimatic.analytics.subscribe(). Any listed script can read what readers type into the API playground, and the token an OAuth 2.0 sign-in leaves in the browser's session storage, so list only vendors you trust.",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["src", "category"],
"properties": {
"src": {
"description": "An address starting with 'https://' and a host, with no spaces, or a file in the 'static' directory, for example 'static/analytics.js'.",
"anyOf": [
{
"$ref": "#/definitions/httpsAddress"
},
{
"$ref": "#/definitions/staticPath"
}
]
},
"category": {
"type": "string",
"description": "What the script is for, in the four groups consent tools ask readers about. 'necessary': the portal needs it to work, or the law requires it, such as your consent tool. 'functional': a feature a reader sees or uses, which may remember their choices, such as a chat widget, a feedback form or a status banner. 'analytics': it measures how readers use the portal, such as an analytics tool, a session recorder or an A/B testing tool. 'marketing': it serves or measures advertising, or follows readers across sites, such as an ad pixel. A script that does more than one takes the last of these that applies, so a feedback widget that also records sessions is 'analytics'. --no-analytics leaves out the 'analytics' and 'marketing' scripts.",
"enum": ["necessary", "functional", "analytics", "marketing"]
}
}
}
},
"pluginUrl": {
"type": "string",
"description": "Where the context plugin is hosted, starting with 'https://' and with no spaces. The Context Plugin page installs it from here, and the portal carries no copy of its own.",
"pattern": "^[hH][tT][tT][pP][sS]://[^\\s/?#]+(?:[/?#]\\S*)?$"
"allOf": [
{
"$ref": "#/definitions/httpsAddress"
}
],
"description": "Where the context plugin is hosted, starting with 'https://' and with no spaces. The Context Plugin page installs it from here, and the portal carries no copy of its own."
}
}
},
Expand Down
2 changes: 1 addition & 1 deletion portal-template/src/components/code-copy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { analytics } from '@/lib/portal-analytics';
type Actions = NonNullable<BlockProps['Actions']>;

export const reportCodeCopy = (language: string) =>
analytics.report('docs_code_copy', { language: languageId(language) });
analytics.report('docs_code_copy', { code_language: languageId(language) });

// Fumadocs' own, which any Actions a block is given replaces.
const DefaultActions: Actions = ({ className, children }) => (
Expand Down
2 changes: 1 addition & 1 deletion portal-template/src/components/sdk-actions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export function DownloadLink({ href, className, language, children }: Readonly<D
href={withBasePath(href)}
download
className={className}
onClick={() => analytics.report('docs_sdk_download', { language: languageId(language) })}
onClick={() => analytics.report('docs_sdk_download', { sdk_language: languageId(language) })}
>
{children}
</a>
Expand Down
80 changes: 63 additions & 17 deletions portal-template/src/lib/analytics.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { EventFeed } from './event-feed';
import { isOAuthCallbackPath } from './oauth-callback';
import type { PortalAnalytics } from './portal-types';
import { type Adapter, adapters, insertTags } from './vendor-tags';
import type { PortalAnalytics, PortalScript } from './portal-types';
import { type Adapter, adapters, insertTags, queueConsentDefaults } from './vendor-tags';

/** The query parameters an ad or mail platform reads from an address itself; a customer adds names and removes none. */
const KEPT_PREFIXES = ['utm_', 'hsa_'];
Expand All @@ -26,9 +27,10 @@ export interface PortalEvents {
docs_page_view: { page_title: string };
docs_markdown_copy: Record<string, never>;
docs_plugin_install: Record<string, never>;
docs_sdk_download: { language: string };
docs_code_copy: { language: string };
docs_search: { search_term: string; result: string; result_count: number };
// Neither is named `language`: gtag takes that name on an event for the reader's own language.
docs_sdk_download: { sdk_language: string };
docs_code_copy: { code_language: string };
docs_search: { search_term: string; picked_result: string; result_count: number };
docs_not_found: { page_referrer: string };
/** `status` is always text: the HTTP status in digits, or `client_error` for a request that never reached the API. */
docs_api_request: { endpoint: string; status: string; duration_ms: number };
Expand All @@ -37,11 +39,27 @@ export type PortalEventName = keyof PortalEvents;

type DataLayerEntry = { docs: null } | { event: PortalEventName; docs: Readonly<Record<string, string | number>> };

/** A symbol, so the window holds it under no name a script comes across and builds on. */
const WINDOW_ANALYTICS = Symbol.for('apimatic.portal.analytics');

/**
* One per `Window` object (https://developer.mozilla.org/en-US/docs/Web/API/Window), which a reload replaces.
* Every instance in it shares this one: a config save under `portal serve` makes a second.
*/
interface WindowAnalytics {
/** The settings and scripts the window started with. */
started: string;
feed: EventFeed;
/** The address of every script the head held at the start, and of each tag and script inserted since. */
inserted: Set<string>;
}

declare global {
interface Window {
dataLayer?: unknown[];
/** Held by the window: a config save under `portal serve` evaluates this module again. */
portalAnalyticsStarted?: string;
[WINDOW_ANALYTICS]?: WindowAnalytics;
/** What customers' scripts are given: `subscribe()` and nothing else. */
apimatic?: { analytics?: Pick<EventFeed, 'subscribe'> };
}
}

Expand All @@ -59,45 +77,73 @@ export function pageLocation(href: string, keep: readonly string[]): string {

export class Analytics {
private readonly live: Adapter[];
/** The window's, once `start()` has made it or joined it: no other method reads the global. */
private windowAnalytics: WindowAnalytics | undefined;
private lastPageView: string | null = null;
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.
if (window.portalAnalyticsStarted !== undefined) {
window.location.reload();
const started = JSON.stringify([this.settings, this.scripts]);
const existing = window[WINDOW_ANALYTICS];
if (existing !== undefined) {
// Other vendors or scripts after a config save: only a fresh window holds exactly their tags.
if (existing.started === started) this.windowAnalytics = existing;
else window.location.reload();
return;
}
window.portalAnalyticsStarted = settings;
const feed = new EventFeed();
// Each script the head holds already, by its src as written: a host may inject one of the portal's itself.
const head = document.head.querySelectorAll('script[src]');
const inserted = new Set(Array.from(head, (script) => script.getAttribute('src') ?? ''));
this.windowAnalytics = { started, feed, inserted };
window[WINDOW_ANALYTICS] = this.windowAnalytics;
const dataLayer = (window.dataLayer ??= []);
if (this.settings.googleConsentMode !== null) queueConsentDefaults(dataLayer);
for (const adapter of this.live) adapter.setup(dataLayer);
insertTags(this.live);
// Ours whatever the window held there first, and `subscribe` alone, bound so a script may call it on its own.
const analytics = Object.freeze({ subscribe: feed.subscribe.bind(feed) });
try {
// On the host's own object if it takes one: a copy lacks its class's methods and is not the object it holds.
// A frozen object takes none, nor one that fixed the name.
const host: unknown = window.apimatic;
const property = { value: analytics, writable: true, enumerable: true, configurable: true };
const taken = Object(host) === host && Reflect.defineProperty(host as object, 'analytics', property);
if (!taken) window.apimatic = { ...window.apimatic, analytics };
} catch (error) {
// A host may have locked the name. Thrown later, so it shows in the console and the bundle goes on loading.
setTimeout(() => {
throw error;
});
}
insertTags(this.live, this.scripts, inserted);
}

/** `href` is the page the event belongs to, when the caller saw the address move on first. */
public report<E extends PortalEventName>(name: E, params: PortalEvents[E], href = window.location.href): void {
// A `--no-analytics` build reports nothing, even to the data layer: a container a kept script loads reads it.
if (this.settings.events === 'off') return;
if (isOAuthCallbackPath(new URL(href).pathname)) return;
const docs = { ...params, page_location: pageLocation(href, this.settings.keepQueryParams) };
const dataLayer = (window.dataLayer ??= []);
// GTM merges every push into what it holds, so a tag would send the last event's details without this.
dataLayer.push({ docs: null } satisfies DataLayerEntry);
dataLayer.push({ event: name, docs } satisfies DataLayerEntry);
for (const adapter of this.live) adapter.send?.(name, docs);
this.windowAnalytics?.feed.publish(name, docs);
}

public reportPageView(): void {
if (isOAuthCallbackPath(window.location.pathname)) return;
// The tags a start on the OAuth callback left out, now that the reader has moved on from it.
insertTags(this.live);
const inserted = this.windowAnalytics?.inserted;
// The tags and scripts a start on the OAuth callback left out, now that the reader has moved on from it.
if (inserted !== undefined) insertTags(this.live, this.scripts, inserted);
const page = pageLocation(window.location.href, this.settings.keepQueryParams);
if (page === this.lastPageView) return;
this.previousPageView = this.lastPageView;
Expand Down
60 changes: 60 additions & 0 deletions portal-template/src/lib/event-feed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/** One portal event as a subscriber receives it. Customers' scripts read these keys, so `version` moves if one ever changes. */
export interface PortalEvent {
readonly name: string;
/** The event's details, with `page_location` among them. */
readonly params: Readonly<Record<string, string | number>>;
/** When it was reported, in milliseconds since the epoch. */
readonly time: number;
readonly version: 1;
}

type Subscriber = (event: PortalEvent) => void;
type Unsubscribe = () => void;

interface Subscription {
callback: Subscriber;
deliveredCount: number;
}

/** A window's events, for the scripts in it: a subscriber gets every one reported so far, then each new one. */
export class EventFeed {
private readonly events: PortalEvent[] = [];
private readonly subscriptions = new Set<Subscription>();

public subscribe(callback: Subscriber): Unsubscribe {
if (typeof callback !== 'function') {
throw new TypeError('window.apimatic.analytics.subscribe() takes a function.');
}
const subscription: Subscription = { callback, deliveredCount: 0 };
this.subscriptions.add(subscription);
// Once this has returned, so a callback can call the function it returns, even for an earlier event.
queueMicrotask(() => EventFeed.deliver(this, subscription));
return () => {
this.subscriptions.delete(subscription);
};
}

public publish(name: string, params: Record<string, string | number>): void {
// A copy, frozen, so no subscriber changes what the next one gets, or what the data layer was handed.
this.events.push(Object.freeze({ name, params: Object.freeze({ ...params }), time: Date.now(), version: 1 }));
// The set itself: one a callback adds is reached in this same pass, and one it removes is skipped.
for (const subscription of this.subscriptions) EventFeed.deliver(this, subscription);
}

private static deliver(feed: EventFeed, subscription: Subscription): void {
// Called on its own, so a callback written without strict mode finds the window as `this`, never this record.
const { callback } = subscription;
while (feed.subscriptions.has(subscription) && subscription.deliveredCount < feed.events.length) {
const event = feed.events[subscription.deliveredCount];
subscription.deliveredCount += 1;
try {
callback(event);
} catch (error) {
// Thrown later, so it shows in the console and stops neither the next event nor the next subscriber.
setTimeout(() => {
throw error;
});
}
}
}
}
2 changes: 1 addition & 1 deletion portal-template/src/lib/portal-analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Loading
Loading