UNPKG

@usenotra/geo

Version:

Request capture SDK for AI traffic attribution and agent feedback collection

191 lines (187 loc) • 5.48 kB
// src/constants.ts var JOURNEY_ID_PARAM = "ntr"; var JOURNEY_ID_PATTERN = /^[A-Za-z0-9_-]{8,32}$/; var JOURNEY_ID_BYTES = 12; // src/link-target.ts var HTTP_PROTOCOL = /^https?:\/\//i; var EXISTING_JOURNEY_PARAM = new RegExp(`[?&](?:amp;)?${JOURNEY_ID_PARAM}=`); var RESOLVE_BASE = "https://journey.invalid"; function isSameHost(target, host) { if (!host) { return false; } try { const parsed = new URL(target, RESOLVE_BASE); return parsed.hostname.toLowerCase() === host.trim().toLowerCase(); } catch { return false; } } function isTaggableTarget(target, host) { const value = target.trim(); if (value.length === 0 || value.startsWith("#") || value.startsWith("<")) { return false; } if (EXISTING_JOURNEY_PARAM.test(value)) { return false; } if (value.startsWith("//")) { return isSameHost(value, host); } if (value.startsWith("/")) { return true; } if (HTTP_PROTOCOL.test(value)) { return isSameHost(value, host); } return false; } function appendJourneyParam(target, journeyId, ampersand = "&") { const hashIndex = target.indexOf("#"); const base = hashIndex === -1 ? target : target.slice(0, hashIndex); const fragment = hashIndex === -1 ? "" : target.slice(hashIndex); let separator = "?"; if (base.endsWith("?")) { separator = ""; } else if (base.includes("?")) { separator = ampersand; } return `${base}${separator}${JOURNEY_ID_PARAM}=${journeyId}${fragment}`; } // src/markdown.ts var FENCE_SPLIT = /(```[\s\S]*?```|~~~[\s\S]*?~~~)/; var INLINE_CODE_SPLIT = /(`+[^`]*`+)/; var REFERENCE_LINK = /^([ \t]{0,3}\[[^\]]+\]:[ \t]*)(\S+)/gm; var BASE64_URL_UNSAFE = /[+/]/g; var BASE64_PADDING = /=+$/; var BASE64_URL_REPLACEMENTS = { "+": "-", "/": "_" }; function mintJourneyId() { const bytes = new Uint8Array(JOURNEY_ID_BYTES); globalThis.crypto.getRandomValues(bytes); let binary = ""; for (const byte of bytes) { binary += String.fromCharCode(byte); } return btoa(binary).replace(BASE64_URL_UNSAFE, (char) => BASE64_URL_REPLACEMENTS[char] ?? char).replace(BASE64_PADDING, ""); } function toUrl(input) { if (typeof input === "string") { try { return new URL(input, RESOLVE_BASE); } catch { return null; } } if (input instanceof URL) { return input; } try { return new URL(input.url); } catch { return null; } } function getJourneyId(request) { const url = toUrl(request); const value = url?.searchParams.get(JOURNEY_ID_PARAM); if (!value || !JOURNEY_ID_PATTERN.test(value)) { return null; } return value; } function tagText(text, journeyId, host) { const output = []; let outputStart = 0; let searchFrom = 0; while (searchFrom < text.length) { const labelStart = text.indexOf("[", searchFrom); if (labelStart === -1) { break; } const labelEnd = text.indexOf("]", labelStart + 1); if (labelEnd === -1) { break; } if (text[labelEnd + 1] !== "(") { searchFrom = labelEnd + 1; continue; } let cursor = labelEnd + 2; while (text[cursor]?.trim() === "") { cursor += 1; } const targetStart = cursor; while (cursor < text.length && text[cursor]?.trim() !== "" && text[cursor] !== "(" && text[cursor] !== ")") { cursor += 1; } if (cursor === targetStart) { searchFrom = labelEnd + 1; continue; } const targetEnd = cursor; while (text[cursor]?.trim() === "") { cursor += 1; } let titleEnd = targetEnd; if (cursor > targetEnd && text[cursor] === '"') { cursor += 1; while (cursor < text.length && text[cursor] !== '"') { cursor += 1; } if (cursor === text.length) { searchFrom = labelEnd + 1; continue; } cursor += 1; titleEnd = cursor; while (text[cursor]?.trim() === "") { cursor += 1; } } if (text[cursor] !== ")") { searchFrom = labelEnd + 1; continue; } const matchEnd = cursor + 1; const target = text.slice(targetStart, targetEnd); const isImage = labelStart > 0 && text[labelStart - 1] === "!"; if (isImage || !isTaggableTarget(target, host)) { searchFrom = matchEnd; continue; } const label = text.slice(labelStart + 1, labelEnd); const title = text.slice(targetEnd, titleEnd); output.push( text.slice(outputStart, labelStart), `[${label}](${appendJourneyParam(target, journeyId)}${title})` ); outputStart = matchEnd; searchFrom = matchEnd; } output.push(text.slice(outputStart)); const withInlineLinks = output.join(""); return withInlineLinks.replace( REFERENCE_LINK, (match, prefix, target) => { if (!isTaggableTarget(target, host)) { return match; } return `${prefix}${appendJourneyParam(target, journeyId)}`; } ); } function tagSegment(segment, journeyId, host) { return segment.split(INLINE_CODE_SPLIT).map( (part) => part.startsWith("`") ? part : tagText(part, journeyId, host) ).join(""); } function tagMarkdownLinks(markdown, journeyId, options = {}) { if (!JOURNEY_ID_PATTERN.test(journeyId)) { return markdown; } return markdown.split(FENCE_SPLIT).map((segment) => { const isFence = segment.startsWith("```") || segment.startsWith("~~~"); return isFence ? segment : tagSegment(segment, journeyId, options.host); }).join(""); } export { getJourneyId, mintJourneyId, tagMarkdownLinks };