import { URL } from 'node:url' export const BROWSER_TOPICS = [ { slug: 'setup', title: 'Setup', description: 'Initialize, configure, debug, and shut down the SDK', capabilities: ['setup', 'shutdown', 'debug'], }, { slug: 'events', title: 'Events and properties', description: 'Capture custom events, AI events, logs, and super properties', capabilities: ['capture', 'capture-ai', 'logs', 'register', 'unregister'], }, { slug: 'identity', title: 'Identity and groups', description: 'Identify users, set person properties, reset sessions, and group analytics', capabilities: [ 'identify', 'alias', 'reset', 'get-distinct-id', 'set-person-properties', 'create-person-profile', 'group', 'group-identify', ], }, { slug: 'feature-flags', title: 'Feature flags', description: 'Evaluate flags, payloads, callbacks, and flag override properties', capabilities: [ 'get-feature-flag', 'get-feature-flag-payload', 'get-feature-flag-result', 'get-feature-flags', 'is-feature-enabled', 'on-feature-flags', 'reload-feature-flags', 'set-person-properties-for-flags', 'reset-person-properties-for-flags', 'set-group-properties-for-flags', 'reset-group-properties-for-flags', ], }, { slug: 'session-replay', title: 'Session replay', description: 'Start, stop, and inspect session recording and session IDs', capabilities: [ 'start-session-recording', 'stop-session-recording', 'is-session-replay-active', 'get-session-id', ], }, { slug: 'error-tracking', title: 'Error tracking', description: 'Capture exceptions, control autocapture, and record exception steps', capabilities: ['capture-exception', 'exception-steps'], }, { slug: 'surveys', title: 'Surveys', description: 'Fetch, match, render, and manage in-app surveys', capabilities: ['surveys'], }, { slug: 'privacy', title: 'Privacy and consent', description: 'Opt in, opt out, and query explicit consent state', capabilities: ['opt-in', 'is-opt-out', 'consent-gating'], }, ] const INDEX_START = '' const INDEX_END = '' const ALLOWED_EXACT_HOSTS = new Set(['posthog.com', 'example.com', 'localhost', '127.0.0.1']) const ALLOWED_HOST_SUFFIXES = ['.posthog.com', '.example.com'] const SKILL_URL_SOURCE = String.raw`https?:\/\/[a-z0-9][^\s)\]<>"'` + '`' + String.raw`]*|(?<=^|[\s([<"'` + '`' + String.raw`])\/\/[a-z0-9.-]+\.[a-z]{2,}[^\s)\]<>"'` + '`' + String.raw`]*` const SKILL_URL_RE = new RegExp(`(?:${SKILL_URL_SOURCE})`, 'gi') const BARE_SKILL_URL_RE = new RegExp(String.raw`(\bSee\s+)?(?:${SKILL_URL_SOURCE})`, 'gi') const FENCE_OPEN_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/ const FENCE_CLOSE_RE = /^ {0,3}(`{3,}|~{3,})\s*$/ export const BROWSER_MEMBER_ORDER = { setup: ['PostHog.init', 'PostHog.set_config', 'PostHog.debug', 'PostHog.shutdown', 'posthog', 'new PostHog(...)'], events: [ 'PostHog.capture', 'PostHog.register', 'PostHog.register_once', 'PostHog.register_for_session', 'PostHog.unregister', 'PostHog.unregister_for_session', 'PostHog.get_property', 'PostHog.getSessionProperty', 'PostHog.logger', 'PostHog.captureLog', 'PostHog.captureTraceFeedback', 'PostHog.captureTraceMetric', ], identity: [ 'PostHog.identify', 'PostHog.reset', 'PostHog.setPersonProperties', 'PostHog.unsetPersonProperties', 'PostHog.createPersonProfile', 'PostHog.get_distinct_id', 'PostHog.alias', 'PostHog.group', 'PostHog.getGroups', 'PostHog.resetGroups', 'PostHog.setInternalOrTestUser', 'PostHog.setIdentity', 'PostHog.clearIdentity', ], 'feature-flags': [ 'PostHog.isFeatureEnabled', 'PostHog.getFeatureFlag', 'PostHog.getFeatureFlagResult', 'PostHog.getAllFeatureFlags', 'PostHog.onFeatureFlags', 'PostHog.reloadFeatureFlags', 'PostHog.setPersonPropertiesForFlags', 'PostHog.resetPersonPropertiesForFlags', 'PostHog.setGroupPropertiesForFlags', 'PostHog.resetGroupPropertiesForFlags', 'PostHog.updateFlags', ], 'session-replay': [ 'PostHog.startSessionRecording', 'PostHog.stopSessionRecording', 'PostHog.sessionRecordingStarted', 'PostHog.get_session_replay_url', 'PostHog.get_session_id', 'PostHog.onSessionId', ], 'error-tracking': [ 'PostHog.captureException', 'PostHog.startExceptionAutocapture', 'PostHog.stopExceptionAutocapture', 'PostHog.addExceptionStep', ], surveys: [ 'PostHog.displaySurvey', 'PostHog.getActiveMatchingSurveys', 'PostHog.getSurveys', 'PostHog.onSurveysLoaded', 'PostHog.onActiveMatchingSurveysChanged', 'PostHog.canRenderSurveyAsync', 'PostHog.cancelPendingSurvey', ], privacy: [ 'PostHog.opt_in_capturing', 'PostHog.opt_out_capturing', 'PostHog.has_opted_in_capturing', 'PostHog.has_opted_out_capturing', 'PostHog.is_capturing', 'PostHog.get_explicit_consent_status', 'PostHog.clear_opt_in_out_capturing', ], utils: [ 'sampleByDistinctId', 'sampleBySessionId', 'sampleByEvent', 'PostHog.on', 'PostHog.getEarlyAccessFeatures', 'PostHog.updateEarlyAccessFeatureEnrollment', 'PostHog.loadToolbar', 'PostHog.getPageViewId', 'PostHog.flagsEndpointWasHit', 'PostHog.version', ], } export function sortItemsByOrder(items, order = []) { return [...items].sort((a, b) => { const ai = order.indexOf(a.label) const bi = order.indexOf(b.label) if (ai !== -1 && bi !== -1) return ai - bi if (ai !== -1) return -1 if (bi !== -1) return 1 return a.label.localeCompare(b.label) }) } const headingSlug = (heading) => heading .toLowerCase() .replace(/[^a-z0-9 _-]/g, '') .split(' ') .join('-') /** * Groups rendered sdk-specs capability entries into higher-level topic pages. * Throws if any mapped capability isn't declared in `topicSpecs`, preventing silent unlisted pages that posthog.com wouldn't route. */ export function groupCapabilitiesIntoTopics(capabilityEntries, utilsEntry, topicSpecs = BROWSER_TOPICS) { const bySlug = new Map(capabilityEntries.map((entry) => [entry.slug, entry])) const assigned = new Set() const topics = [] const topicSlugs = new Set(topicSpecs.map((s) => headingSlug(s.title))) topicSlugs.add('sdk-utils') const buildMemberSections = (memberItems, order) => { const sorted = sortItemsByOrder(memberItems, order) const emittedAnchors = new Set() return sorted.flatMap((item) => { const ids = (item.anchors ?? []).filter((id) => !topicSlugs.has(id) && !emittedAnchors.has(id)) ids.forEach((id) => emittedAnchors.add(id)) return ids.length ? [`${ids.map((id) => ``).join('')}\n\n${item.rendered}`] : [item.rendered] }) } for (const spec of topicSpecs) { const rawSections = [] const labels = [] const signatures = [] const memberItems = [] for (const slug of spec.capabilities) { const entry = bySlug.get(slug) if (!entry) continue assigned.add(slug) rawSections.push(...entry.sections) labels.push(...entry.labels) signatures.push(...(entry.signatures ?? entry.labels)) if (entry.memberItems) memberItems.push(...entry.memberItems) } if (rawSections.length > 0 || memberItems.length > 0) { const order = BROWSER_MEMBER_ORDER[spec.slug] ?? [] const sortedLabels = memberItems.length ? sortItemsByOrder(memberItems, order).map((m) => m.label) : labels const sortedSignatures = memberItems.length ? sortItemsByOrder(memberItems, order).map((m) => m.signature) : signatures const topicSections = memberItems.length ? [`## ${spec.title}`, ...buildMemberSections(memberItems, order)] : rawSections topics.push({ slug: spec.slug, title: spec.title, description: spec.description, sections: rawSections, topicSections, labels: sortedLabels, signatures: sortedSignatures, }) } } const unassigned = capabilityEntries.filter((entry) => !assigned.has(entry.slug)).map((entry) => entry.slug) if (unassigned.length > 0) { throw new Error( `Unassigned SDK capability(s): ${unassigned.join(', ')}. Assign each to a topic in BROWSER_TOPICS.` ) } if (utilsEntry?.sections?.length || utilsEntry?.memberItems?.length) { const order = BROWSER_MEMBER_ORDER.utils ?? [] const sortedUtils = utilsEntry.memberItems ? sortItemsByOrder(utilsEntry.memberItems, order) : [] const utilsTopicSections = sortedUtils.length ? ['## SDK utils', ...buildMemberSections(sortedUtils, order)] : utilsEntry.sections topics.push({ slug: 'utils', title: 'SDK utils', description: 'Samplers, toolbar, early access features, and helper utilities', sections: [...(utilsEntry.sections ?? [])], topicSections: utilsTopicSections, labels: sortedUtils.length ? sortedUtils.map((m) => m.label) : [...(utilsEntry.labels ?? [])], signatures: sortedUtils.length ? sortedUtils.map((m) => m.signature) : [...(utilsEntry.signatures ?? utilsEntry.labels ?? [])], }) } return topics } /** * Cleans TypeDoc-generated member or type Markdown by removing noise left by TypeScript internals: * empty Returns: void blocks, Call/Get Signature wrapper headings, self-referential Extended by lists, * leaked @experimental tags in defaults, stale beforeCapture wording, monorepo sync notes, and empty See headings. */ export function cleanRenderedMarkdown(markdown, { stripVoidReturn = false } = {}) { let out = markdown .replace(/^#### (?:Call|Get) Signature\n+/gm, '') .replace(/^##### (Parameters|Returns|Remarks|Examples?|See|Deprecated)\b/gm, '#### $1') .replace(/\*\*Default\*\* `([^`]+?) @experimental`/g, '**Default** `$1`') .replace(/\bbeforeCapture\b/g, 'before_send') .replace(/^Sync with plugin-server\/src\/types\.ts\.\n*/gm, '') .replace( /^NOTE: This type is also defined in @posthog\/core \(exception-steps\.ts\)\. Keep both in sync\.\n*/gm, '' ) .replace(/\n*#### See\s*(?=\n|$)(?!\n\n(?:[^\n-]|- [^\s]))/g, '') if (stripVoidReturn) { out = out.replace(/\n+#{4,6} Returns\n+`void`\s*(?=\n#{2,6} |\n$|$)/g, '\n') } const headingMatch = out.match(/^### `([^`]+)`/) if (headingMatch) { const typeName = headingMatch[1] const escaped = typeName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') out = out.replace(new RegExp(`\\n+#### Extended by\\n+- \`${escaped}\`\\s*(?=\\n#### |$)`, 'g'), '\n') } // Trim trailing spaces inside fenced code blocks (e.g., expanded TypeScript parameter lists). out = out.replace(/```ts\n[\s\S]*?\n```/g, (block) => block .split('\n') .map((line) => line.trimEnd()) .join('\n') ) return out.replace(/\n{3,}/g, '\n\n').trim() } /** Filters duplicate and internal browser types while keeping PostHogConfig fields merged and ordered. */ export const BROWSER_EXCLUDED_TYPE_NAMES = new Set([ 'PostHog', 'PostHogInterface', 'LogSdkContext', 'Client', 'Extension', 'ExtensionToken', 'KeyValueStore', 'PersistentStore', 'ApiResponse', 'SendRequestInit', 'Disposable', 'Listener', 'FlagsResponse', 'RemoteConfig', 'SessionRecordingPersistedConfig', 'SessionRecordingRemoteConfig', 'RequestWithOptions', 'QueuedRequestWithOptions', 'RetriableRequestWithOptions', 'RequestTarget', 'RequestTransport', 'NextOptions', 'PostHogFeatureFlags', 'PostHogLogs', 'PostHogMetrics', 'Message', 'MessageAuthorType', 'MarkAsReadResponse', 'SendMessagePayload', 'SendMessageResponse', 'GetMessagesResponse', 'GetTicketsOptions', 'GetTicketsResponse', 'UserProvidedTraits', 'WidgetPosition', 'SessionContext', 'SnippetArrayItem', 'DeadClickCandidate', 'Writable', 'HistogramOptions', 'BeforeSendMetricFn', 'CaptureMetricOptions', 'RequestRestoreLinkPayload', 'RequestRestoreLinkResponse', 'ShowTourOptions', 'JSONContent', 'NetworkRequest', 'OverrideConfig', ]) export const BROWSER_EXCLUDED_TYPE_PREFIXES = [ /^Otlp/, /^(Conversations|Ticket|TipTap|RestoreFromToken)/, /^(BrowserMetrics|MetricsConfig|Metric|NetworkMetrics)/, /^ProductTour/, /^SiteApp/, /^SegmentAnalytics/, ] export function isExcludedBrowserType(name) { return BROWSER_EXCLUDED_TYPE_NAMES.has(name) || BROWSER_EXCLUDED_TYPE_PREFIXES.some((pattern) => pattern.test(name)) } /** True for configuration types bundled in config.md (PostHogConfig, SessionRecordingOptions, ConfigDefaults, *Config). */ export function isConfigType(name) { return ( name === 'PostHogConfig' || name === 'SessionRecordingOptions' || name === 'ConfigDefaults' || name.endsWith('Config') ) } /** Tracks CommonMark code fence open/close state across lines so inline ```foo``` does not toggle fence state. */ export function nextFenceState(fence, line) { if (!fence) { const open = line.match(FENCE_OPEN_RE) if (!open) return null const [, run, info] = open return run[0] === '`' && info.includes('`') ? null : { char: run[0], len: run.length } } const close = line.match(FENCE_CLOSE_RE) return close && close[1][0] === fence.char && close[1].length >= fence.len ? null : fence } function transformOutsideFences(markdown, transformLine) { let fence = null return markdown .split('\n') .map((line) => { const next = nextFenceState(fence, line) const inFence = Boolean(fence || next) fence = next return inFence ? line : transformLine(line) }) .join('\n') } /** Rewrites relative `/docs/...` and `/tutorials/...` Markdown links to `https://posthog.com/...` outside code fences. */ export function rewriteRelativeDocsLinks(markdown) { return transformOutsideFences(markdown, (line) => line .replace(/\]\(\/docs\/([^)#\s]+)(#[^)\s]*)?\)/g, (_match, rawPath, hash = '') => { const cleanPath = rawPath.replace(/\/+$/, '') const target = cleanPath.endsWith('.md') ? cleanPath : `${cleanPath}.md` return `](https://posthog.com/docs/${target}${hash})` }) .replace(/\]\(\/tutorials\/([^)#\s]+)(#[^)\s]*)?\)/g, (_match, rawPath, hash = '') => { const cleanPath = rawPath.replace(/\/+$/, '') return `](https://posthog.com/tutorials/${cleanPath}${hash})` }) ) } /** Strict domain allowlist: only PostHog-owned domains, PostHog GitHub repos, or RFC 2606 example placeholders. */ export function isAllowedSkillUrl(rawUrl) { if (typeof rawUrl !== 'string') return false const trimmed = rawUrl.trim() if (!/^(?:https?:)?\/\/[a-z0-9]/i.test(trimmed)) return false let parsed try { parsed = trimmed.startsWith('//') ? new URL(`https:${trimmed}`) : new URL(trimmed) } catch { return false } if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return false const host = parsed.hostname.toLowerCase() if (ALLOWED_EXACT_HOSTS.has(host) || ALLOWED_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix))) { return true } if (host === 'github.com' && /^\/posthog(\/|$)/i.test(parsed.pathname)) { return true } return false } /** Strips Markdown and bare links pointing outside the strict PostHog allowlist. */ export function stripNonPostHogLinks(markdown) { return transformOutsideFences(markdown, (line) => { let out = line.replace(/\[([^\]]+)\]\(((?:https?:)?\/\/[a-z0-9][^)\s]*)\)/gi, (match, label, url) => isAllowedSkillUrl(url) ? match : label ) out = out.replace(/<((?:https?:)?\/\/[a-z0-9][^>\s]*)>/gi, (match, url) => isAllowedSkillUrl(url) ? match : '' ) out = out.replace(BARE_SKILL_URL_RE, (match) => { const url = match.replace(/^See\s+/i, '').replace(/[.,;:!?]+$/, '') return isAllowedSkillUrl(url) ? match : '' }) return out .replace(/\s{2,}/g, ' ') .replace(/\s+\|/g, ' |') .trimEnd() }) } /** Returns any disallowed external URLs anywhere in the skill Markdown, including fenced code blocks. */ export function findDisallowedSkillUrls(markdown) { const disallowed = new Set() for (const match of markdown.matchAll(SKILL_URL_RE)) { const url = match[0].replace(/[.,;:!?]+$/, '') if (!isAllowedSkillUrl(url)) disallowed.add(url) } return [...disallowed] } /** * Parses flat SKILL.md YAML frontmatter and rejects ambiguous plain scalars (such as unquoted `: `). * Keeps zero-dependency parity with strict YAML parsers like js-yaml. */ export function parseSkillFrontmatter(skillMarkdown) { const match = skillMarkdown.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/) if (!match) { throw new Error('SKILL.md is missing YAML frontmatter (--- ... ---)') } const result = {} for (const rawLine of match[1].split(/\r?\n/)) { const line = rawLine.trimEnd() if (!line.trim() || line.trimStart().startsWith('#')) continue const kv = line.match(/^([a-zA-Z0-9_-]+):\s*(.+)$/) if (!kv) { throw new Error(`Invalid YAML frontmatter line: ${line}`) } const [, key, rawValue] = kv if (Object.hasOwn(result, key)) { throw new Error(`Duplicate YAML frontmatter key: ${key}`) } const trimmed = rawValue.trim() const doubleQuoted = trimmed.match(/^"((?:\\.|[^"\\])*)"$/) if (doubleQuoted) { result[key] = doubleQuoted[1].replace(/\\(["\\])/g, '$1') continue } const singleQuoted = trimmed.match(/^'((?:''|[^'])*)'$/) if (singleQuoted) { result[key] = singleQuoted[1].replace(/''/g, "'") continue } if (/^[[{}*&!|>%@`"']/.test(trimmed)) { throw new Error(`Invalid or unclosed scalar for YAML frontmatter key "${key}"`) } if (/:(\s|$)/.test(trimmed) || /\s#/.test(trimmed)) { throw new Error( `YAML frontmatter key "${key}" contains ": " or " #" in an unquoted scalar; wrap it in quotes` ) } result[key] = trimmed } return result } /** Replaces the generated reference index block between comment markers in SKILL.md. */ export function updateSkillIndex(skillMarkdown, indexTable) { const startIdx = skillMarkdown.indexOf(INDEX_START) const endIdx = skillMarkdown.indexOf(INDEX_END) if (startIdx === -1 || endIdx === -1 || endIdx < startIdx) { throw new Error(`SKILL.md must contain ${INDEX_START} and ${INDEX_END} markers`) } const before = skillMarkdown.slice(0, startIdx + INDEX_START.length) const after = skillMarkdown.slice(endIdx) return `${before}\n${indexTable.trim()}\n${after}` } /** Formats a compact method or constructor signature from a TypeDoc reflection for the SKILL.md index table. */ export function formatCompactSignature(label, reflection) { const sig = reflection?.signatures?.[0] if (!sig) return label const params = (sig.parameters ?? []) .map((p) => { const rest = p.flags?.isRest ? '...' : '' const optional = p.flags?.isOptional || typeof p.defaultValue === 'string' ? '?' : '' return `${rest}${p.name}${optional}` }) .join(', ') if (label === 'new PostHog(...)') return `new PostHog(${params})` const base = label.startsWith('PostHog.') ? `posthog.${label.slice('PostHog.'.length)}` : label return `${base}(${params})` } export function formatSkillIndexTable(entries) { const rows = entries.map( ({ file, description, signatures }) => `| \`./references/${file}\` | ${description} | ${signatures} |` ) return ['| Reference file | Covers | Key signatures |', '| --- | --- | --- |', ...rows].join('\n') }