import { get } from "lodash-es"; import type { PageAttributes } from "../site/attributes"; import { datasourceSystemProperties, datasourceInternalManifest, Datasource, datasourceSystemIndexes, } from "./types"; import z from "zod"; export { nanoid } from "nanoid"; // Date part shared between patterns — handles leap years (Feb 29) correctly const DATE_PART = "(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29" + "|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))"; // Accepts both ISO 8601 UTC (2024-01-15T14:30:00Z) and SQL-style (2024-01-15 14:30:00) const DATETIME_PATTERN = `^${DATE_PART}` + `(?:T(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?Z` + `| (?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d)$`; export type ToJSONSchemaOptions = Parameters[1]; /** * Converts a Zod schema to JSON Schema. * For `z.iso.datetime()` fields, the pattern accepts both ISO 8601 UTC * (e.g. `2024-01-15T14:30:00Z`) and SQL-style (e.g. `2024-01-15 14:30:00`). */ export function toJSONSchema(schema: z.ZodType, options?: ToJSONSchemaOptions) { return z.toJSONSchema(schema, { ...options, override(ctx) { // Apply the caller's own override first (it mutates ctx.jsonSchema in place) options?.override?.(ctx); const js = ctx.jsonSchema as Record; if (js.type === "string" && js.format === "date-time") { js.pattern = DATETIME_PATTERN; } }, }); } export function stringifyObjectValues( obj: Record, ): Record { return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, value.toString()])); } export function createPlaceholderReplacer(attr?: PageAttributes) { return function replacePlaceholders(_: unknown, p1: string) { const varName = (p1 as string).trim(); return String(get(attr, varName)) ?? ""; }; } export const placeholderRx = /{{(.+?)}}/g; /** * Map a datasource schema to include $id, $createdAt, and $updatedAt properties. */ export function mapDatasourceSchemaWithInternalProperties(schema: z.ZodObject) { const originalMeta = schema.meta() ?? {}; return schema.extend(datasourceSystemProperties.shape).meta(originalMeta); } // NOTE on the shape of `schema`: // We type it as `z.core.$ZodType` (rather than `z.ZodObject` // or `z.ZodRawShape`) to keep tsgo happy. zod v4's `ZodObject` requires // `Shape extends Readonly<$ZodShape>`; tsgo refuses to unify that `Readonly` // constraint with the literal shape produced by `z.object({...})`, which // cascades into TS2589. Constraining on the base `$ZodType` sidesteps the // shape-variance check entirely while still inferring the concrete schema // type at the call site (so `ds.schema.shape.foo` keeps its narrow type). interface DefineDatasourceManifest> { id: string; label: string; description?: string; provider: "internal"; hidden?: boolean; schema: S; labelBy?: string; indexes?: Datasource["indexes"]; foreignKeys?: Datasource["foreignKeys"]; } /** * For now, defineDatasource() force the usage of a custom (internal) datasource */ export function defineDatasource>( manifest: DefineDatasourceManifest, ) { const parsed = datasourceInternalManifest.parse(manifest); const finalSchema = mapDatasourceSchemaWithInternalProperties( manifest.schema as unknown as z.ZodObject, ); const indexes = [...(parsed.indexes ?? []), ...datasourceSystemIndexes]; const result: Datasource = { ...parsed, provider: "internal" as const, schema: finalSchema, indexes, }; return result as unknown as Omit & { schema: S }; }