export const POSTGRES_IDENTIFIER_MAX_LENGTH = 63; export const PLAY_NAME_MAX_LENGTH = POSTGRES_IDENTIFIER_MAX_LENGTH; export const MAP_KEY_NAMESPACE_MAX_LENGTH = POSTGRES_IDENTIFIER_MAX_LENGTH; export const DEFAULT_TABLE_NAMESPACE = 'sheet'; export const DEFAULT_INTERNAL_TABLE_NAMESPACE = '_key'; const SHA256_INITIAL_HASH: number[] = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, ]; const SHA256_ROUND_CONSTANTS: number[] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ]; function stableValue(value: unknown): unknown { if (Array.isArray(value)) { return value.map((entry) => stableValue(entry)); } if (value && typeof value === 'object') { return Object.fromEntries( Object.entries(value as Record) .filter(([, entry]) => entry !== undefined) .sort(([left], [right]) => left.localeCompare(right)) .map(([key, entry]) => [key, stableValue(entry)]), ); } return value; } export function stableStringify(value: unknown): string { return JSON.stringify(stableValue(value)); } function rightRotate32(value: number, bits: number): number { return (value >>> bits) | (value << (32 - bits)); } export function sha256Hex(input: string): string { const bytes = Array.from(new TextEncoder().encode(input)); const bitLength = bytes.length * 8; bytes.push(0x80); while (bytes.length % 64 !== 56) { bytes.push(0); } const highBits = Math.floor(bitLength / 0x100000000); const lowBits = bitLength >>> 0; bytes.push( (highBits >>> 24) & 0xff, (highBits >>> 16) & 0xff, (highBits >>> 8) & 0xff, highBits & 0xff, (lowBits >>> 24) & 0xff, (lowBits >>> 16) & 0xff, (lowBits >>> 8) & 0xff, lowBits & 0xff, ); const hash = [...SHA256_INITIAL_HASH]; const words = new Array(64).fill(0); for (let offset = 0; offset < bytes.length; offset += 64) { for (let index = 0; index < 16; index += 1) { const wordOffset = offset + index * 4; words[index] = ((bytes[wordOffset] ?? 0) << 24) | ((bytes[wordOffset + 1] ?? 0) << 16) | ((bytes[wordOffset + 2] ?? 0) << 8) | (bytes[wordOffset + 3] ?? 0); } for (let index = 16; index < 64; index += 1) { const s0 = rightRotate32(words[index - 15], 7) ^ rightRotate32(words[index - 15], 18) ^ (words[index - 15] >>> 3); const s1 = rightRotate32(words[index - 2], 17) ^ rightRotate32(words[index - 2], 19) ^ (words[index - 2] >>> 10); words[index] = (words[index - 16] + s0 + words[index - 7] + s1) >>> 0; } let [a, b, c, d, e, f, g, h] = hash; for (let index = 0; index < 64; index += 1) { const s1 = rightRotate32(e, 6) ^ rightRotate32(e, 11) ^ rightRotate32(e, 25); const ch = (e & f) ^ (~e & g); const temp1 = (h + s1 + ch + SHA256_ROUND_CONSTANTS[index] + words[index]) >>> 0; const s0 = rightRotate32(a, 2) ^ rightRotate32(a, 13) ^ rightRotate32(a, 22); const maj = (a & b) ^ (a & c) ^ (b & c); const temp2 = (s0 + maj) >>> 0; h = g; g = f; f = e; e = (d + temp1) >>> 0; d = c; c = b; b = a; a = (temp1 + temp2) >>> 0; } hash[0] = (hash[0] + a) >>> 0; hash[1] = (hash[1] + b) >>> 0; hash[2] = (hash[2] + c) >>> 0; hash[3] = (hash[3] + d) >>> 0; hash[4] = (hash[4] + e) >>> 0; hash[5] = (hash[5] + f) >>> 0; hash[6] = (hash[6] + g) >>> 0; hash[7] = (hash[7] + h) >>> 0; } return hash.map((word) => word.toString(16).padStart(8, '0')).join(''); } function sanitizeIdentifierPart(value: string): string { return value .trim() .replace(/[^a-z0-9]+/gi, '_') .replace(/_+/g, '_') .replace(/^_+|_+$/g, '') .toLowerCase(); } function validateIdentifierPart( rawValue: string, label: string, maxLength: number, ): string { const sanitized = sanitizeIdentifierPart(rawValue); if (!sanitized) { throw new Error(`${label} must contain a letter or number.`); } if (sanitized.length > maxLength) { throw new Error( `${label} is too long after normalization (${sanitized.length}/${maxLength}): "${sanitized}".`, ); } return sanitized; } export function normalizePlayName(value: string): string { if (value.includes('/')) { throw new Error( 'Play name cannot contain "/". Slash is reserved.', ); } return validateIdentifierPart(value, 'Play name', PLAY_NAME_MAX_LENGTH); } /** * Normalize a play name into the leading segment of a physical sheet table name. * * A qualified reference like "prebuilt/name-and-domain-to-email-waterfall" folds * its namespace separator into a plain identifier * ("prebuilt_name_and_domain_to_email_waterfall") so the physical table reads * cleanly. `validatePlaySheetTableName` enforces the 63-char Postgres identifier * limit on the play + namespace combination and fails loudly when a name is * genuinely too long — no opaque content digest is mixed into the table name. */ export function normalizePlayNameForSheet(value: string): string { if (!value.includes('/')) { return normalizePlayName(value); } return validateIdentifierPart( value.replace(/\//g, '_'), 'Play name', PLAY_NAME_MAX_LENGTH, ); } export function normalizeTableNamespace(value: string): string { return validateIdentifierPart( value, 'ctx.dataset() key', MAP_KEY_NAMESPACE_MAX_LENGTH, ); } export function validatePlaySheetTableName( playName: string, tableNamespace: string, ): string { const playSegment = normalizePlayNameForSheet(playName); const keySegment = normalizeTableNamespace(tableNamespace); const resolved = `${playSegment}_${keySegment}`; if (resolved.length > POSTGRES_IDENTIFIER_MAX_LENGTH) { throw new Error( `Play sheet table name is too long after normalization (${resolved.length}/63): "${resolved}".`, ); } return resolved; } export function derivePlayRowIdentity( row: Record, tableNamespace: string, ): string { return deriveDerivedOutputIdentity({ inputItem: row, operationNamespace: tableNamespace, }); } export function deriveDerivedOutputIdentity(input: { inputItem: Record; operationNamespace: string; }): string { const normalizedNamespace = normalizeTableNamespace(input.operationNamespace); const canonicalRow = stableStringify(input.inputItem); const digest = sha256Hex(`${normalizedNamespace}\n${canonicalRow}`); return `${normalizedNamespace}:${digest}`; } export function deriveToolRequestIdentity(input: { toolId: string; requestInput: Record; }): string { const toolId = input.toolId.trim(); if (!toolId) { throw new Error('Tool request identity requires a non-empty tool id.'); } const digest = sha256Hex( stableStringify({ requestInput: input.requestInput, toolId, }), ); return `tool:${normalizeTableNamespace(toolId)}:${digest}`; } /** * Build a stable row identity from an explicit user-provided key string. * * Use when the caller wants to pin row identity to a primary column * (e.g. row.email) instead of hashing the full row contents — so harmless * mutations to other columns don't invalidate the cache. */ export function derivePlayRowIdentityFromKey( key: string, tableNamespace: string, ): string { const normalizedNamespace = normalizeTableNamespace(tableNamespace); const digest = sha256Hex(`${normalizedNamespace}\nkey:${key}`); return `${normalizedNamespace}:${digest}`; }