/** Records Notion-as-Code declarations while the build-only metadata bundle evaluates. */ import type { InfraAsCodeIntent } from "./intents.js"; import type { RecordedProvisioning } from "./provisioning.js"; let activeRecorder: RecordedProvisioning | undefined; let currentCapabilityKey: string | undefined; /** Start collecting declarations from the metadata bundle. */ export function startMetadataRecording(): RecordedProvisioning { const recorder: RecordedProvisioning = { intents: [] }; activeRecorder = recorder; currentCapabilityKey = undefined; return recorder; } /** Finish the active metadata collection and return its declarations. */ export function finishMetadataRecording(recorder: RecordedProvisioning): RecordedProvisioning { if (activeRecorder !== recorder) { throw new Error("Notion-as-Code metadata recorder was replaced before build completed"); } activeRecorder = undefined; currentCapabilityKey = undefined; return recorder; } /** Record one declaration when metadata collection is active. */ export function recordIntent(intent: InfraAsCodeIntent): void { activeRecorder?.intents.push(intent); } /** Evaluate one discovered capability with its build-time identity available to declarations. */ export async function withMetadataCapabilityKey( capabilityKey: string | undefined, evaluate: () => Promise, ): Promise { const previousCapabilityKey = currentCapabilityKey; currentCapabilityKey = capabilityKey; try { return await evaluate(); } finally { currentCapabilityKey = previousCapabilityKey; } } /** Return the capability key only while a metadata bundle is recording. */ export function getCurrentMetadataCapabilityKey(): string | undefined { return activeRecorder === undefined ? undefined : currentCapabilityKey; } /** Whether declarations are currently being collected by the build metadata bundle. */ export function isMetadataRecording(): boolean { return activeRecorder !== undefined; }