viborm 1.8.0 → 1.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-namespace-BMss0hKo.mjs → adapter-namespace-VikEzb7o.mjs} +2 -2
- package/dist/{adapter-namespace-BMss0hKo.mjs.map → adapter-namespace-VikEzb7o.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{builder-Ct1qPFc8.mjs → builder-CEQ2TIq7.mjs} +2 -2
- package/dist/{builder-Ct1qPFc8.mjs.map → builder-CEQ2TIq7.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/{chain--uZ0O7_Y.mjs → chain-DG_4uSjk.mjs} +2 -2
- package/dist/{chain--uZ0O7_Y.mjs.map → chain-DG_4uSjk.mjs.map} +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/{client-mQcOvDdK.mjs → client-BJuTpcYj.mjs} +20 -20
- package/dist/client-BJuTpcYj.mjs.map +1 -0
- package/dist/client-BojZRIyT.mjs +2 -0
- package/dist/client-BojZRIyT.mjs.map +1 -0
- package/dist/{client-DP6gM_tf.d.mts → client-CrBKhXo-.d.mts} +1 -1
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/{datetime-physical-codec-DTdvABny.mjs → datetime-physical-codec-Cdgq6sGs.mjs} +2 -2
- package/dist/{datetime-physical-codec-DTdvABny.mjs.map → datetime-physical-codec-Cdgq6sGs.mjs.map} +1 -1
- package/dist/{driver-NtekjA3W.mjs → driver-DX8GWgGf.mjs} +2 -2
- package/dist/{driver-NtekjA3W.mjs.map → driver-DX8GWgGf.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/every-CyllpuCG.mjs +2 -0
- package/dist/{every-Xql4tHDz.mjs.map → every-CyllpuCG.mjs.map} +1 -1
- package/dist/{geo-area-codec-DvHcWF3g.mjs → geo-area-codec-B3QtKij8.mjs} +2 -2
- package/dist/{geo-area-codec-DvHcWF3g.mjs.map → geo-area-codec-B3QtKij8.mjs.map} +1 -1
- package/dist/{geo-point-codec-CIZxuIvE.mjs → geo-point-codec-Ggv29hSH.mjs} +2 -2
- package/dist/{geo-point-codec-CIZxuIvE.mjs.map → geo-point-codec-Ggv29hSH.mjs.map} +1 -1
- package/dist/{hydration-BNEFeV5v.mjs → hydration-Dd2H4EyY.mjs} +2 -2
- package/dist/{hydration-BNEFeV5v.mjs.map → hydration-Dd2H4EyY.mjs.map} +1 -1
- package/dist/{identifier-conversion-C_XCo9es.mjs → identifier-conversion-BVE8cfFA.mjs} +2 -2
- package/dist/{identifier-conversion-C_XCo9es.mjs.map → identifier-conversion-BVE8cfFA.mjs.map} +1 -1
- package/dist/{index-DBhpNR0X.d.mts → index-BlBkgxtx.d.mts} +12 -0
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{key-QgLg2Kve.mjs → key-B4B1etH3.mjs} +2 -2
- package/dist/{key-QgLg2Kve.mjs.map → key-B4B1etH3.mjs.map} +1 -1
- package/dist/{keys-D5hv9EaJ.mjs → keys-CyfjT6uC.mjs} +2 -2
- package/dist/{keys-D5hv9EaJ.mjs.map → keys-CyfjT6uC.mjs.map} +1 -1
- package/dist/{libsql-BsJdPDES.mjs → libsql-CcKrXiun.mjs} +2 -2
- package/dist/{libsql-BsJdPDES.mjs.map → libsql-CcKrXiun.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-BEaJ0-FU.mjs → memory-B0HOEpPu.mjs} +2 -2
- package/dist/{memory-BEaJ0-FU.mjs.map → memory-B0HOEpPu.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/{model-D94xU8jq.mjs → model-u8Ug971J.mjs} +2 -2
- package/dist/{model-D94xU8jq.mjs.map → model-u8Ug971J.mjs.map} +1 -1
- package/dist/{mysql-adapter-BUwzKlbt.mjs → mysql-adapter-CWisQgdc.mjs} +2 -2
- package/dist/{mysql-adapter-BUwzKlbt.mjs.map → mysql-adapter-CWisQgdc.mjs.map} +1 -1
- package/dist/{mysql-DT_dTWDi.mjs → mysql-sGTzkV2q.mjs} +2 -2
- package/dist/{mysql-DT_dTWDi.mjs.map → mysql-sGTzkV2q.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/{object-store-35LjwOS-.d.mts → object-store-C-VOh0LP.d.mts} +3 -3
- package/dist/on.d.mts +1 -1
- package/dist/ordering.d.mts +33 -8
- package/dist/ordering.mjs +10 -10
- package/dist/ordering.mjs.map +1 -1
- package/dist/permissions.d.mts +22 -3
- package/dist/permissions.mjs +1 -1
- package/dist/permissions.mjs.map +1 -1
- package/dist/pg.d.mts +1 -1
- package/dist/pg.mjs +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/{physical-t_gDjUCD.mjs → physical-CjG29tya.mjs} +2 -2
- package/dist/{physical-t_gDjUCD.mjs.map → physical-CjG29tya.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-CmDw5jPb.d.mts → planner-syQCWHHr.d.mts} +1 -1
- package/dist/{postgres-Do0nq95P.mjs → postgres-C2uUUh0t.mjs} +2 -2
- package/dist/{postgres-Do0nq95P.mjs.map → postgres-C2uUUh0t.mjs.map} +1 -1
- package/dist/{postgres-adapter-Dvt16rbl.mjs → postgres-adapter-CdUHI_lw.mjs} +2 -2
- package/dist/{postgres-adapter-Dvt16rbl.mjs.map → postgres-adapter-CdUHI_lw.mjs.map} +1 -1
- package/dist/{postgres-adapter-DFzjbAP7.mjs → postgres-adapter-D4v50VQk.mjs} +2 -2
- package/dist/{postgres-adapter-DFzjbAP7.mjs.map → postgres-adapter-D4v50VQk.mjs.map} +1 -1
- package/dist/postgres.d.mts +1 -1
- package/dist/postgres.mjs +1 -1
- package/dist/{provider-limits-kO9B3KCF.mjs → provider-limits-DolYOv3_.mjs} +2 -2
- package/dist/{provider-limits-kO9B3KCF.mjs.map → provider-limits-DolYOv3_.mjs.map} +1 -1
- package/dist/{result-shape-DwoSyWnq.mjs → result-shape-dG_6HE7s.mjs} +2 -2
- package/dist/{result-shape-DwoSyWnq.mjs.map → result-shape-dG_6HE7s.mjs.map} +1 -1
- package/dist/{rows-ig1gjVRb.mjs → rows-CEYfrodD.mjs} +2 -2
- package/dist/rows-CEYfrodD.mjs.map +1 -0
- package/dist/rows-of-qH0_KyL6.mjs +2 -0
- package/dist/rows-of-qH0_KyL6.mjs.map +1 -0
- package/dist/{scalar-BgxfbRLw.mjs → scalar-DNshDNz3.mjs} +2 -2
- package/dist/{scalar-BgxfbRLw.mjs.map → scalar-DNshDNz3.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema-DYPfTOQl.mjs +2 -0
- package/dist/{schema-CT57uls5.mjs.map → schema-DYPfTOQl.mjs.map} +1 -1
- package/dist/{schema-introspection-BFDAX5Ol.mjs → schema-introspection-Bu2N__75.mjs} +2 -2
- package/dist/{schema-introspection-BFDAX5Ol.mjs.map → schema-introspection-Bu2N__75.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/soft-delete.d.mts +4 -1
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/{sqlite-adapter-eGsbASDR.mjs → sqlite-adapter-BHx--tnz.mjs} +2 -2
- package/dist/{sqlite-adapter-eGsbASDR.mjs.map → sqlite-adapter-BHx--tnz.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/{to-many-CJ-8_caR.mjs → to-many-5gt2AWLE.mjs} +2 -2
- package/dist/{to-many-CJ-8_caR.mjs.map → to-many-5gt2AWLE.mjs.map} +1 -1
- package/dist/{utils-DYz-Xm59.mjs → utils-CmNRGkRq.mjs} +2 -2
- package/dist/{utils-DYz-Xm59.mjs.map → utils-CmNRGkRq.mjs.map} +1 -1
- package/dist/{v-C2XN11Gy.mjs → v-CWY9ntMb.mjs} +2 -2
- package/dist/{v-C2XN11Gy.mjs.map → v-CWY9ntMb.mjs.map} +1 -1
- package/dist/{validation-BSpO4DjI.mjs → validation-CMvAxrIo.mjs} +2 -2
- package/dist/{validation-BSpO4DjI.mjs.map → validation-CMvAxrIo.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-DqI5RlVU.mjs → validator-CYKdGTvX.mjs} +2 -2
- package/dist/{validator-DqI5RlVU.mjs.map → validator-CYKdGTvX.mjs.map} +1 -1
- package/dist/version-Cam5kto_.mjs +2 -0
- package/dist/{version-DyH_HopX.mjs.map → version-Cam5kto_.mjs.map} +1 -1
- package/package.json +19 -19
- package/dist/client-BAxU6jnw.mjs +0 -2
- package/dist/client-BAxU6jnw.mjs.map +0 -1
- package/dist/client-mQcOvDdK.mjs.map +0 -1
- package/dist/every-Xql4tHDz.mjs +0 -2
- package/dist/rows-ig1gjVRb.mjs.map +0 -1
- package/dist/rows-of-Djavcb19.mjs +0 -2
- package/dist/rows-of-Djavcb19.mjs.map +0 -1
- package/dist/schema-CT57uls5.mjs +0 -2
- package/dist/version-DyH_HopX.mjs +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scalar-BgxfbRLw.mjs","names":["state","catalogs","v","state"],"sources":["../src/schema/registration-preflight.ts","../src/schema/validation/error.ts","../src/schema/scalars/common.ts","../src/schema/scalars/native-catalog.ts","../src/validation/primitives/sha3.ts","../src/schema/scalars/string/autogenerate.ts","../src/schema/scalars/string/scalar.ts"],"sourcesContent":["import type { Model } from \"./model\";\nimport type { SchemaValidationIssue } from \"./validation/types\";\n\n/**\n * Prove that every model object in one registration batch has one schema key.\n *\n * The model's hydrated name is the lifetime claim. The local map covers the\n * still-unhydrated batch, so `{ alpha: shared, beta: shared }` is refused before\n * hydration writes either name. Repeating the same object under the same key is\n * deliberately idempotent.\n */\nexport function preflightModelRegistrationIdentity(\n registrations: Iterable<readonly [string, Model<any>]>\n): SchemaValidationIssue | undefined {\n const claimedInThisPass = new Map<Model<any>, string>();\n for (const [modelKey, model] of registrations) {\n if (\n model === null ||\n typeof model !== \"object\" ||\n !model[\"~\"]?.names ||\n !model[\"~\"]?.state?.scalars\n )\n return {\n code: \"M008\",\n message: `Schema entry '${modelKey}' is not a model; pass an explicit object containing only s.model() definitions`,\n severity: \"error\",\n model: modelKey,\n };\n const claimed = model[\"~\"].names.ts ?? claimedInThisPass.get(model);\n if (claimed !== undefined && claimed !== modelKey)\n return doubleRegistrationIssue(claimed, modelKey);\n claimedInThisPass.set(model, modelKey);\n }\n return undefined;\n}\n\nfunction doubleRegistrationIssue(\n claimed: string,\n modelKey: string\n): SchemaValidationIssue {\n return {\n code: \"M003\",\n message: `Model registered as '${claimed}' cannot also be registered as '${modelKey}'; one model object binds one schema key`,\n severity: \"error\",\n model: modelKey,\n };\n}\n","import { VibORMError, VibORMErrorCode } from \"../../errors/base\";\nimport type { SchemaValidationIssue } from \"./types\";\n\nexport class SchemaValidationError extends VibORMError {\n static override readonly diagnosticName = \"SchemaValidationError\";\n\n declare readonly code: typeof VibORMErrorCode.INVALID_INPUT;\n readonly issues: readonly SchemaValidationIssue[];\n\n constructor(\n issues: readonly SchemaValidationIssue[],\n options?: { cause?: Error | undefined }\n ) {\n // `candidates` is the one array-valued field, so the snapshot freezes it\n // too: a shallow freeze would publish an immutable issue wrapping a\n // caller-mutable list.\n const snapshot = Object.freeze(\n issues.map((issue) =>\n Object.freeze(\n issue.candidates\n ? { ...issue, candidates: Object.freeze([...issue.candidates]) }\n : { ...issue }\n )\n )\n );\n const messages = snapshot.map((issue) =>\n [\n `[${issue.code}] ${issue.message}`,\n issue.candidates?.length\n ? `Candidates: ${issue.candidates.join(\", \")}`\n : \"\",\n issue.repair ?? \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\")\n );\n super(\n `Schema validation failed:\\n${messages.join(\"\\n\")}`,\n VibORMErrorCode.INVALID_INPUT,\n options?.cause ? { cause: options.cause } : undefined\n );\n this.issues = snapshot;\n }\n\n override toJSON(): Record<string, unknown> {\n return { ...super.toJSON(), issues: this.issues };\n }\n}\n\nexport function isSchemaValidationError(\n error: unknown\n): error is SchemaValidationError {\n return error instanceof SchemaValidationError;\n}\n\n/**\n * ONE reading of a value pulled out of a `catch`, shared by every gate boundary\n * that turns a throw into a diagnostic.\n *\n * The throwers this gate catches are all in-repo and all throw `Error`s — the\n * target once-cell normalizes before the resolver ever sees a getter's throw,\n * and the physical-name owner throws its own error type. Each catch site\n * spelling this narrowing itself made three owners for one rule and three arms\n * that no schema can reach; the narrowing lives here instead, where it is\n * witnessed directly.\n */\nexport function thrownAsError(thrown: unknown): Error {\n return thrown instanceof Error ? thrown : new Error(String(thrown));\n}\n","// Common Scalar Utilities\n// Shared types and helpers for all scalar classes\n\nimport { ValidationError } from \"@errors\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { InferInput, VibSchema } from \"@validation\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport type { Scalar } from \"./base\";\n\n// =============================================================================\n// SCHEMA NAMES (hydrated by client at initialization)\n// =============================================================================\n\n/**\n * Name slots for models, scalars, and relations.\n * These are hydrated by the client at initialization time when the full\n * schema context is available.\n *\n * - ts: TypeScript/schema key name (e.g., \"email\", \"User\")\n * - sql: Resolved database name (e.g., \"email_column\", \"users\")\n */\nexport interface SchemaNames {\n /** TypeScript key name in the schema */\n ts?: string;\n /** Resolved SQL name (column/table) */\n sql?: string;\n}\n\n/**\n * Hydrated schema names - guaranteed to have both ts and sql defined.\n * Returned by model[\"~\"].getFieldName() for scalar keys.\n */\nexport interface HydratedSchemaNames {\n /** TypeScript key name in the schema */\n ts: string;\n /** Resolved SQL name (column/table) */\n sql: string;\n}\n\n// =============================================================================\n// SCALAR TYPES\n// =============================================================================\n\nexport type ScalarType =\n | \"string\"\n | \"int\"\n | \"number\"\n | \"decimal\"\n | \"boolean\"\n | \"datetime\"\n | \"date\"\n | \"time\"\n | \"bigint\"\n | \"json\"\n | \"blob\"\n | \"vector\"\n | \"point\"\n | \"enum\";\n\nexport type AutoGenerateType =\n | \"uuid\"\n | \"uuidv7\"\n | \"ulid\"\n | \"ksuid\"\n | \"nanoid\"\n | \"cuid\"\n | \"increment\"\n | \"now\"\n | \"updatedAt\";\n\n/**\n * A generator declaration.\n *\n * `kind` is the only statement of which generator runs. `prefix` and `length`\n * are declaration facts the string generators otherwise bake into their default\n * closure, where nothing can read them back; state is their durable home so a\n * serializer can restate the declaration that produced the closure.\n * `increment`/`now`/`updatedAt` take neither.\n */\nexport interface AutoGenerate {\n kind: AutoGenerateType;\n prefix?: string | undefined;\n length?: number | undefined;\n /**\n * The caller did not NAME this format; `.id()` installed it.\n *\n * The distinction is what separates a key from a domain. `.ulid()` is an\n * assertion about every value the field will ever hold — which is what lets\n * VibORM admit those values, normalize their aliases and store them as\n * sixteen bytes. `.id()` is an assertion about the KEY, carrying a generator\n * so a caller need not supply one; the values it accepts are still whatever\n * a string column accepts, and it stores them as text. `.ulid().id()` says\n * both, and is a ULID key.\n *\n * It lives on the declaration record, beside `kind`, because it IS a fact\n * about how this generator came to be declared — not a second scalar state.\n */\n implicit?: boolean | undefined;\n /** Explicit generation choice; absent formats acquire a default only as IDs. */\n generate?: boolean | undefined;\n}\n\n/**\n * The closures the generator modifiers installed.\n *\n * A generator writes TWO facts: `autoGenerate`, which is the declaration, and\n * `default`, which is the closure that produces the value. A later\n * `.default(fn)` replaces only the second, so `autoGenerate !== undefined` is\n * not evidence that the closure standing in `default` is the generator's — and\n * a consumer that restates a declaration from state (the JSON serializer) would\n * otherwise silently substitute a random generator for a caller's own function.\n *\n * Identity is the only thing that distinguishes them, so identity is what is\n * recorded. One owner, beside the declaration it belongs to; nothing outside\n * the eight modifier writers may add to it.\n */\nconst GENERATOR_DEFAULTS = new WeakSet<object>();\n\n/** Mark a closure as the default a generator modifier installed. */\ndeclare const GENERATED_DEFAULT: unique symbol;\nexport interface GeneratorDefaultBrand {\n readonly [GENERATED_DEFAULT]: true;\n}\nexport function generatorDefault<F extends () => unknown>(\n closure: F\n): F & GeneratorDefaultBrand;\nexport function generatorDefault<F extends () => unknown>(closure: F) {\n GENERATOR_DEFAULTS.add(closure);\n return closure;\n}\n\n/** A scalar generator cannot produce a complete list default. */\nexport function refuseListGenerator(builder: string): never {\n throw new ValidationError(\n { kind: \"schema-builder\", builder, path: \"array\" },\n [\n {\n path: \"array\",\n message:\n \"Scalar generation is not supported on lists; declare an explicit array default\",\n },\n ]\n );\n}\n\n/** Nullable admission supplies null only when no default was already declared. */\nexport function nullableDefault<State extends ScalarState>(\n state: State\n): State[\"hasDefault\"] extends true ? State[\"default\"] : null;\nexport function nullableDefault(state: ScalarState) {\n return state.hasDefault ? state.default : null;\n}\n\n/** Whether this default value IS a generator's own installed closure. */\nexport function isGeneratorDefault(value: unknown): boolean {\n return typeof value === \"function\" && GENERATOR_DEFAULTS.has(value);\n}\n\n// =============================================================================\n// SCALAR STATE\n// =============================================================================\n\n/**\n * Complete state for a scalar instance.\n * This is the single generic that flows through the scalar class.\n */\n\nexport interface ScalarState<T extends ScalarType = ScalarType> {\n type: T;\n nullable: boolean;\n array: boolean;\n hasDefault: boolean;\n isId: boolean;\n isUnique: boolean;\n default: DefaultValue<any> | undefined;\n autoGenerate: AutoGenerate | undefined;\n /** Runtime create validation for portable auto-increment semantics. */\n disallowZero?: boolean;\n schema: StandardSchemaV1<any, any> | undefined;\n optional: boolean;\n /** Custom column name in the database (set via .map()) */\n columnName: string | undefined;\n base: VibSchema;\n withTimezone?: boolean | undefined;\n /**\n * The declared fixed-decimal domain, frozen at `s.decimal({...})`.\n *\n * It is the ONE source of truth for input validation, physical DDL, literal\n * encoding, result decoding, comparison and aggregate lowering, arithmetic\n * rounding and overflow, list-member encoding, and migration compatibility.\n * No adapter, driver, result parser, or migration component stores a second\n * precision or scale decision, and every modifier carries THIS object by\n * reference rather than rebuilding one.\n */\n decimal?: DecimalDescriptor | undefined;\n /** Fixed vector length for pgvector-backed vector scalars. */\n dimension?: number | undefined;\n /** Custom enum type name in the database (set via .name() on enum scalars) */\n enumName?: string | undefined;\n}\n\n// =============================================================================\n// STATE UPDATE HELPER\n// =============================================================================\n\n/**\n * Computes the new state type after applying an update.\n * Used by chainable methods to derive the return type.\n *\n * @example\n * nullable(): StringScalar<UpdateState<State, { nullable: true }>>\n */\nexport type UpdateState<\n State extends ScalarState,\n Update extends Partial<ScalarState>,\n> = Omit<State, keyof Update> & Update;\n\nexport const updateState = <\n F extends Scalar,\n const Update extends Partial<ScalarState>,\n>(\n scalar: F,\n update: Update\n) => {\n return { ...scalar[\"~\"].state, ...update } as UpdateState<\n F[\"~\"][\"state\"],\n Update\n >;\n};\n\n// =============================================================================\n// TYPE HELPERS\n// =============================================================================\n\n/**\n * Conditionally wraps a type with null\n */\nexport type MaybeNullable<\n T,\n Nullable extends boolean = false,\n> = Nullable extends true ? T | null : T;\n\n/**\n * Conditionally wraps a type as array\n */\nexport type MaybeArray<\n T,\n IsArray extends boolean = false,\n> = IsArray extends true ? T[] : T;\n\n/**\n * Type for default value - can be direct value or factory function\n */\nexport type DefaultValue<T> = T | (() => T);\n\n/**\n * The input accepted by the scalar's current base schema, or a factory for it.\n *\n * The base schema already owns the scalar's nullable and array wrappers. Adding\n * them again here turns a list default into a list of lists at the type level\n * (`string[][]` for `s.string().array()`), while runtime validation correctly\n * expects `string[]`. Read the one trusted shape instead of reconstructing it.\n */\nexport type DefaultValueInput<S extends ScalarState> = DefaultValue<\n InferInput<S[\"base\"]>\n>;\n\n// =============================================================================\n// DEFAULT STATE FACTORY\n// =============================================================================\n\n/** The factory's existing initial state stays named in exported model graphs. */\nexport interface InitialScalarState<T extends ScalarType, B extends VibSchema> {\n type: T;\n nullable: boolean;\n array: boolean;\n hasDefault: boolean;\n isId: boolean;\n isUnique: boolean;\n default: undefined;\n autoGenerate: undefined;\n disallowZero: boolean;\n schema: undefined;\n columnName: undefined;\n optional: boolean;\n withTimezone: boolean;\n base: B;\n}\n\n/**\n * Creates a default initial state for a scalar type\n */\nexport const createDefaultState = <T extends ScalarType, B extends VibSchema>(\n type: T,\n base: B\n): InitialScalarState<T, B> => ({\n type,\n nullable: false,\n array: false,\n hasDefault: false,\n isId: false,\n isUnique: false,\n default: undefined,\n autoGenerate: undefined,\n disallowZero: false,\n schema: undefined,\n columnName: undefined,\n optional: false,\n withTimezone: false,\n base,\n});\n\n// =============================================================================\n// INFER HELPERS (for type-level inference from state)\n// =============================================================================\n\n/**\n * Infers the base TypeScript type from a scalar state\n */\nexport type InferBaseType<\n BaseType,\n State extends ScalarState,\n> = State[\"array\"] extends true\n ? State[\"nullable\"] extends true\n ? (BaseType | null)[]\n : BaseType[]\n : State[\"nullable\"] extends true\n ? BaseType | null\n : BaseType;\n\n/**\n * Infers the create input type from a scalar state\n */\nexport type InferCreateType<\n BaseType,\n State extends ScalarState,\n> = State[\"hasDefault\"] extends true\n ? State[\"nullable\"] extends true\n ? BaseType | null | undefined\n : BaseType | undefined\n : State[\"nullable\"] extends true\n ? BaseType | null\n : BaseType;\n\n// =============================================================================\n// SCHEMA SHORTHANDS (re-exported from validation primitives)\n// =============================================================================\n\nexport {\n shorthandArray,\n shorthandFilter,\n shorthandUpdate,\n} from \"@validation/primitives/shorthand\";\n","// The closed per-dialect native-type catalog, and the scalar factories' one\n// native-type admission.\n//\n// A native type's `type` is the ONE declaration string a migration driver emits\n// into DDL verbatim — the three drivers write it as a column's type with no\n// escaping, because a coded schema takes it from a typed constant. A schema\n// document is written by whoever hands you one, so it decides what may occupy\n// that position here. Coded maps and tagged declarations share the historical\n// trusted schema-author escape hatch for custom type spellings. The round-1 answer was a word grammar; the reviewer proved it cannot\n// work: `TEXT REFERENCES victims(id)`, `TEXT UNIQUE` and `TEXT CHECK(0)` are\n// letters and spaces with an optional parenthesized group, indistinguishable\n// from a multi-word type name, yet each appends a CONSTRAINT to a column in DDL.\n// No regex over arbitrary SQL words separates a type from a clause.\n//\n// So the admissible set is CLOSED and derived, per dialect, from the one owner\n// that already enumerates native types: the shipped `PG`/`MYSQL`/`SQLITE`\n// constant trees. Derivation, not duplication —\n//\n// - a string leaf (`{ db, type: \"text\" }`) contributes its EXACT value;\n// - a function leaf (a parameterized type) is probe-called at zero, one and\n// two integer arguments to learn its base name and which argument arities it\n// publishes; the catalog then admits that base bare, or with one or two\n// INTEGER arguments, at exactly those arities.\n//\n// The trees produce no word-argument type THROUGH A FUNCTION — `geometry(Point)`\n// is a string leaf, matched exactly — so there is no word-argument rule, which\n// is the narrowest rule the trees justify. A coded schema's constants are\n// catalog members by construction. The schema-document reader and serializer\n// consult this owner for the tagged `native` form; `admitNativeType` validates coded maps structurally. A TAGGED declaration written in code keeps its historical\n// open contract (a custom `{ db, type }` still reaches DDL as written) — only a\n// document refuses one outside the catalog. Nothing downstream sanitizes native\n// types, and nothing can.\n//\n// This lives beside `native-types.ts` rather than in the document module because\n// the scalar factories need it; it imports the constant trees, so the trees'\n// module cannot import it back.\n\nimport { ValidationError } from \"@errors\";\nimport { isRecord } from \"@validation/value-guards\";\nimport {\n type DialectNativeType,\n isTaggedNativeType,\n MYSQL,\n NATIVE_DIALECTS,\n type NativeDialect,\n type NativeTypeDeclaration,\n type NativeTypeMap,\n PG,\n SQLITE,\n} from \"./native-types\";\n\ntype Dialect = NativeDialect;\n\ntype DialectCatalog = {\n /** The exact type strings every string leaf produces. */\n readonly exact: Set<string>;\n /** A parameterized base name → the argument arities it publishes (0 = bare). */\n readonly templates: Map<string, Set<number>>;\n};\n\n/** Distinct non-zero probe arguments, so a produced form is unambiguous. */\nconst PROBE_ARGUMENTS: readonly number[][] = [[], [1], [1, 2]];\n\n/** A parameterized-type argument the trees produce: a non-negative integer. */\nconst INTEGER_ARGUMENT = /^\\d+$/;\n\n/**\n * A native type at the matching boundary: a base identifier, optionally followed\n * by one parenthesized group of comma-separated integers. This gate REJECTS\n * everything a clause needs — a quote, a space, a semicolon, a comment, a second\n * group, a non-integer argument — so what survives is only shaped like a type,\n * and the catalog then decides whether it IS one.\n */\nconst TYPE_EXPRESSION = /^[A-Za-z_][A-Za-z0-9_]*(\\(\\d+(,\\d+)*\\))?$/;\n\nconst CONSTANT_NAMES: Record<Dialect, string> = {\n pg: \"PG\",\n mysql: \"MYSQL\",\n sqlite: \"SQLITE\",\n};\n\n// Built on the first native-type check rather than at import: walking every\n// dialect's constants runs dozens of probe calls, and a schema that declares\n// no native type never asks.\nlet catalogs: Record<Dialect, DialectCatalog> | undefined;\n\n/**\n * Whether `type` is a native type the declared dialect's catalog admits. The\n * gate's single statement, used by the reader and the serializer alike.\n */\nexport function isNativeTypeInCatalog(db: Dialect, type: string): boolean {\n catalogs ??= buildCatalogs();\n const catalog = catalogs[db];\n if (catalog.exact.has(type)) {\n return true;\n }\n if (!TYPE_EXPRESSION.test(type)) {\n return false;\n }\n const open = type.indexOf(\"(\");\n if (open === -1) {\n return catalog.templates.get(type)?.has(0) === true;\n }\n const base = type.slice(0, open);\n const arity = type.slice(open + 1, -1).split(\",\").length;\n return catalog.templates.get(base)?.has(arity) === true;\n}\n\n/**\n * The refusal both directions carry, naming the dialect whose catalog was\n * consulted and pointing at the documented list.\n */\nexport function nativeTypeRefusal(db: Dialect): string {\n return `A \\`native.type\\` is written into DDL verbatim, so a document may carry only a native type from the '${db}' dialect's closed catalog — the values the ${CONSTANT_NAMES[db]} native-type constants produce. See the native types documentation (docs/schema/native-types).`;\n}\n\n// =============================================================================\n// SCALAR FACTORY ADMISSION\n// =============================================================================\n\n/** The one construction-time refusal of a native-type argument. */\nfunction refuse(builder: string, path: string, message: string): never {\n throw new ValidationError({ kind: \"schema-builder\", builder, path }, [\n { path, message },\n ]);\n}\n\n/**\n * A scalar factory's native-type argument, admitted: the declaration the scalar\n * stores and every modifier carries.\n *\n * The tagged shorthand is returned AS GIVEN — its open historical contract,\n * custom spellings and unrelated extra keys included, is unchanged — once it\n * names one of the three dialects as `db` and a string `type` (a value that does\n * not would be silently ignored by every dialect, or reach DDL as `undefined`),\n * and unless it also carries a dialect key, which makes it two declarations at\n * once. A map is the new form and is\n * held to its whole contract here, where types can be bypassed: only the three\n * dialect keys, at least one of them, each an OWN entry of its own dialect whose\n * type the catalog admits. It is then SNAPSHOT into a frozen map of frozen\n * `{ db, type }` entries, so the caller's object — or an entry it shares with\n * another declaration — can change afterwards without changing this scalar.\n */\nexport function admitNativeType(\n builder: string,\n declaration: NativeTypeDeclaration | undefined\n): NativeTypeDeclaration | undefined {\n return declaration === undefined\n ? undefined\n : admitDeclaredNativeType(builder, declaration);\n}\n\n/** A declared native type, out of line: most scalars declare none. */\nfunction admitDeclaredNativeType(\n builder: string,\n declaration: NativeTypeDeclaration\n): NativeTypeDeclaration {\n if (!isRecord(declaration)) {\n refuse(\n builder,\n \"nativeType\",\n \"A native type is a `{ db, type }` constant or a map of them by dialect (`{ pg, mysql, sqlite }`)\"\n );\n }\n if (isTaggedNativeType(declaration)) {\n const { db, type } = declaration;\n if (!NATIVE_DIALECTS.includes(db) || typeof type !== \"string\") {\n refuse(\n builder,\n \"nativeType\",\n `A tagged native type is \\`{ db, type }\\`: \\`db\\` one of ${NATIVE_DIALECTS.join(\", \")} and \\`type\\` a string`\n );\n }\n const beside = NATIVE_DIALECTS.find((dialect) =>\n Object.hasOwn(declaration, dialect)\n );\n if (beside !== undefined) {\n refuse(\n builder,\n `nativeType.${beside}`,\n `A tagged native type ('db: ${db}') cannot also carry a '${beside}' entry: declare one tagged type, or a map by dialect (\\`{ pg, mysql, sqlite }\\`)`\n );\n }\n return declaration;\n }\n return admitNativeTypeMap(builder, declaration);\n}\n\nfunction admitNativeTypeMap(\n builder: string,\n map: NativeTypeMap\n): NativeTypeMap {\n for (const key of Object.keys(map)) {\n if (!NATIVE_DIALECTS.some((dialect) => dialect === key)) {\n refuse(\n builder,\n `nativeType.${key}`,\n `'${key}' is not a dialect: a native-type map names only ${NATIVE_DIALECTS.join(\", \")}`\n );\n }\n }\n const snapshot: {\n pg?: DialectNativeType<\"pg\">;\n mysql?: DialectNativeType<\"mysql\">;\n sqlite?: DialectNativeType<\"sqlite\">;\n } = {};\n if (Object.hasOwn(map, \"pg\")) snapshot.pg = admitEntry(builder, \"pg\", map.pg);\n if (Object.hasOwn(map, \"mysql\")) {\n snapshot.mysql = admitEntry(builder, \"mysql\", map.mysql);\n }\n if (Object.hasOwn(map, \"sqlite\")) {\n snapshot.sqlite = admitEntry(builder, \"sqlite\", map.sqlite);\n }\n if (Object.keys(snapshot).length === 0) {\n refuse(\n builder,\n \"nativeType\",\n \"A native-type map names at least one dialect; omit the argument to keep every automatic column\"\n );\n }\n return Object.freeze(snapshot);\n}\n\n/** One map entry: a native type of exactly its key's dialect, in its catalog. */\nfunction admitEntry<Entry extends Dialect>(\n builder: string,\n dialect: Entry,\n entry: unknown\n): DialectNativeType<Entry> {\n const db = isRecord(entry) ? entry.db : undefined;\n const type = isRecord(entry) ? entry.type : undefined;\n if (db !== dialect || typeof type !== \"string\") {\n refuse(\n builder,\n `nativeType.${dialect}`,\n `The '${dialect}' entry must be a ${CONSTANT_NAMES[dialect]} native type (\\`{ db: \"${dialect}\", type }\\`)`\n );\n }\n return Object.freeze({ db: dialect, type });\n}\n\n// =============================================================================\n// CATALOG CONSTRUCTION\n// =============================================================================\n\nfunction buildCatalogs(): Record<Dialect, DialectCatalog> {\n const catalogs: Record<Dialect, DialectCatalog> = {\n pg: emptyCatalog(),\n mysql: emptyCatalog(),\n sqlite: emptyCatalog(),\n };\n walk(PG, catalogs.pg);\n walk(MYSQL, catalogs.mysql);\n walk(SQLITE, catalogs.sqlite);\n return catalogs;\n}\n\nfunction emptyCatalog(): DialectCatalog {\n return { exact: new Set(), templates: new Map() };\n}\n\n// The trees are trusted, shipped constants — objects, categories and function\n// leaves, never a primitive or null — so this walk reads their shape directly.\n// The node type is `any` because a walk over a heterogeneous tree erases the\n// leaf types, and narrowing back to them would need the casts the house forbids.\nfunction walk(node: any, catalog: DialectCatalog): void {\n if (typeof node === \"function\") {\n deriveFunction(node, catalog);\n return;\n }\n const type = node.type;\n if (typeof type === \"string\") {\n catalog.exact.add(type);\n return;\n }\n for (const value of Object.values(node)) {\n walk(value, catalog);\n }\n}\n\n/** A parameterized-type leaf, called generically — hence the erased type. */\nfunction deriveFunction(factory: any, catalog: DialectCatalog): void {\n for (const args of PROBE_ARGUMENTS) {\n const type: string = factory(...args).type;\n const open = type.indexOf(\"(\");\n if (open === -1) {\n admit(catalog, type, 0);\n continue;\n }\n // A required-argument function called with too few produces `base(undefined)`\n // — never a value the constant yields — so a non-integer argument is skipped.\n const parts = type.slice(open + 1, -1).split(\",\");\n if (parts.every((part) => INTEGER_ARGUMENT.test(part))) {\n admit(catalog, type.slice(0, open), parts.length);\n }\n }\n}\n\nfunction admit(catalog: DialectCatalog, base: string, arity: number): void {\n const arities = catalog.templates.get(base);\n if (arities === undefined) {\n catalog.templates.set(base, new Set([arity]));\n return;\n }\n arities.add(arity);\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: Keccak-f[1600] is a bit\n// permutation. Every operator below is part of the published specification's\n// arithmetic, carried on 32-bit halves because JavaScript has no 64-bit word.\n\n/**\n * SHA3-512, the one hash VibORM computes.\n *\n * FIPS 202's Keccak-f[1600] over 25 lanes of 64 bits, rate 72 bytes, domain\n * padding `0x06 ... 0x80`. One exported function, no streaming, no options, no\n * configuration: the caller hands over the complete message and receives the\n * 64-byte digest.\n *\n * Each 64-bit lane is carried as TWO 32-bit halves rather than a `BigInt`.\n * JavaScript's bitwise operators are 32-bit, so a BigInt lane would allocate a\n * new arbitrary-precision value for every one of the roughly 1,200 operations a\n * single digest performs.\n *\n * Every read goes through a `DataView`, which is the one indexed read this\n * codebase has that is not `T | undefined`: a Keccak round has no in-range\n * check to make and no branch to take, so a fallback on a typed-array read\n * would be a guard whose coverage cannot be named. The halves are stored\n * little-endian at `lane * 8` and `lane * 8 + 4`, which is exactly the lane's\n * own little-endian byte layout — so absorbing a block is a word-wise XOR of\n * the message and squeezing is a copy of the first 64 bytes.\n *\n * The one caller is CUID2 (`@schema/scalars/string/autogenerate`). Nothing else\n * in VibORM may import this module without its own differential proof against a\n * reference implementation.\n */\n\n/** SHA3-512's rate: 1600 - 2*512 bits, as bytes. */\nconst RATE_BYTES = 72;\n/** 512 bits of output. */\nconst DIGEST_BYTES = 64;\nconst LANES = 25;\nconst STATE_BYTES = LANES * 8;\nconst ROUNDS = 24;\n/** SHA-3's domain separation: `01` then the pad10*1 rule's leading bit. */\nconst DOMAIN_PAD = 0x06;\n/** pad10*1's trailing bit, at the top of the block's last byte. */\nconst FINAL_PAD = 0x80;\n\n/**\n * The iota round constants, low half then high half of each round.\n *\n * Filled through the same little-endian writes every other buffer in this\n * module is filled with. A typed array would lay its bytes out in the HOST's\n * order, which is not what the read at the iota step asks for: the two would\n * agree on a little-endian machine and disagree on every other one.\n */\nconst ROUND_CONSTANTS = new DataView(new ArrayBuffer(ROUNDS * 8));\nfor (const [half, constant] of [\n 0x00_00_00_01, 0x00_00_00_00, 0x00_00_80_82, 0x00_00_00_00, 0x00_00_80_8a,\n 0x80_00_00_00, 0x80_00_80_00, 0x80_00_00_00, 0x00_00_80_8b, 0x00_00_00_00,\n 0x80_00_00_01, 0x00_00_00_00, 0x80_00_80_81, 0x80_00_00_00, 0x00_00_80_09,\n 0x80_00_00_00, 0x00_00_00_8a, 0x00_00_00_00, 0x00_00_00_88, 0x00_00_00_00,\n 0x80_00_80_09, 0x00_00_00_00, 0x80_00_00_0a, 0x00_00_00_00, 0x80_00_80_8b,\n 0x00_00_00_00, 0x00_00_00_8b, 0x80_00_00_00, 0x00_00_80_89, 0x80_00_00_00,\n 0x00_00_80_03, 0x80_00_00_00, 0x00_00_80_02, 0x80_00_00_00, 0x00_00_00_80,\n 0x80_00_00_00, 0x00_00_80_0a, 0x00_00_00_00, 0x80_00_00_0a, 0x80_00_00_00,\n 0x80_00_80_81, 0x80_00_00_00, 0x00_00_80_80, 0x80_00_00_00, 0x80_00_00_01,\n 0x00_00_00_00, 0x80_00_80_08, 0x80_00_00_00,\n].entries()) {\n ROUND_CONSTANTS.setInt32(half * 4, constant, true);\n}\n\n/** Rho: the rotation each lane receives, indexed by `x + 5y`. */\nconst ROTATIONS = new DataView(\n new Uint8Array([\n 0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8,\n 18, 2, 61, 56, 14,\n ]).buffer\n);\n\n/** Pi: where lane `x + 5y` lands, which is `y + 5*((2x + 3y) mod 5)`. */\nconst DESTINATIONS = new DataView(\n new Uint8Array([\n 0, 10, 20, 5, 15, 16, 1, 11, 21, 6, 7, 17, 2, 12, 22, 23, 8, 18, 3, 13, 14,\n 24, 9, 19, 4,\n ]).buffer\n);\n\n/**\n * The permutation state and its two scratch planes, allocated once.\n *\n * `sha3_512` is synchronous from entry to return and this module has no other\n * caller, so one set of buffers is reused rather than allocating a hundred\n * slots per identifier. Every entry begins by zeroing the state.\n */\nconst stateBytes = new Uint8Array(STATE_BYTES);\nconst state = new DataView(stateBytes.buffer);\nconst plane = new DataView(new ArrayBuffer(STATE_BYTES));\nconst column = new DataView(new ArrayBuffer(5 * 8));\n\n/**\n * Keccak-f[1600]: 24 rounds of theta, rho + pi, chi and iota.\n *\n * A rotation by `n < 32` takes its missing bits from the other half at\n * `32 - n`; a rotation by `n > 32` is the same shape with the halves swapped\n * and `n - 32`. Neither case is reachable with `n = 0` or `n = 32`, which would\n * need a 32-bit shift JavaScript does not have: rho's only zero is lane 0,\n * which is skipped, and 32 is not one of its offsets.\n */\nfunction permute(): void {\n for (let round = 0; round < ROUNDS; round++) {\n // Theta: each column's parity, folded back into every lane of the column.\n for (let x = 0; x < 5; x++) {\n let low = 0;\n let high = 0;\n for (let y = 0; y < LANES; y += 5) {\n low ^= state.getInt32((x + y) * 8, true);\n high ^= state.getInt32((x + y) * 8 + 4, true);\n }\n column.setInt32(x * 8, low, true);\n column.setInt32(x * 8 + 4, high, true);\n }\n for (let x = 0; x < 5; x++) {\n const nextLow = column.getInt32(((x + 1) % 5) * 8, true);\n const nextHigh = column.getInt32(((x + 1) % 5) * 8 + 4, true);\n const deltaLow =\n column.getInt32(((x + 4) % 5) * 8, true) ^\n ((nextLow << 1) | (nextHigh >>> 31));\n const deltaHigh =\n column.getInt32(((x + 4) % 5) * 8 + 4, true) ^\n ((nextHigh << 1) | (nextLow >>> 31));\n for (let y = 0; y < LANES; y += 5) {\n const at = (x + y) * 8;\n state.setInt32(at, state.getInt32(at, true) ^ deltaLow, true);\n state.setInt32(at + 4, state.getInt32(at + 4, true) ^ deltaHigh, true);\n }\n }\n\n // Rho and pi: rotate every lane, then move it to its permuted position.\n plane.setInt32(0, state.getInt32(0, true), true);\n plane.setInt32(4, state.getInt32(4, true), true);\n for (let lane = 1; lane < LANES; lane++) {\n const shift = ROTATIONS.getUint8(lane);\n const low = state.getInt32(lane * 8, true);\n const high = state.getInt32(lane * 8 + 4, true);\n const target = DESTINATIONS.getUint8(lane) * 8;\n if (shift < 32) {\n plane.setInt32(target, (low << shift) | (high >>> (32 - shift)), true);\n plane.setInt32(\n target + 4,\n (high << shift) | (low >>> (32 - shift)),\n true\n );\n } else {\n const rest = shift - 32;\n plane.setInt32(target, (high << rest) | (low >>> (32 - rest)), true);\n plane.setInt32(\n target + 4,\n (low << rest) | (high >>> (32 - rest)),\n true\n );\n }\n }\n\n // Chi: each lane against the next two in its row.\n for (let y = 0; y < LANES; y += 5) {\n for (let x = 0; x < 5; x++) {\n const at = (y + x) * 8;\n const next = (y + ((x + 1) % 5)) * 8;\n const after = (y + ((x + 2) % 5)) * 8;\n state.setInt32(\n at,\n plane.getInt32(at, true) ^\n (~plane.getInt32(next, true) & plane.getInt32(after, true)),\n true\n );\n state.setInt32(\n at + 4,\n plane.getInt32(at + 4, true) ^\n (~plane.getInt32(next + 4, true) & plane.getInt32(after + 4, true)),\n true\n );\n }\n }\n\n // Iota: the round constant, on the first lane only.\n state.setInt32(\n 0,\n state.getInt32(0, true) ^ ROUND_CONSTANTS.getInt32(round * 8, true),\n true\n );\n state.setInt32(\n 4,\n state.getInt32(4, true) ^ ROUND_CONSTANTS.getInt32(round * 8 + 4, true),\n true\n );\n }\n}\n\n/** Absorb one complete rate-sized block and run the permutation. */\nfunction absorb(block: DataView, offset: number): void {\n for (let at = 0; at < RATE_BYTES; at += 4) {\n state.setInt32(\n at,\n state.getInt32(at, true) ^ block.getInt32(offset + at, true),\n true\n );\n }\n permute();\n}\n\n/**\n * The SHA3-512 digest of one complete message.\n *\n * Byte-identical to the reference implementation for every input, which a\n * differential test pins against the NIST known-answer vectors and 10,000\n * random messages crossing every rate boundary.\n */\nexport function sha3_512(bytes: Uint8Array): Uint8Array {\n stateBytes.fill(0);\n\n const length = bytes.length;\n const message = new DataView(bytes.buffer, bytes.byteOffset, length);\n const wholeBlocks = Math.floor(length / RATE_BYTES);\n for (let block = 0; block < wholeBlocks; block++) {\n absorb(message, block * RATE_BYTES);\n }\n\n // The final block is the message tail plus pad10*1. A tail of exactly\n // `RATE_BYTES - 1` puts both pad bits in the same byte, which is the rule\n // rather than a special case.\n const tail = new Uint8Array(RATE_BYTES);\n const tailLength = length - wholeBlocks * RATE_BYTES;\n tail.set(bytes.subarray(wholeBlocks * RATE_BYTES));\n tail[tailLength] = DOMAIN_PAD;\n tail[RATE_BYTES - 1] =\n tailLength === RATE_BYTES - 1 ? DOMAIN_PAD | FINAL_PAD : FINAL_PAD;\n absorb(new DataView(tail.buffer), 0);\n\n // 512 bits is narrower than the rate, so one squeeze with no further\n // permutation is the whole digest — and the halves are already stored in the\n // little-endian order the digest is written in.\n return Uint8Array.from(stateBytes.subarray(0, DIGEST_BYTES));\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: NanoID selects a\n// character with `byte & 63`, the ULID counter carries a byte at a time, and\n// CUID2's digest is read as one big-endian integer. All three are bit layouts.\n\n/**\n * The six identifier generators a string scalar can declare.\n *\n * Each `default*` function is the DECLARATION: it validates what the modifier\n * was spelled with and returns the closure the scalar stores as its default.\n * The closure is what runs per row, synchronously, inside the field's own\n * create schema — so nothing here may be asynchronous, and nothing here may\n * draw entropy before it is called.\n *\n * The byte layouts, alphabets, widths and the one entropy source live in\n * `@validation/primitives/id-formats`, where the storage codec can read them\n * without pulling a scalar class. This module owns only what a GENERATOR adds\n * to a format: the clock it reads, the state it keeps between calls, and the\n * prefix it puts in front of the payload.\n */\n\nimport {\n applyIdPrefix,\n bytesToKsuid,\n bytesToUlid,\n bytesToUuid,\n KSUID_PAYLOAD_LENGTH,\n ksuidBytes,\n MAX_RANDOM_BYTES,\n NANOID_ALPHABET,\n NANOID_DEFAULT_LENGTH,\n randomBytes,\n refuseId,\n ULID_RANDOM_LENGTH,\n UUID_BYTE_LENGTH,\n UUIDV7_RANDOM_LENGTH,\n ulidBytes,\n uuidV4Bytes,\n uuidV7Bytes,\n} from \"@validation/primitives/id-formats\";\nimport { sha3_512 } from \"@validation/primitives/sha3\";\n\nconst MILLISECONDS_PER_SECOND = 1000;\n\n// =============================================================================\n// UUID\n// =============================================================================\n\n/**\n * A UUIDv4.\n *\n * `crypto.randomUUID()` when the runtime has it — it is the platform's own\n * implementation of exactly this format, and it is measurably faster than\n * drawing bytes and tagging them. The manual path is not a fallback to a weaker\n * value: it is the same 122 random bits with the same version and variant, from\n * the same entropy source, for runtimes that expose `getRandomValues` without\n * `randomUUID`.\n */\nfunction uuidV4(): string {\n const source = globalThis.crypto;\n if (typeof source?.randomUUID === \"function\") return source.randomUUID();\n return bytesToUuid(uuidV4Bytes(randomBytes(UUID_BYTE_LENGTH, \"uuid\")));\n}\n\nexport const defaultUuid = (prefix?: string) => () =>\n applyIdPrefix(prefix, uuidV4());\n\nexport const defaultUuidV7 = (prefix?: string) => () =>\n applyIdPrefix(\n prefix,\n bytesToUuid(\n uuidV7Bytes(Date.now(), randomBytes(UUIDV7_RANDOM_LENGTH, \"uuidv7\"))\n )\n );\n\n// =============================================================================\n// ULID\n// =============================================================================\n\n/** The next 80-bit random block, or a refusal when the block is exhausted. */\nfunction incrementUlidRandom(random: Uint8Array): Uint8Array {\n const next = Uint8Array.from(random);\n const view = new DataView(next.buffer);\n for (let index = next.length - 1; index >= 0; index--) {\n const incremented = view.getUint8(index) + 1;\n view.setUint8(index, incremented & 255);\n if (incremented <= 255) return next;\n }\n return refuseId(\n \"s.string().ulid\",\n \"generate\",\n \"This process issued every ULID one millisecond can hold (2^80). Monotonicity cannot be preserved without emitting a smaller identifier\"\n );\n}\n\n/**\n * One monotonic ULID sequence.\n *\n * Within a millisecond the timestamp repeats, so the 80-bit random block is\n * INCREMENTED instead of redrawn: two ULIDs minted in the same millisecond\n * still sort in the order they were issued. A clock that moves backwards keeps\n * emitting the last timestamp for the same reason — a smaller identifier would\n * break the ordering the format promises, and the ORM cannot fix the clock.\n *\n * The whole block is drawn at once from secure bytes, so every bit is uniform.\n *\n * `now` and `random` are injectable because monotonicity, rollback and\n * exhaustion are statements about a SEQUENCE, and a sequence cannot be observed\n * through a real clock. The process-wide generator below takes the defaults.\n */\nexport function createUlidGenerator(\n options: { now?: () => number; random?: (length: number) => Uint8Array } = {}\n): () => string {\n const now = options.now ?? Date.now;\n const draw = options.random ?? ((length) => randomBytes(length, \"ulid\"));\n let last: { time: number; random: Uint8Array } | undefined;\n return () => {\n const time = now();\n last =\n last !== undefined && time <= last.time\n ? { time: last.time, random: incrementUlidRandom(last.random) }\n : { time, random: draw(ULID_RANDOM_LENGTH) };\n return bytesToUlid(ulidBytes(last.time, last.random));\n };\n}\n\n/**\n * ONE monotonic sequence per process, shared by every `.ulid()` and `.id()`\n * field. Monotonicity is a property of the issuing process, not of a field: two\n * models minting ULIDs in the same millisecond must not collide, and a\n * per-field sequence would let them.\n */\nconst nextUlid = createUlidGenerator();\n\nexport const defaultUlid = (prefix?: string) => () =>\n applyIdPrefix(prefix, nextUlid());\n\n// =============================================================================\n// KSUID\n// =============================================================================\n\nexport const defaultKsuid = (prefix?: string) => () =>\n applyIdPrefix(\n prefix,\n bytesToKsuid(\n ksuidBytes(\n Math.floor(Date.now() / MILLISECONDS_PER_SECOND),\n randomBytes(KSUID_PAYLOAD_LENGTH, \"ksuid\")\n )\n )\n );\n\n// =============================================================================\n// NANOID\n// =============================================================================\n\n/**\n * The lengths a nanoid can have, refused where the length is spelled.\n *\n * One character costs one byte of entropy, so the upper bound is the entropy\n * source's own per-call quota: asking for more used to declare cleanly and then\n * throw a raw `QuotaExceededError` from inside the closure, at row-create time,\n * for every row.\n */\nexport const defaultNanoid = (length?: number, prefix?: string) => {\n const size = length ?? NANOID_DEFAULT_LENGTH;\n if (!Number.isInteger(size) || size < 1 || size > MAX_RANDOM_BYTES) {\n refuseId(\n \"s.string().nanoid\",\n \"length\",\n `A nanoid length must be a whole number of characters between 1 and ${MAX_RANDOM_BYTES}; received ${size}`\n );\n }\n return () => {\n let id = \"\";\n for (const byte of randomBytes(size, \"nanoid\")) {\n id += NANOID_ALPHABET.charAt(byte & 63);\n }\n return applyIdPrefix(prefix, id);\n };\n};\n\n// =============================================================================\n// CUID2\n// =============================================================================\n\n/*\n * The CUID2 construction below is a port of @paralleldrive/cuid2 3.3.0, kept\n * byte-identical to it so that identifiers minted by VibORM and identifiers\n * minted by the upstream package belong to the same space. What changed is the\n * arithmetic (native `BigInt` in place of bignumber.js), the entropy source\n * (secure bytes only, never `Math.random()`), and the fingerprint's global\n * object (`globalThis`, which every supported runtime has). A differential test\n * pins the rest against the upstream package.\n *\n * MIT License\n *\n * Copyright (c) 2022 Eric Elliott\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nconst CUID_DEFAULT_LENGTH = 24;\nconst CUID_BIG_LENGTH = 32;\nconst CUID_ALPHABET_SIZE = 26;\nconst BASE36 = 36;\n/** ~22k hosts before a 50% chance of an initial counter collision (upstream). */\nconst CUID_INITIAL_COUNT_MAX = 476_782_367;\n\nconst TEXT_ENCODER = new TextEncoder();\nconst LOWERCASE_LETTERS = \"abcdefghijklmnopqrstuvwxyz\";\n\n/** A float in `[0, 1)` from four secure bytes, read as one 32-bit word. */\nfunction secureFloat(): number {\n const bytes = randomBytes(4, \"cuid\");\n const word = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n return word.getUint32(0, true) / 0x1_00_00_00_00;\n}\n\nfunction createEntropy(length: number, random: () => number): string {\n let entropy = \"\";\n while (entropy.length < length) {\n entropy += Math.floor(random() * BASE36).toString(BASE36);\n }\n return entropy;\n}\n\n/**\n * SHA3-512 of `input`, rendered in base36 with the first digit dropped — that\n * digit is biased toward the low end of the alphabet because the digest is not\n * a whole number of base36 digits.\n */\nfunction hashBase36(input: string): string {\n let value = 0n;\n for (const byte of sha3_512(TEXT_ENCODER.encode(input))) {\n value = (value << 8n) | BigInt(byte);\n }\n return value.toString(BASE36).slice(1);\n}\n\n/**\n * A fingerprint of the host environment, mixed into every id so that two\n * processes minting ids at the same millisecond with the same counter still\n * disagree.\n */\nfunction createFingerprint(random: () => number): string {\n const globals = Object.keys(globalThis).toString();\n const entropy = createEntropy(CUID_BIG_LENGTH, random);\n // Upstream writes `globals.length > 0 ? globals + entropy : entropy`. The two\n // arms are the same string — concatenating an empty `globals` IS `entropy` —\n // so the condition names no case, and a branch whose unique coverage cannot\n // be stated is one this codebase does not keep. The digest is unchanged,\n // which the differential test against the pinned upstream package proves.\n return hashBase36(globals + entropy).substring(0, CUID_BIG_LENGTH);\n}\n\n/**\n * One CUID2 sequence.\n *\n * Everything upstream lets a caller replace is replaceable here for the same\n * reason: the fingerprint, counter and random source are the parts that make\n * two processes differ, and a test that cannot fix them cannot compare two\n * implementations at all. `length` is replaceable for the same reason — the\n * salt is as long as the id, so a differential test that only ever saw 24\n * characters would compare one input shape.\n *\n * No length is spellable in a schema: `.cuid(prefix?)` takes none and always\n * mints the published 24, and a schema document that declares one is refused by\n * the reader (J007). The construction therefore states no bound of its own.\n */\nexport function createCuid2(\n options: {\n random?: () => number;\n counter?: () => number;\n length?: number;\n fingerprint?: string;\n } = {}\n): () => string {\n const random = options.random ?? secureFloat;\n const counter =\n options.counter ??\n createCounter(Math.floor(random() * CUID_INITIAL_COUNT_MAX));\n const length = options.length ?? CUID_DEFAULT_LENGTH;\n const fingerprint = options.fingerprint ?? createFingerprint(random);\n return () => {\n const firstLetter = LOWERCASE_LETTERS.charAt(\n Math.floor(random() * CUID_ALPHABET_SIZE)\n );\n const time = Date.now().toString(BASE36);\n const count = counter().toString(BASE36);\n const salt = createEntropy(length, random);\n return (\n firstLetter +\n hashBase36(time + salt + count + fingerprint).substring(1, length)\n );\n };\n}\n\nfunction createCounter(start: number): () => number {\n let count = start;\n return () => {\n const current = count;\n count++;\n return current;\n };\n}\n\n/**\n * The process-wide CUID2 sequence, built on first use.\n *\n * Lazily, because the fingerprint hashes 32 characters of entropy: building it\n * at import would draw randomness from every process that merely loads VibORM,\n * including ones that never mint an id.\n */\nlet processCuid: (() => string) | undefined;\n\nexport const defaultCuid = (prefix?: string) => () =>\n applyIdPrefix(prefix, (processCuid ??= createCuid2())());\n","// String Scalar\n// Standalone scalar class with State generic pattern\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { hasIdPrefix, refuseId } from \"@validation/primitives/id-formats\";\nimport v from \"@validation/primitives/v\";\nimport {\n type AutoGenerate,\n createDefaultState,\n type DefaultValueInput,\n type GeneratorDefaultBrand,\n generatorDefault,\n isGeneratorDefault,\n nullableDefault,\n refuseListGenerator,\n type ScalarState,\n type UpdateState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\nimport {\n defaultCuid,\n defaultKsuid,\n defaultNanoid,\n defaultUlid,\n defaultUuid,\n defaultUuidV7,\n} from \"./autogenerate\";\n\ninterface FormatOptions {\n prefix?: string;\n generate?: true;\n}\ninterface NanoidOptions extends FormatOptions {\n length?: number;\n}\ninterface KeyOptions {\n generate: false;\n prefix?: string;\n}\ntype IdentifierKind = \"uuid\" | \"uuidv7\" | \"ulid\" | \"ksuid\" | \"nanoid\" | \"cuid\";\ntype ExactOptions<Given, Allowed> = Given extends string | number | undefined\n ? unknown\n : Record<Exclude<keyof Given, keyof Allowed>, never>;\ntype GenerationRequested<\n State extends ScalarState<\"string\">,\n Given,\n> = Given extends { generate: true }\n ? true\n : Given extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends { generate: true }\n ? true\n : State[\"isId\"];\ntype GenerationChoice<\n State extends ScalarState<\"string\">,\n Given,\n> = Given extends { generate: true }\n ? true\n : Given extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends {\n generate: infer Choice extends boolean | undefined;\n }\n ? Choice\n : undefined;\ntype HasCustomDefault<State extends ScalarState<\"string\">> =\n State[\"default\"] extends GeneratorDefaultBrand ? false : State[\"hasDefault\"];\ntype FormatState<\n State extends ScalarState<\"string\">,\n Given,\n Kind extends IdentifierKind = IdentifierKind,\n> = {\n autoGenerate: AutoGenerate & {\n kind: Kind;\n implicit?: undefined;\n generate: GenerationChoice<State, Given>;\n };\n hasDefault: HasCustomDefault<State> extends true\n ? true\n : GenerationRequested<State, Given>;\n optional: HasCustomDefault<State> extends true\n ? true\n : GenerationRequested<State, Given>;\n default: HasCustomDefault<State> extends true\n ? State[\"default\"]\n : GenerationRequested<State, Given> extends true\n ? (() => string) & GeneratorDefaultBrand\n : undefined;\n};\ntype KeyState<State extends ScalarState<\"string\">, Given> = Omit<\n FormatState<UpdateState<State, { isId: true }>, Given>,\n \"autoGenerate\"\n> & {\n isId: true;\n isUnique: true;\n autoGenerate: State[\"autoGenerate\"] extends AutoGenerate\n ? Omit<State[\"autoGenerate\"], \"generate\"> & {\n generate: GenerationChoice<State, Given>;\n }\n : {\n kind: \"ulid\";\n implicit: true;\n prefix?: string;\n generate: GenerationChoice<State, Given>;\n };\n};\n\nfunction identifierGenerator(declaration: AutoGenerate): () => string {\n const { kind, prefix, length } = declaration;\n switch (kind) {\n case \"uuid\":\n return defaultUuid(prefix);\n case \"uuidv7\":\n return defaultUuidV7(prefix);\n case \"ulid\":\n return defaultUlid(prefix);\n case \"ksuid\":\n return defaultKsuid(prefix);\n case \"nanoid\":\n return defaultNanoid(length, prefix);\n case \"cuid\":\n return defaultCuid(prefix);\n default:\n return refuseId(\n \"s.string\",\n \"generate\",\n \"This generator is not a string identifier format\"\n );\n }\n}\n\nconst stringBase = v.string();\n\nexport class StringScalar<State extends ScalarState<\"string\">> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n nullable() {\n return new StringScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.string<{\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }>({\n nullable: true,\n array: this.state.array,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n array() {\n if (isGeneratorDefault(this.state.default)) refuseListGenerator(\"s.string\");\n return new StringScalar(\n updateState(this, {\n array: true,\n base: v.string<{\n nullable: State[\"nullable\"];\n array: true;\n schema: State[\"schema\"];\n }>({\n nullable: this.state.nullable,\n array: true,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n id<const Given extends string | KeyOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, KeyOptions>\n ): StringScalar<UpdateState<State, KeyState<State, Given>>>;\n id(options?: string | KeyOptions): StringScalar<ScalarState<\"string\">> {\n const generate = typeof options === \"object\" ? options.generate : undefined;\n const prefix = typeof options === \"string\" ? options : options?.prefix;\n const declared = this.state.autoGenerate;\n if (declared && hasIdPrefix(prefix)) refuseSecondIdPrefix(declared);\n const declaration: AutoGenerate = declared\n ? { ...declared, generate: generate ?? declared.generate }\n : { kind: \"ulid\", prefix, implicit: true, generate };\n return this.withIdentifier(declaration, true);\n }\n\n unique() {\n return new StringScalar(\n updateState(this, {\n isUnique: true,\n }),\n this._nativeType\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new StringScalar(\n updateState(this, {\n hasDefault: true,\n default: value,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n schema<S extends StandardSchemaV1<string>>(schema: S) {\n return new StringScalar(\n updateState(this, {\n schema,\n base: v.string<{\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }>({\n nullable: this.state.nullable,\n array: this.state.array,\n schema,\n }),\n }),\n this._nativeType\n );\n }\n\n /**\n * Maps this scalar to a custom column name in the database\n */\n map(columnName: string) {\n return new StringScalar(\n updateState(this, { columnName }),\n this._nativeType\n );\n }\n\n uuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"uuid\">>>;\n uuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"uuid\", options);\n }\n\n uuidv7<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"uuidv7\">>>;\n uuidv7(\n options?: string | FormatOptions\n ): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"uuidv7\", options);\n }\n\n ksuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"ksuid\">>>;\n ksuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"ksuid\", options);\n }\n\n ulid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"ulid\">>>;\n ulid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"ulid\", options);\n }\n\n cuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"cuid\">>>;\n cuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"cuid\", options);\n }\n\n nanoid<const Given extends number | NanoidOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, NanoidOptions>,\n prefix?: string\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"nanoid\">>>;\n nanoid(\n options?: number | NanoidOptions,\n prefix?: string\n ): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\n \"nanoid\",\n typeof options === \"number\"\n ? { length: options, prefix }\n : (options ?? { prefix })\n );\n }\n\n private withFormat(kind: IdentifierKind, options?: string | NanoidOptions) {\n const configuration: NanoidOptions | undefined =\n typeof options === \"string\" ? { prefix: options } : options;\n return this.withIdentifier(\n {\n kind,\n prefix: configuration?.prefix,\n length: kind === \"nanoid\" ? configuration?.length : undefined,\n generate: configuration?.generate ?? this.state.autoGenerate?.generate,\n },\n this.state.isId\n );\n }\n\n private withIdentifier(declaration: AutoGenerate, isId: boolean) {\n const generator = identifierGenerator(declaration);\n const customDefault =\n this.state.hasDefault && !isGeneratorDefault(this.state.default);\n const generate =\n declaration.generate === true || (isId && declaration.generate !== false);\n const installed = generate && !customDefault;\n if (this.state.array && installed) refuseListGenerator(\"s.string\");\n return new StringScalar(\n updateState(this, {\n isId,\n isUnique: isId || this.state.isUnique,\n autoGenerate: declaration,\n hasDefault: customDefault || installed,\n optional: customDefault || installed,\n default: installed\n ? generatorDefault(generator)\n : customDefault\n ? this.state.default\n : undefined,\n }),\n this._nativeType\n );\n }\n\n private _internal?: {\n state: State;\n nativeType: NativeTypeDeclaration | undefined;\n };\n\n get [\"~\"]() {\n return (this._internal ??= {\n state: this.state,\n nativeType: this._nativeType,\n });\n }\n}\n\nexport const string = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) => {\n return new StringScalar(\n createDefaultState(\"string\", stringBase),\n admitNativeType(\"s.string\", nativeType)\n );\n};\n\nfunction refuseSecondIdPrefix(declared: {\n readonly kind: string;\n readonly prefix?: string | undefined;\n}): never {\n return refuseId(\n \"s.string().id\",\n \"prefix\",\n `This field already declares a '${declared.kind}' generator${declared.prefix ? ` with the prefix '${declared.prefix}'` : \"\"}. A prefix is spelled once, on the call that declares the format`\n );\n}\n"],"mappings":"8dAWA,SAAgB,mCACd,EACmC,CACnC,IAAM,EAAoB,IAAI,IAC9B,IAAK,GAAM,CAAC,EAAU,KAAU,EAAe,CAC7C,GAEE,OAAO,GAAU,WADjB,GAEA,CAAC,EAAM,MAAM,OACb,CAAC,EAAM,MAAM,OAAO,QAEpB,MAAO,CACL,KAAM,OACN,QAAS,iBAAiB,EAAS,iFACnC,SAAU,QACV,MAAO,EACR,CACH,IAAM,EAAU,EAAM,KAAK,MAAM,IAAM,EAAkB,IAAI,EAAM,CACnE,GAAI,IAAY,IAAA,IAAa,IAAY,EACvC,OAAO,wBAAwB,EAAS,EAAS,CACnD,EAAkB,IAAI,EAAO,EAAS,EAK1C,SAAS,wBACP,EACA,EACuB,CACvB,MAAO,CACL,KAAM,OACN,QAAS,wBAAwB,EAAQ,kCAAkC,EAAS,0CACpF,SAAU,QACV,MAAO,EACR,CC1CH,IAAa,sBAAb,cAA2C,CAAY,CACrD,OAAyB,eAAiB,wBAG1C,OAEA,YACE,EACA,EACA,CAIA,IAAM,EAAW,OAAO,OACtB,EAAO,IAAK,GACV,OAAO,OACL,EAAM,WACF,CAAE,GAAG,EAAO,WAAY,OAAO,OAAO,CAAC,GAAG,EAAM,WAAW,CAAC,CAAE,CAC9D,CAAE,GAAG,EAAO,CACjB,CACF,CACF,CACK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,OAAQ,EAAS,CAAG,EACtD,OAAO,KAAK,eACV,CACE,OACA,OAAQ,GAAe,OACvB,OAAQ,IAAS,SAAW,GAAe,OAAS,IAAA,GACpD,SAAU,GAAe,UAAY,KAAK,MAAM,cAAc,SAC/D,CACD,KAAK,MAAM,KACZ,CAGH,eAAuB,EAA2B,EAAe,CAC/D,IAAM,EAAY,oBAAoB,EAAY,CAC5C,EACJ,KAAK,MAAM,YAAc,CAAC,mBAAmB,KAAK,MAAM,QAAQ,CAG5D,GADJ,EAAY,WAAa,IAAS,GAAQ,EAAY,WAAa,KACvC,CAAC,EAE/B,OADI,KAAK,MAAM,OAAS,GAAW,oBAAoB,WAAW,CAC3D,IAAI,aACT,YAAY,KAAM,CAChB,OACA,SAAU,GAAQ,KAAK,MAAM,SAC7B,aAAc,EACd,WAAY,GAAiB,EAC7B,SAAU,GAAiB,EAC3B,QAAS,EACL,iBAAiB,EAAU,CAC3B,EACE,KAAK,MAAM,QACX,IAAA,GACP,CAAC,CACF,KAAK,YACN,CAGH,UAKA,GAAK,KAAO,CACV,MAAQ,MAAK,YAAc,CACzB,MAAO,KAAK,MACZ,WAAY,KAAK,YAClB,GAIL,MAAa,OAIX,GAEO,IAAI,EACT,mBAAmB,SAAU,EAAW,CACxC,gBAAgB,WAAY,EAAW,CACxC,CAGH,SAAS,qBAAqB,EAGpB,CACR,OAAO,EACL,gBACA,SACA,kCAAkC,EAAS,KAAK,aAAa,EAAS,OAAS,qBAAqB,EAAS,OAAO,GAAK,GAAG,kEAC7H"}
|
|
1
|
+
{"version":3,"file":"scalar-DNshDNz3.mjs","names":["state","catalogs","v","state"],"sources":["../src/schema/registration-preflight.ts","../src/schema/validation/error.ts","../src/schema/scalars/common.ts","../src/schema/scalars/native-catalog.ts","../src/validation/primitives/sha3.ts","../src/schema/scalars/string/autogenerate.ts","../src/schema/scalars/string/scalar.ts"],"sourcesContent":["import type { Model } from \"./model\";\nimport type { SchemaValidationIssue } from \"./validation/types\";\n\n/**\n * Prove that every model object in one registration batch has one schema key.\n *\n * The model's hydrated name is the lifetime claim. The local map covers the\n * still-unhydrated batch, so `{ alpha: shared, beta: shared }` is refused before\n * hydration writes either name. Repeating the same object under the same key is\n * deliberately idempotent.\n */\nexport function preflightModelRegistrationIdentity(\n registrations: Iterable<readonly [string, Model<any>]>\n): SchemaValidationIssue | undefined {\n const claimedInThisPass = new Map<Model<any>, string>();\n for (const [modelKey, model] of registrations) {\n if (\n model === null ||\n typeof model !== \"object\" ||\n !model[\"~\"]?.names ||\n !model[\"~\"]?.state?.scalars\n )\n return {\n code: \"M008\",\n message: `Schema entry '${modelKey}' is not a model; pass an explicit object containing only s.model() definitions`,\n severity: \"error\",\n model: modelKey,\n };\n const claimed = model[\"~\"].names.ts ?? claimedInThisPass.get(model);\n if (claimed !== undefined && claimed !== modelKey)\n return doubleRegistrationIssue(claimed, modelKey);\n claimedInThisPass.set(model, modelKey);\n }\n return undefined;\n}\n\nfunction doubleRegistrationIssue(\n claimed: string,\n modelKey: string\n): SchemaValidationIssue {\n return {\n code: \"M003\",\n message: `Model registered as '${claimed}' cannot also be registered as '${modelKey}'; one model object binds one schema key`,\n severity: \"error\",\n model: modelKey,\n };\n}\n","import { VibORMError, VibORMErrorCode } from \"../../errors/base\";\nimport type { SchemaValidationIssue } from \"./types\";\n\nexport class SchemaValidationError extends VibORMError {\n static override readonly diagnosticName = \"SchemaValidationError\";\n\n declare readonly code: typeof VibORMErrorCode.INVALID_INPUT;\n readonly issues: readonly SchemaValidationIssue[];\n\n constructor(\n issues: readonly SchemaValidationIssue[],\n options?: { cause?: Error | undefined }\n ) {\n // `candidates` is the one array-valued field, so the snapshot freezes it\n // too: a shallow freeze would publish an immutable issue wrapping a\n // caller-mutable list.\n const snapshot = Object.freeze(\n issues.map((issue) =>\n Object.freeze(\n issue.candidates\n ? { ...issue, candidates: Object.freeze([...issue.candidates]) }\n : { ...issue }\n )\n )\n );\n const messages = snapshot.map((issue) =>\n [\n `[${issue.code}] ${issue.message}`,\n issue.candidates?.length\n ? `Candidates: ${issue.candidates.join(\", \")}`\n : \"\",\n issue.repair ?? \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\")\n );\n super(\n `Schema validation failed:\\n${messages.join(\"\\n\")}`,\n VibORMErrorCode.INVALID_INPUT,\n options?.cause ? { cause: options.cause } : undefined\n );\n this.issues = snapshot;\n }\n\n override toJSON(): Record<string, unknown> {\n return { ...super.toJSON(), issues: this.issues };\n }\n}\n\nexport function isSchemaValidationError(\n error: unknown\n): error is SchemaValidationError {\n return error instanceof SchemaValidationError;\n}\n\n/**\n * ONE reading of a value pulled out of a `catch`, shared by every gate boundary\n * that turns a throw into a diagnostic.\n *\n * The throwers this gate catches are all in-repo and all throw `Error`s — the\n * target once-cell normalizes before the resolver ever sees a getter's throw,\n * and the physical-name owner throws its own error type. Each catch site\n * spelling this narrowing itself made three owners for one rule and three arms\n * that no schema can reach; the narrowing lives here instead, where it is\n * witnessed directly.\n */\nexport function thrownAsError(thrown: unknown): Error {\n return thrown instanceof Error ? thrown : new Error(String(thrown));\n}\n","// Common Scalar Utilities\n// Shared types and helpers for all scalar classes\n\nimport { ValidationError } from \"@errors\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { InferInput, VibSchema } from \"@validation\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport type { Scalar } from \"./base\";\n\n// =============================================================================\n// SCHEMA NAMES (hydrated by client at initialization)\n// =============================================================================\n\n/**\n * Name slots for models, scalars, and relations.\n * These are hydrated by the client at initialization time when the full\n * schema context is available.\n *\n * - ts: TypeScript/schema key name (e.g., \"email\", \"User\")\n * - sql: Resolved database name (e.g., \"email_column\", \"users\")\n */\nexport interface SchemaNames {\n /** TypeScript key name in the schema */\n ts?: string;\n /** Resolved SQL name (column/table) */\n sql?: string;\n}\n\n/**\n * Hydrated schema names - guaranteed to have both ts and sql defined.\n * Returned by model[\"~\"].getFieldName() for scalar keys.\n */\nexport interface HydratedSchemaNames {\n /** TypeScript key name in the schema */\n ts: string;\n /** Resolved SQL name (column/table) */\n sql: string;\n}\n\n// =============================================================================\n// SCALAR TYPES\n// =============================================================================\n\nexport type ScalarType =\n | \"string\"\n | \"int\"\n | \"number\"\n | \"decimal\"\n | \"boolean\"\n | \"datetime\"\n | \"date\"\n | \"time\"\n | \"bigint\"\n | \"json\"\n | \"blob\"\n | \"vector\"\n | \"point\"\n | \"enum\";\n\nexport type AutoGenerateType =\n | \"uuid\"\n | \"uuidv7\"\n | \"ulid\"\n | \"ksuid\"\n | \"nanoid\"\n | \"cuid\"\n | \"increment\"\n | \"now\"\n | \"updatedAt\";\n\n/**\n * A generator declaration.\n *\n * `kind` is the only statement of which generator runs. `prefix` and `length`\n * are declaration facts the string generators otherwise bake into their default\n * closure, where nothing can read them back; state is their durable home so a\n * serializer can restate the declaration that produced the closure.\n * `increment`/`now`/`updatedAt` take neither.\n */\nexport interface AutoGenerate {\n kind: AutoGenerateType;\n prefix?: string | undefined;\n length?: number | undefined;\n /**\n * The caller did not NAME this format; `.id()` installed it.\n *\n * The distinction is what separates a key from a domain. `.ulid()` is an\n * assertion about every value the field will ever hold — which is what lets\n * VibORM admit those values, normalize their aliases and store them as\n * sixteen bytes. `.id()` is an assertion about the KEY, carrying a generator\n * so a caller need not supply one; the values it accepts are still whatever\n * a string column accepts, and it stores them as text. `.ulid().id()` says\n * both, and is a ULID key.\n *\n * It lives on the declaration record, beside `kind`, because it IS a fact\n * about how this generator came to be declared — not a second scalar state.\n */\n implicit?: boolean | undefined;\n /** Explicit generation choice; absent formats acquire a default only as IDs. */\n generate?: boolean | undefined;\n}\n\n/**\n * The closures the generator modifiers installed.\n *\n * A generator writes TWO facts: `autoGenerate`, which is the declaration, and\n * `default`, which is the closure that produces the value. A later\n * `.default(fn)` replaces only the second, so `autoGenerate !== undefined` is\n * not evidence that the closure standing in `default` is the generator's — and\n * a consumer that restates a declaration from state (the JSON serializer) would\n * otherwise silently substitute a random generator for a caller's own function.\n *\n * Identity is the only thing that distinguishes them, so identity is what is\n * recorded. One owner, beside the declaration it belongs to; nothing outside\n * the eight modifier writers may add to it.\n */\nconst GENERATOR_DEFAULTS = new WeakSet<object>();\n\n/** Mark a closure as the default a generator modifier installed. */\ndeclare const GENERATED_DEFAULT: unique symbol;\nexport interface GeneratorDefaultBrand {\n readonly [GENERATED_DEFAULT]: true;\n}\nexport function generatorDefault<F extends () => unknown>(\n closure: F\n): F & GeneratorDefaultBrand;\nexport function generatorDefault<F extends () => unknown>(closure: F) {\n GENERATOR_DEFAULTS.add(closure);\n return closure;\n}\n\n/** A scalar generator cannot produce a complete list default. */\nexport function refuseListGenerator(builder: string): never {\n throw new ValidationError(\n { kind: \"schema-builder\", builder, path: \"array\" },\n [\n {\n path: \"array\",\n message:\n \"Scalar generation is not supported on lists; declare an explicit array default\",\n },\n ]\n );\n}\n\n/** Nullable admission supplies null only when no default was already declared. */\nexport function nullableDefault<State extends ScalarState>(\n state: State\n): State[\"hasDefault\"] extends true ? State[\"default\"] : null;\nexport function nullableDefault(state: ScalarState) {\n return state.hasDefault ? state.default : null;\n}\n\n/** Whether this default value IS a generator's own installed closure. */\nexport function isGeneratorDefault(value: unknown): boolean {\n return typeof value === \"function\" && GENERATOR_DEFAULTS.has(value);\n}\n\n// =============================================================================\n// SCALAR STATE\n// =============================================================================\n\n/**\n * Complete state for a scalar instance.\n * This is the single generic that flows through the scalar class.\n */\n\nexport interface ScalarState<T extends ScalarType = ScalarType> {\n type: T;\n nullable: boolean;\n array: boolean;\n hasDefault: boolean;\n isId: boolean;\n isUnique: boolean;\n default: DefaultValue<any> | undefined;\n autoGenerate: AutoGenerate | undefined;\n /** Runtime create validation for portable auto-increment semantics. */\n disallowZero?: boolean;\n schema: StandardSchemaV1<any, any> | undefined;\n optional: boolean;\n /** Custom column name in the database (set via .map()) */\n columnName: string | undefined;\n base: VibSchema;\n withTimezone?: boolean | undefined;\n /**\n * The declared fixed-decimal domain, frozen at `s.decimal({...})`.\n *\n * It is the ONE source of truth for input validation, physical DDL, literal\n * encoding, result decoding, comparison and aggregate lowering, arithmetic\n * rounding and overflow, list-member encoding, and migration compatibility.\n * No adapter, driver, result parser, or migration component stores a second\n * precision or scale decision, and every modifier carries THIS object by\n * reference rather than rebuilding one.\n */\n decimal?: DecimalDescriptor | undefined;\n /** Fixed vector length for pgvector-backed vector scalars. */\n dimension?: number | undefined;\n /** Custom enum type name in the database (set via .name() on enum scalars) */\n enumName?: string | undefined;\n}\n\n// =============================================================================\n// STATE UPDATE HELPER\n// =============================================================================\n\n/**\n * Computes the new state type after applying an update.\n * Used by chainable methods to derive the return type.\n *\n * @example\n * nullable(): StringScalar<UpdateState<State, { nullable: true }>>\n */\nexport type UpdateState<\n State extends ScalarState,\n Update extends Partial<ScalarState>,\n> = Omit<State, keyof Update> & Update;\n\nexport const updateState = <\n F extends Scalar,\n const Update extends Partial<ScalarState>,\n>(\n scalar: F,\n update: Update\n) => {\n return { ...scalar[\"~\"].state, ...update } as UpdateState<\n F[\"~\"][\"state\"],\n Update\n >;\n};\n\n// =============================================================================\n// TYPE HELPERS\n// =============================================================================\n\n/**\n * Conditionally wraps a type with null\n */\nexport type MaybeNullable<\n T,\n Nullable extends boolean = false,\n> = Nullable extends true ? T | null : T;\n\n/**\n * Conditionally wraps a type as array\n */\nexport type MaybeArray<\n T,\n IsArray extends boolean = false,\n> = IsArray extends true ? T[] : T;\n\n/**\n * Type for default value - can be direct value or factory function\n */\nexport type DefaultValue<T> = T | (() => T);\n\n/**\n * The input accepted by the scalar's current base schema, or a factory for it.\n *\n * The base schema already owns the scalar's nullable and array wrappers. Adding\n * them again here turns a list default into a list of lists at the type level\n * (`string[][]` for `s.string().array()`), while runtime validation correctly\n * expects `string[]`. Read the one trusted shape instead of reconstructing it.\n */\nexport type DefaultValueInput<S extends ScalarState> = DefaultValue<\n InferInput<S[\"base\"]>\n>;\n\n// =============================================================================\n// DEFAULT STATE FACTORY\n// =============================================================================\n\n/** The factory's existing initial state stays named in exported model graphs. */\nexport interface InitialScalarState<T extends ScalarType, B extends VibSchema> {\n type: T;\n nullable: boolean;\n array: boolean;\n hasDefault: boolean;\n isId: boolean;\n isUnique: boolean;\n default: undefined;\n autoGenerate: undefined;\n disallowZero: boolean;\n schema: undefined;\n columnName: undefined;\n optional: boolean;\n withTimezone: boolean;\n base: B;\n}\n\n/**\n * Creates a default initial state for a scalar type\n */\nexport const createDefaultState = <T extends ScalarType, B extends VibSchema>(\n type: T,\n base: B\n): InitialScalarState<T, B> => ({\n type,\n nullable: false,\n array: false,\n hasDefault: false,\n isId: false,\n isUnique: false,\n default: undefined,\n autoGenerate: undefined,\n disallowZero: false,\n schema: undefined,\n columnName: undefined,\n optional: false,\n withTimezone: false,\n base,\n});\n\n// =============================================================================\n// INFER HELPERS (for type-level inference from state)\n// =============================================================================\n\n/**\n * Infers the base TypeScript type from a scalar state\n */\nexport type InferBaseType<\n BaseType,\n State extends ScalarState,\n> = State[\"array\"] extends true\n ? State[\"nullable\"] extends true\n ? (BaseType | null)[]\n : BaseType[]\n : State[\"nullable\"] extends true\n ? BaseType | null\n : BaseType;\n\n/**\n * Infers the create input type from a scalar state\n */\nexport type InferCreateType<\n BaseType,\n State extends ScalarState,\n> = State[\"hasDefault\"] extends true\n ? State[\"nullable\"] extends true\n ? BaseType | null | undefined\n : BaseType | undefined\n : State[\"nullable\"] extends true\n ? BaseType | null\n : BaseType;\n\n// =============================================================================\n// SCHEMA SHORTHANDS (re-exported from validation primitives)\n// =============================================================================\n\nexport {\n shorthandArray,\n shorthandFilter,\n shorthandUpdate,\n} from \"@validation/primitives/shorthand\";\n","// The closed per-dialect native-type catalog, and the scalar factories' one\n// native-type admission.\n//\n// A native type's `type` is the ONE declaration string a migration driver emits\n// into DDL verbatim — the three drivers write it as a column's type with no\n// escaping, because a coded schema takes it from a typed constant. A schema\n// document is written by whoever hands you one, so it decides what may occupy\n// that position here. Coded maps and tagged declarations share the historical\n// trusted schema-author escape hatch for custom type spellings. The round-1 answer was a word grammar; the reviewer proved it cannot\n// work: `TEXT REFERENCES victims(id)`, `TEXT UNIQUE` and `TEXT CHECK(0)` are\n// letters and spaces with an optional parenthesized group, indistinguishable\n// from a multi-word type name, yet each appends a CONSTRAINT to a column in DDL.\n// No regex over arbitrary SQL words separates a type from a clause.\n//\n// So the admissible set is CLOSED and derived, per dialect, from the one owner\n// that already enumerates native types: the shipped `PG`/`MYSQL`/`SQLITE`\n// constant trees. Derivation, not duplication —\n//\n// - a string leaf (`{ db, type: \"text\" }`) contributes its EXACT value;\n// - a function leaf (a parameterized type) is probe-called at zero, one and\n// two integer arguments to learn its base name and which argument arities it\n// publishes; the catalog then admits that base bare, or with one or two\n// INTEGER arguments, at exactly those arities.\n//\n// The trees produce no word-argument type THROUGH A FUNCTION — `geometry(Point)`\n// is a string leaf, matched exactly — so there is no word-argument rule, which\n// is the narrowest rule the trees justify. A coded schema's constants are\n// catalog members by construction. The schema-document reader and serializer\n// consult this owner for the tagged `native` form; `admitNativeType` validates coded maps structurally. A TAGGED declaration written in code keeps its historical\n// open contract (a custom `{ db, type }` still reaches DDL as written) — only a\n// document refuses one outside the catalog. Nothing downstream sanitizes native\n// types, and nothing can.\n//\n// This lives beside `native-types.ts` rather than in the document module because\n// the scalar factories need it; it imports the constant trees, so the trees'\n// module cannot import it back.\n\nimport { ValidationError } from \"@errors\";\nimport { isRecord } from \"@validation/value-guards\";\nimport {\n type DialectNativeType,\n isTaggedNativeType,\n MYSQL,\n NATIVE_DIALECTS,\n type NativeDialect,\n type NativeTypeDeclaration,\n type NativeTypeMap,\n PG,\n SQLITE,\n} from \"./native-types\";\n\ntype Dialect = NativeDialect;\n\ntype DialectCatalog = {\n /** The exact type strings every string leaf produces. */\n readonly exact: Set<string>;\n /** A parameterized base name → the argument arities it publishes (0 = bare). */\n readonly templates: Map<string, Set<number>>;\n};\n\n/** Distinct non-zero probe arguments, so a produced form is unambiguous. */\nconst PROBE_ARGUMENTS: readonly number[][] = [[], [1], [1, 2]];\n\n/** A parameterized-type argument the trees produce: a non-negative integer. */\nconst INTEGER_ARGUMENT = /^\\d+$/;\n\n/**\n * A native type at the matching boundary: a base identifier, optionally followed\n * by one parenthesized group of comma-separated integers. This gate REJECTS\n * everything a clause needs — a quote, a space, a semicolon, a comment, a second\n * group, a non-integer argument — so what survives is only shaped like a type,\n * and the catalog then decides whether it IS one.\n */\nconst TYPE_EXPRESSION = /^[A-Za-z_][A-Za-z0-9_]*(\\(\\d+(,\\d+)*\\))?$/;\n\nconst CONSTANT_NAMES: Record<Dialect, string> = {\n pg: \"PG\",\n mysql: \"MYSQL\",\n sqlite: \"SQLITE\",\n};\n\n// Built on the first native-type check rather than at import: walking every\n// dialect's constants runs dozens of probe calls, and a schema that declares\n// no native type never asks.\nlet catalogs: Record<Dialect, DialectCatalog> | undefined;\n\n/**\n * Whether `type` is a native type the declared dialect's catalog admits. The\n * gate's single statement, used by the reader and the serializer alike.\n */\nexport function isNativeTypeInCatalog(db: Dialect, type: string): boolean {\n catalogs ??= buildCatalogs();\n const catalog = catalogs[db];\n if (catalog.exact.has(type)) {\n return true;\n }\n if (!TYPE_EXPRESSION.test(type)) {\n return false;\n }\n const open = type.indexOf(\"(\");\n if (open === -1) {\n return catalog.templates.get(type)?.has(0) === true;\n }\n const base = type.slice(0, open);\n const arity = type.slice(open + 1, -1).split(\",\").length;\n return catalog.templates.get(base)?.has(arity) === true;\n}\n\n/**\n * The refusal both directions carry, naming the dialect whose catalog was\n * consulted and pointing at the documented list.\n */\nexport function nativeTypeRefusal(db: Dialect): string {\n return `A \\`native.type\\` is written into DDL verbatim, so a document may carry only a native type from the '${db}' dialect's closed catalog — the values the ${CONSTANT_NAMES[db]} native-type constants produce. See the native types documentation (docs/schema/native-types).`;\n}\n\n// =============================================================================\n// SCALAR FACTORY ADMISSION\n// =============================================================================\n\n/** The one construction-time refusal of a native-type argument. */\nfunction refuse(builder: string, path: string, message: string): never {\n throw new ValidationError({ kind: \"schema-builder\", builder, path }, [\n { path, message },\n ]);\n}\n\n/**\n * A scalar factory's native-type argument, admitted: the declaration the scalar\n * stores and every modifier carries.\n *\n * The tagged shorthand is returned AS GIVEN — its open historical contract,\n * custom spellings and unrelated extra keys included, is unchanged — once it\n * names one of the three dialects as `db` and a string `type` (a value that does\n * not would be silently ignored by every dialect, or reach DDL as `undefined`),\n * and unless it also carries a dialect key, which makes it two declarations at\n * once. A map is the new form and is\n * held to its whole contract here, where types can be bypassed: only the three\n * dialect keys, at least one of them, each an OWN entry of its own dialect whose\n * type the catalog admits. It is then SNAPSHOT into a frozen map of frozen\n * `{ db, type }` entries, so the caller's object — or an entry it shares with\n * another declaration — can change afterwards without changing this scalar.\n */\nexport function admitNativeType(\n builder: string,\n declaration: NativeTypeDeclaration | undefined\n): NativeTypeDeclaration | undefined {\n return declaration === undefined\n ? undefined\n : admitDeclaredNativeType(builder, declaration);\n}\n\n/** A declared native type, out of line: most scalars declare none. */\nfunction admitDeclaredNativeType(\n builder: string,\n declaration: NativeTypeDeclaration\n): NativeTypeDeclaration {\n if (!isRecord(declaration)) {\n refuse(\n builder,\n \"nativeType\",\n \"A native type is a `{ db, type }` constant or a map of them by dialect (`{ pg, mysql, sqlite }`)\"\n );\n }\n if (isTaggedNativeType(declaration)) {\n const { db, type } = declaration;\n if (!NATIVE_DIALECTS.includes(db) || typeof type !== \"string\") {\n refuse(\n builder,\n \"nativeType\",\n `A tagged native type is \\`{ db, type }\\`: \\`db\\` one of ${NATIVE_DIALECTS.join(\", \")} and \\`type\\` a string`\n );\n }\n const beside = NATIVE_DIALECTS.find((dialect) =>\n Object.hasOwn(declaration, dialect)\n );\n if (beside !== undefined) {\n refuse(\n builder,\n `nativeType.${beside}`,\n `A tagged native type ('db: ${db}') cannot also carry a '${beside}' entry: declare one tagged type, or a map by dialect (\\`{ pg, mysql, sqlite }\\`)`\n );\n }\n return declaration;\n }\n return admitNativeTypeMap(builder, declaration);\n}\n\nfunction admitNativeTypeMap(\n builder: string,\n map: NativeTypeMap\n): NativeTypeMap {\n for (const key of Object.keys(map)) {\n if (!NATIVE_DIALECTS.some((dialect) => dialect === key)) {\n refuse(\n builder,\n `nativeType.${key}`,\n `'${key}' is not a dialect: a native-type map names only ${NATIVE_DIALECTS.join(\", \")}`\n );\n }\n }\n const snapshot: {\n pg?: DialectNativeType<\"pg\">;\n mysql?: DialectNativeType<\"mysql\">;\n sqlite?: DialectNativeType<\"sqlite\">;\n } = {};\n if (Object.hasOwn(map, \"pg\")) snapshot.pg = admitEntry(builder, \"pg\", map.pg);\n if (Object.hasOwn(map, \"mysql\")) {\n snapshot.mysql = admitEntry(builder, \"mysql\", map.mysql);\n }\n if (Object.hasOwn(map, \"sqlite\")) {\n snapshot.sqlite = admitEntry(builder, \"sqlite\", map.sqlite);\n }\n if (Object.keys(snapshot).length === 0) {\n refuse(\n builder,\n \"nativeType\",\n \"A native-type map names at least one dialect; omit the argument to keep every automatic column\"\n );\n }\n return Object.freeze(snapshot);\n}\n\n/** One map entry: a native type of exactly its key's dialect, in its catalog. */\nfunction admitEntry<Entry extends Dialect>(\n builder: string,\n dialect: Entry,\n entry: unknown\n): DialectNativeType<Entry> {\n const db = isRecord(entry) ? entry.db : undefined;\n const type = isRecord(entry) ? entry.type : undefined;\n if (db !== dialect || typeof type !== \"string\") {\n refuse(\n builder,\n `nativeType.${dialect}`,\n `The '${dialect}' entry must be a ${CONSTANT_NAMES[dialect]} native type (\\`{ db: \"${dialect}\", type }\\`)`\n );\n }\n return Object.freeze({ db: dialect, type });\n}\n\n// =============================================================================\n// CATALOG CONSTRUCTION\n// =============================================================================\n\nfunction buildCatalogs(): Record<Dialect, DialectCatalog> {\n const catalogs: Record<Dialect, DialectCatalog> = {\n pg: emptyCatalog(),\n mysql: emptyCatalog(),\n sqlite: emptyCatalog(),\n };\n walk(PG, catalogs.pg);\n walk(MYSQL, catalogs.mysql);\n walk(SQLITE, catalogs.sqlite);\n return catalogs;\n}\n\nfunction emptyCatalog(): DialectCatalog {\n return { exact: new Set(), templates: new Map() };\n}\n\n// The trees are trusted, shipped constants — objects, categories and function\n// leaves, never a primitive or null — so this walk reads their shape directly.\n// The node type is `any` because a walk over a heterogeneous tree erases the\n// leaf types, and narrowing back to them would need the casts the house forbids.\nfunction walk(node: any, catalog: DialectCatalog): void {\n if (typeof node === \"function\") {\n deriveFunction(node, catalog);\n return;\n }\n const type = node.type;\n if (typeof type === \"string\") {\n catalog.exact.add(type);\n return;\n }\n for (const value of Object.values(node)) {\n walk(value, catalog);\n }\n}\n\n/** A parameterized-type leaf, called generically — hence the erased type. */\nfunction deriveFunction(factory: any, catalog: DialectCatalog): void {\n for (const args of PROBE_ARGUMENTS) {\n const type: string = factory(...args).type;\n const open = type.indexOf(\"(\");\n if (open === -1) {\n admit(catalog, type, 0);\n continue;\n }\n // A required-argument function called with too few produces `base(undefined)`\n // — never a value the constant yields — so a non-integer argument is skipped.\n const parts = type.slice(open + 1, -1).split(\",\");\n if (parts.every((part) => INTEGER_ARGUMENT.test(part))) {\n admit(catalog, type.slice(0, open), parts.length);\n }\n }\n}\n\nfunction admit(catalog: DialectCatalog, base: string, arity: number): void {\n const arities = catalog.templates.get(base);\n if (arities === undefined) {\n catalog.templates.set(base, new Set([arity]));\n return;\n }\n arities.add(arity);\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: Keccak-f[1600] is a bit\n// permutation. Every operator below is part of the published specification's\n// arithmetic, carried on 32-bit halves because JavaScript has no 64-bit word.\n\n/**\n * SHA3-512, the one hash VibORM computes.\n *\n * FIPS 202's Keccak-f[1600] over 25 lanes of 64 bits, rate 72 bytes, domain\n * padding `0x06 ... 0x80`. One exported function, no streaming, no options, no\n * configuration: the caller hands over the complete message and receives the\n * 64-byte digest.\n *\n * Each 64-bit lane is carried as TWO 32-bit halves rather than a `BigInt`.\n * JavaScript's bitwise operators are 32-bit, so a BigInt lane would allocate a\n * new arbitrary-precision value for every one of the roughly 1,200 operations a\n * single digest performs.\n *\n * Every read goes through a `DataView`, which is the one indexed read this\n * codebase has that is not `T | undefined`: a Keccak round has no in-range\n * check to make and no branch to take, so a fallback on a typed-array read\n * would be a guard whose coverage cannot be named. The halves are stored\n * little-endian at `lane * 8` and `lane * 8 + 4`, which is exactly the lane's\n * own little-endian byte layout — so absorbing a block is a word-wise XOR of\n * the message and squeezing is a copy of the first 64 bytes.\n *\n * The one caller is CUID2 (`@schema/scalars/string/autogenerate`). Nothing else\n * in VibORM may import this module without its own differential proof against a\n * reference implementation.\n */\n\n/** SHA3-512's rate: 1600 - 2*512 bits, as bytes. */\nconst RATE_BYTES = 72;\n/** 512 bits of output. */\nconst DIGEST_BYTES = 64;\nconst LANES = 25;\nconst STATE_BYTES = LANES * 8;\nconst ROUNDS = 24;\n/** SHA-3's domain separation: `01` then the pad10*1 rule's leading bit. */\nconst DOMAIN_PAD = 0x06;\n/** pad10*1's trailing bit, at the top of the block's last byte. */\nconst FINAL_PAD = 0x80;\n\n/**\n * The iota round constants, low half then high half of each round.\n *\n * Filled through the same little-endian writes every other buffer in this\n * module is filled with. A typed array would lay its bytes out in the HOST's\n * order, which is not what the read at the iota step asks for: the two would\n * agree on a little-endian machine and disagree on every other one.\n */\nconst ROUND_CONSTANTS = new DataView(new ArrayBuffer(ROUNDS * 8));\nfor (const [half, constant] of [\n 0x00_00_00_01, 0x00_00_00_00, 0x00_00_80_82, 0x00_00_00_00, 0x00_00_80_8a,\n 0x80_00_00_00, 0x80_00_80_00, 0x80_00_00_00, 0x00_00_80_8b, 0x00_00_00_00,\n 0x80_00_00_01, 0x00_00_00_00, 0x80_00_80_81, 0x80_00_00_00, 0x00_00_80_09,\n 0x80_00_00_00, 0x00_00_00_8a, 0x00_00_00_00, 0x00_00_00_88, 0x00_00_00_00,\n 0x80_00_80_09, 0x00_00_00_00, 0x80_00_00_0a, 0x00_00_00_00, 0x80_00_80_8b,\n 0x00_00_00_00, 0x00_00_00_8b, 0x80_00_00_00, 0x00_00_80_89, 0x80_00_00_00,\n 0x00_00_80_03, 0x80_00_00_00, 0x00_00_80_02, 0x80_00_00_00, 0x00_00_00_80,\n 0x80_00_00_00, 0x00_00_80_0a, 0x00_00_00_00, 0x80_00_00_0a, 0x80_00_00_00,\n 0x80_00_80_81, 0x80_00_00_00, 0x00_00_80_80, 0x80_00_00_00, 0x80_00_00_01,\n 0x00_00_00_00, 0x80_00_80_08, 0x80_00_00_00,\n].entries()) {\n ROUND_CONSTANTS.setInt32(half * 4, constant, true);\n}\n\n/** Rho: the rotation each lane receives, indexed by `x + 5y`. */\nconst ROTATIONS = new DataView(\n new Uint8Array([\n 0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8,\n 18, 2, 61, 56, 14,\n ]).buffer\n);\n\n/** Pi: where lane `x + 5y` lands, which is `y + 5*((2x + 3y) mod 5)`. */\nconst DESTINATIONS = new DataView(\n new Uint8Array([\n 0, 10, 20, 5, 15, 16, 1, 11, 21, 6, 7, 17, 2, 12, 22, 23, 8, 18, 3, 13, 14,\n 24, 9, 19, 4,\n ]).buffer\n);\n\n/**\n * The permutation state and its two scratch planes, allocated once.\n *\n * `sha3_512` is synchronous from entry to return and this module has no other\n * caller, so one set of buffers is reused rather than allocating a hundred\n * slots per identifier. Every entry begins by zeroing the state.\n */\nconst stateBytes = new Uint8Array(STATE_BYTES);\nconst state = new DataView(stateBytes.buffer);\nconst plane = new DataView(new ArrayBuffer(STATE_BYTES));\nconst column = new DataView(new ArrayBuffer(5 * 8));\n\n/**\n * Keccak-f[1600]: 24 rounds of theta, rho + pi, chi and iota.\n *\n * A rotation by `n < 32` takes its missing bits from the other half at\n * `32 - n`; a rotation by `n > 32` is the same shape with the halves swapped\n * and `n - 32`. Neither case is reachable with `n = 0` or `n = 32`, which would\n * need a 32-bit shift JavaScript does not have: rho's only zero is lane 0,\n * which is skipped, and 32 is not one of its offsets.\n */\nfunction permute(): void {\n for (let round = 0; round < ROUNDS; round++) {\n // Theta: each column's parity, folded back into every lane of the column.\n for (let x = 0; x < 5; x++) {\n let low = 0;\n let high = 0;\n for (let y = 0; y < LANES; y += 5) {\n low ^= state.getInt32((x + y) * 8, true);\n high ^= state.getInt32((x + y) * 8 + 4, true);\n }\n column.setInt32(x * 8, low, true);\n column.setInt32(x * 8 + 4, high, true);\n }\n for (let x = 0; x < 5; x++) {\n const nextLow = column.getInt32(((x + 1) % 5) * 8, true);\n const nextHigh = column.getInt32(((x + 1) % 5) * 8 + 4, true);\n const deltaLow =\n column.getInt32(((x + 4) % 5) * 8, true) ^\n ((nextLow << 1) | (nextHigh >>> 31));\n const deltaHigh =\n column.getInt32(((x + 4) % 5) * 8 + 4, true) ^\n ((nextHigh << 1) | (nextLow >>> 31));\n for (let y = 0; y < LANES; y += 5) {\n const at = (x + y) * 8;\n state.setInt32(at, state.getInt32(at, true) ^ deltaLow, true);\n state.setInt32(at + 4, state.getInt32(at + 4, true) ^ deltaHigh, true);\n }\n }\n\n // Rho and pi: rotate every lane, then move it to its permuted position.\n plane.setInt32(0, state.getInt32(0, true), true);\n plane.setInt32(4, state.getInt32(4, true), true);\n for (let lane = 1; lane < LANES; lane++) {\n const shift = ROTATIONS.getUint8(lane);\n const low = state.getInt32(lane * 8, true);\n const high = state.getInt32(lane * 8 + 4, true);\n const target = DESTINATIONS.getUint8(lane) * 8;\n if (shift < 32) {\n plane.setInt32(target, (low << shift) | (high >>> (32 - shift)), true);\n plane.setInt32(\n target + 4,\n (high << shift) | (low >>> (32 - shift)),\n true\n );\n } else {\n const rest = shift - 32;\n plane.setInt32(target, (high << rest) | (low >>> (32 - rest)), true);\n plane.setInt32(\n target + 4,\n (low << rest) | (high >>> (32 - rest)),\n true\n );\n }\n }\n\n // Chi: each lane against the next two in its row.\n for (let y = 0; y < LANES; y += 5) {\n for (let x = 0; x < 5; x++) {\n const at = (y + x) * 8;\n const next = (y + ((x + 1) % 5)) * 8;\n const after = (y + ((x + 2) % 5)) * 8;\n state.setInt32(\n at,\n plane.getInt32(at, true) ^\n (~plane.getInt32(next, true) & plane.getInt32(after, true)),\n true\n );\n state.setInt32(\n at + 4,\n plane.getInt32(at + 4, true) ^\n (~plane.getInt32(next + 4, true) & plane.getInt32(after + 4, true)),\n true\n );\n }\n }\n\n // Iota: the round constant, on the first lane only.\n state.setInt32(\n 0,\n state.getInt32(0, true) ^ ROUND_CONSTANTS.getInt32(round * 8, true),\n true\n );\n state.setInt32(\n 4,\n state.getInt32(4, true) ^ ROUND_CONSTANTS.getInt32(round * 8 + 4, true),\n true\n );\n }\n}\n\n/** Absorb one complete rate-sized block and run the permutation. */\nfunction absorb(block: DataView, offset: number): void {\n for (let at = 0; at < RATE_BYTES; at += 4) {\n state.setInt32(\n at,\n state.getInt32(at, true) ^ block.getInt32(offset + at, true),\n true\n );\n }\n permute();\n}\n\n/**\n * The SHA3-512 digest of one complete message.\n *\n * Byte-identical to the reference implementation for every input, which a\n * differential test pins against the NIST known-answer vectors and 10,000\n * random messages crossing every rate boundary.\n */\nexport function sha3_512(bytes: Uint8Array): Uint8Array {\n stateBytes.fill(0);\n\n const length = bytes.length;\n const message = new DataView(bytes.buffer, bytes.byteOffset, length);\n const wholeBlocks = Math.floor(length / RATE_BYTES);\n for (let block = 0; block < wholeBlocks; block++) {\n absorb(message, block * RATE_BYTES);\n }\n\n // The final block is the message tail plus pad10*1. A tail of exactly\n // `RATE_BYTES - 1` puts both pad bits in the same byte, which is the rule\n // rather than a special case.\n const tail = new Uint8Array(RATE_BYTES);\n const tailLength = length - wholeBlocks * RATE_BYTES;\n tail.set(bytes.subarray(wholeBlocks * RATE_BYTES));\n tail[tailLength] = DOMAIN_PAD;\n tail[RATE_BYTES - 1] =\n tailLength === RATE_BYTES - 1 ? DOMAIN_PAD | FINAL_PAD : FINAL_PAD;\n absorb(new DataView(tail.buffer), 0);\n\n // 512 bits is narrower than the rate, so one squeeze with no further\n // permutation is the whole digest — and the halves are already stored in the\n // little-endian order the digest is written in.\n return Uint8Array.from(stateBytes.subarray(0, DIGEST_BYTES));\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: NanoID selects a\n// character with `byte & 63`, the ULID counter carries a byte at a time, and\n// CUID2's digest is read as one big-endian integer. All three are bit layouts.\n\n/**\n * The six identifier generators a string scalar can declare.\n *\n * Each `default*` function is the DECLARATION: it validates what the modifier\n * was spelled with and returns the closure the scalar stores as its default.\n * The closure is what runs per row, synchronously, inside the field's own\n * create schema — so nothing here may be asynchronous, and nothing here may\n * draw entropy before it is called.\n *\n * The byte layouts, alphabets, widths and the one entropy source live in\n * `@validation/primitives/id-formats`, where the storage codec can read them\n * without pulling a scalar class. This module owns only what a GENERATOR adds\n * to a format: the clock it reads, the state it keeps between calls, and the\n * prefix it puts in front of the payload.\n */\n\nimport {\n applyIdPrefix,\n bytesToKsuid,\n bytesToUlid,\n bytesToUuid,\n KSUID_PAYLOAD_LENGTH,\n ksuidBytes,\n MAX_RANDOM_BYTES,\n NANOID_ALPHABET,\n NANOID_DEFAULT_LENGTH,\n randomBytes,\n refuseId,\n ULID_RANDOM_LENGTH,\n UUID_BYTE_LENGTH,\n UUIDV7_RANDOM_LENGTH,\n ulidBytes,\n uuidV4Bytes,\n uuidV7Bytes,\n} from \"@validation/primitives/id-formats\";\nimport { sha3_512 } from \"@validation/primitives/sha3\";\n\nconst MILLISECONDS_PER_SECOND = 1000;\n\n// =============================================================================\n// UUID\n// =============================================================================\n\n/**\n * A UUIDv4.\n *\n * `crypto.randomUUID()` when the runtime has it — it is the platform's own\n * implementation of exactly this format, and it is measurably faster than\n * drawing bytes and tagging them. The manual path is not a fallback to a weaker\n * value: it is the same 122 random bits with the same version and variant, from\n * the same entropy source, for runtimes that expose `getRandomValues` without\n * `randomUUID`.\n */\nfunction uuidV4(): string {\n const source = globalThis.crypto;\n if (typeof source?.randomUUID === \"function\") return source.randomUUID();\n return bytesToUuid(uuidV4Bytes(randomBytes(UUID_BYTE_LENGTH, \"uuid\")));\n}\n\nexport const defaultUuid = (prefix?: string) => () =>\n applyIdPrefix(prefix, uuidV4());\n\nexport const defaultUuidV7 = (prefix?: string) => () =>\n applyIdPrefix(\n prefix,\n bytesToUuid(\n uuidV7Bytes(Date.now(), randomBytes(UUIDV7_RANDOM_LENGTH, \"uuidv7\"))\n )\n );\n\n// =============================================================================\n// ULID\n// =============================================================================\n\n/** The next 80-bit random block, or a refusal when the block is exhausted. */\nfunction incrementUlidRandom(random: Uint8Array): Uint8Array {\n const next = Uint8Array.from(random);\n const view = new DataView(next.buffer);\n for (let index = next.length - 1; index >= 0; index--) {\n const incremented = view.getUint8(index) + 1;\n view.setUint8(index, incremented & 255);\n if (incremented <= 255) return next;\n }\n return refuseId(\n \"s.string().ulid\",\n \"generate\",\n \"This process issued every ULID one millisecond can hold (2^80). Monotonicity cannot be preserved without emitting a smaller identifier\"\n );\n}\n\n/**\n * One monotonic ULID sequence.\n *\n * Within a millisecond the timestamp repeats, so the 80-bit random block is\n * INCREMENTED instead of redrawn: two ULIDs minted in the same millisecond\n * still sort in the order they were issued. A clock that moves backwards keeps\n * emitting the last timestamp for the same reason — a smaller identifier would\n * break the ordering the format promises, and the ORM cannot fix the clock.\n *\n * The whole block is drawn at once from secure bytes, so every bit is uniform.\n *\n * `now` and `random` are injectable because monotonicity, rollback and\n * exhaustion are statements about a SEQUENCE, and a sequence cannot be observed\n * through a real clock. The process-wide generator below takes the defaults.\n */\nexport function createUlidGenerator(\n options: { now?: () => number; random?: (length: number) => Uint8Array } = {}\n): () => string {\n const now = options.now ?? Date.now;\n const draw = options.random ?? ((length) => randomBytes(length, \"ulid\"));\n let last: { time: number; random: Uint8Array } | undefined;\n return () => {\n const time = now();\n last =\n last !== undefined && time <= last.time\n ? { time: last.time, random: incrementUlidRandom(last.random) }\n : { time, random: draw(ULID_RANDOM_LENGTH) };\n return bytesToUlid(ulidBytes(last.time, last.random));\n };\n}\n\n/**\n * ONE monotonic sequence per process, shared by every `.ulid()` and `.id()`\n * field. Monotonicity is a property of the issuing process, not of a field: two\n * models minting ULIDs in the same millisecond must not collide, and a\n * per-field sequence would let them.\n */\nconst nextUlid = createUlidGenerator();\n\nexport const defaultUlid = (prefix?: string) => () =>\n applyIdPrefix(prefix, nextUlid());\n\n// =============================================================================\n// KSUID\n// =============================================================================\n\nexport const defaultKsuid = (prefix?: string) => () =>\n applyIdPrefix(\n prefix,\n bytesToKsuid(\n ksuidBytes(\n Math.floor(Date.now() / MILLISECONDS_PER_SECOND),\n randomBytes(KSUID_PAYLOAD_LENGTH, \"ksuid\")\n )\n )\n );\n\n// =============================================================================\n// NANOID\n// =============================================================================\n\n/**\n * The lengths a nanoid can have, refused where the length is spelled.\n *\n * One character costs one byte of entropy, so the upper bound is the entropy\n * source's own per-call quota: asking for more used to declare cleanly and then\n * throw a raw `QuotaExceededError` from inside the closure, at row-create time,\n * for every row.\n */\nexport const defaultNanoid = (length?: number, prefix?: string) => {\n const size = length ?? NANOID_DEFAULT_LENGTH;\n if (!Number.isInteger(size) || size < 1 || size > MAX_RANDOM_BYTES) {\n refuseId(\n \"s.string().nanoid\",\n \"length\",\n `A nanoid length must be a whole number of characters between 1 and ${MAX_RANDOM_BYTES}; received ${size}`\n );\n }\n return () => {\n let id = \"\";\n for (const byte of randomBytes(size, \"nanoid\")) {\n id += NANOID_ALPHABET.charAt(byte & 63);\n }\n return applyIdPrefix(prefix, id);\n };\n};\n\n// =============================================================================\n// CUID2\n// =============================================================================\n\n/*\n * The CUID2 construction below is a port of @paralleldrive/cuid2 3.3.0, kept\n * byte-identical to it so that identifiers minted by VibORM and identifiers\n * minted by the upstream package belong to the same space. What changed is the\n * arithmetic (native `BigInt` in place of bignumber.js), the entropy source\n * (secure bytes only, never `Math.random()`), and the fingerprint's global\n * object (`globalThis`, which every supported runtime has). A differential test\n * pins the rest against the upstream package.\n *\n * MIT License\n *\n * Copyright (c) 2022 Eric Elliott\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nconst CUID_DEFAULT_LENGTH = 24;\nconst CUID_BIG_LENGTH = 32;\nconst CUID_ALPHABET_SIZE = 26;\nconst BASE36 = 36;\n/** ~22k hosts before a 50% chance of an initial counter collision (upstream). */\nconst CUID_INITIAL_COUNT_MAX = 476_782_367;\n\nconst TEXT_ENCODER = new TextEncoder();\nconst LOWERCASE_LETTERS = \"abcdefghijklmnopqrstuvwxyz\";\n\n/** A float in `[0, 1)` from four secure bytes, read as one 32-bit word. */\nfunction secureFloat(): number {\n const bytes = randomBytes(4, \"cuid\");\n const word = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n return word.getUint32(0, true) / 0x1_00_00_00_00;\n}\n\nfunction createEntropy(length: number, random: () => number): string {\n let entropy = \"\";\n while (entropy.length < length) {\n entropy += Math.floor(random() * BASE36).toString(BASE36);\n }\n return entropy;\n}\n\n/**\n * SHA3-512 of `input`, rendered in base36 with the first digit dropped — that\n * digit is biased toward the low end of the alphabet because the digest is not\n * a whole number of base36 digits.\n */\nfunction hashBase36(input: string): string {\n let value = 0n;\n for (const byte of sha3_512(TEXT_ENCODER.encode(input))) {\n value = (value << 8n) | BigInt(byte);\n }\n return value.toString(BASE36).slice(1);\n}\n\n/**\n * A fingerprint of the host environment, mixed into every id so that two\n * processes minting ids at the same millisecond with the same counter still\n * disagree.\n */\nfunction createFingerprint(random: () => number): string {\n const globals = Object.keys(globalThis).toString();\n const entropy = createEntropy(CUID_BIG_LENGTH, random);\n // Upstream writes `globals.length > 0 ? globals + entropy : entropy`. The two\n // arms are the same string — concatenating an empty `globals` IS `entropy` —\n // so the condition names no case, and a branch whose unique coverage cannot\n // be stated is one this codebase does not keep. The digest is unchanged,\n // which the differential test against the pinned upstream package proves.\n return hashBase36(globals + entropy).substring(0, CUID_BIG_LENGTH);\n}\n\n/**\n * One CUID2 sequence.\n *\n * Everything upstream lets a caller replace is replaceable here for the same\n * reason: the fingerprint, counter and random source are the parts that make\n * two processes differ, and a test that cannot fix them cannot compare two\n * implementations at all. `length` is replaceable for the same reason — the\n * salt is as long as the id, so a differential test that only ever saw 24\n * characters would compare one input shape.\n *\n * No length is spellable in a schema: `.cuid(prefix?)` takes none and always\n * mints the published 24, and a schema document that declares one is refused by\n * the reader (J007). The construction therefore states no bound of its own.\n */\nexport function createCuid2(\n options: {\n random?: () => number;\n counter?: () => number;\n length?: number;\n fingerprint?: string;\n } = {}\n): () => string {\n const random = options.random ?? secureFloat;\n const counter =\n options.counter ??\n createCounter(Math.floor(random() * CUID_INITIAL_COUNT_MAX));\n const length = options.length ?? CUID_DEFAULT_LENGTH;\n const fingerprint = options.fingerprint ?? createFingerprint(random);\n return () => {\n const firstLetter = LOWERCASE_LETTERS.charAt(\n Math.floor(random() * CUID_ALPHABET_SIZE)\n );\n const time = Date.now().toString(BASE36);\n const count = counter().toString(BASE36);\n const salt = createEntropy(length, random);\n return (\n firstLetter +\n hashBase36(time + salt + count + fingerprint).substring(1, length)\n );\n };\n}\n\nfunction createCounter(start: number): () => number {\n let count = start;\n return () => {\n const current = count;\n count++;\n return current;\n };\n}\n\n/**\n * The process-wide CUID2 sequence, built on first use.\n *\n * Lazily, because the fingerprint hashes 32 characters of entropy: building it\n * at import would draw randomness from every process that merely loads VibORM,\n * including ones that never mint an id.\n */\nlet processCuid: (() => string) | undefined;\n\nexport const defaultCuid = (prefix?: string) => () =>\n applyIdPrefix(prefix, (processCuid ??= createCuid2())());\n","// String Scalar\n// Standalone scalar class with State generic pattern\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { hasIdPrefix, refuseId } from \"@validation/primitives/id-formats\";\nimport v from \"@validation/primitives/v\";\nimport {\n type AutoGenerate,\n createDefaultState,\n type DefaultValueInput,\n type GeneratorDefaultBrand,\n generatorDefault,\n isGeneratorDefault,\n nullableDefault,\n refuseListGenerator,\n type ScalarState,\n type UpdateState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\nimport {\n defaultCuid,\n defaultKsuid,\n defaultNanoid,\n defaultUlid,\n defaultUuid,\n defaultUuidV7,\n} from \"./autogenerate\";\n\ninterface FormatOptions {\n prefix?: string;\n generate?: true;\n}\ninterface NanoidOptions extends FormatOptions {\n length?: number;\n}\ninterface KeyOptions {\n generate: false;\n prefix?: string;\n}\ntype IdentifierKind = \"uuid\" | \"uuidv7\" | \"ulid\" | \"ksuid\" | \"nanoid\" | \"cuid\";\ntype ExactOptions<Given, Allowed> = Given extends string | number | undefined\n ? unknown\n : Record<Exclude<keyof Given, keyof Allowed>, never>;\ntype GenerationRequested<\n State extends ScalarState<\"string\">,\n Given,\n> = Given extends { generate: true }\n ? true\n : Given extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends { generate: true }\n ? true\n : State[\"isId\"];\ntype GenerationChoice<\n State extends ScalarState<\"string\">,\n Given,\n> = Given extends { generate: true }\n ? true\n : Given extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends {\n generate: infer Choice extends boolean | undefined;\n }\n ? Choice\n : undefined;\ntype HasCustomDefault<State extends ScalarState<\"string\">> =\n State[\"default\"] extends GeneratorDefaultBrand ? false : State[\"hasDefault\"];\ntype FormatState<\n State extends ScalarState<\"string\">,\n Given,\n Kind extends IdentifierKind = IdentifierKind,\n> = {\n autoGenerate: AutoGenerate & {\n kind: Kind;\n implicit?: undefined;\n generate: GenerationChoice<State, Given>;\n };\n hasDefault: HasCustomDefault<State> extends true\n ? true\n : GenerationRequested<State, Given>;\n optional: HasCustomDefault<State> extends true\n ? true\n : GenerationRequested<State, Given>;\n default: HasCustomDefault<State> extends true\n ? State[\"default\"]\n : GenerationRequested<State, Given> extends true\n ? (() => string) & GeneratorDefaultBrand\n : undefined;\n};\ntype KeyState<State extends ScalarState<\"string\">, Given> = Omit<\n FormatState<UpdateState<State, { isId: true }>, Given>,\n \"autoGenerate\"\n> & {\n isId: true;\n isUnique: true;\n autoGenerate: State[\"autoGenerate\"] extends AutoGenerate\n ? Omit<State[\"autoGenerate\"], \"generate\"> & {\n generate: GenerationChoice<State, Given>;\n }\n : {\n kind: \"ulid\";\n implicit: true;\n prefix?: string;\n generate: GenerationChoice<State, Given>;\n };\n};\n\nfunction identifierGenerator(declaration: AutoGenerate): () => string {\n const { kind, prefix, length } = declaration;\n switch (kind) {\n case \"uuid\":\n return defaultUuid(prefix);\n case \"uuidv7\":\n return defaultUuidV7(prefix);\n case \"ulid\":\n return defaultUlid(prefix);\n case \"ksuid\":\n return defaultKsuid(prefix);\n case \"nanoid\":\n return defaultNanoid(length, prefix);\n case \"cuid\":\n return defaultCuid(prefix);\n default:\n return refuseId(\n \"s.string\",\n \"generate\",\n \"This generator is not a string identifier format\"\n );\n }\n}\n\nconst stringBase = v.string();\n\nexport class StringScalar<State extends ScalarState<\"string\">> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n nullable() {\n return new StringScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.string<{\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }>({\n nullable: true,\n array: this.state.array,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n array() {\n if (isGeneratorDefault(this.state.default)) refuseListGenerator(\"s.string\");\n return new StringScalar(\n updateState(this, {\n array: true,\n base: v.string<{\n nullable: State[\"nullable\"];\n array: true;\n schema: State[\"schema\"];\n }>({\n nullable: this.state.nullable,\n array: true,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n id<const Given extends string | KeyOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, KeyOptions>\n ): StringScalar<UpdateState<State, KeyState<State, Given>>>;\n id(options?: string | KeyOptions): StringScalar<ScalarState<\"string\">> {\n const generate = typeof options === \"object\" ? options.generate : undefined;\n const prefix = typeof options === \"string\" ? options : options?.prefix;\n const declared = this.state.autoGenerate;\n if (declared && hasIdPrefix(prefix)) refuseSecondIdPrefix(declared);\n const declaration: AutoGenerate = declared\n ? { ...declared, generate: generate ?? declared.generate }\n : { kind: \"ulid\", prefix, implicit: true, generate };\n return this.withIdentifier(declaration, true);\n }\n\n unique() {\n return new StringScalar(\n updateState(this, {\n isUnique: true,\n }),\n this._nativeType\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new StringScalar(\n updateState(this, {\n hasDefault: true,\n default: value,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n schema<S extends StandardSchemaV1<string>>(schema: S) {\n return new StringScalar(\n updateState(this, {\n schema,\n base: v.string<{\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }>({\n nullable: this.state.nullable,\n array: this.state.array,\n schema,\n }),\n }),\n this._nativeType\n );\n }\n\n /**\n * Maps this scalar to a custom column name in the database\n */\n map(columnName: string) {\n return new StringScalar(\n updateState(this, { columnName }),\n this._nativeType\n );\n }\n\n uuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"uuid\">>>;\n uuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"uuid\", options);\n }\n\n uuidv7<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"uuidv7\">>>;\n uuidv7(\n options?: string | FormatOptions\n ): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"uuidv7\", options);\n }\n\n ksuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"ksuid\">>>;\n ksuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"ksuid\", options);\n }\n\n ulid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"ulid\">>>;\n ulid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"ulid\", options);\n }\n\n cuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"cuid\">>>;\n cuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"cuid\", options);\n }\n\n nanoid<const Given extends number | NanoidOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, NanoidOptions>,\n prefix?: string\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"nanoid\">>>;\n nanoid(\n options?: number | NanoidOptions,\n prefix?: string\n ): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\n \"nanoid\",\n typeof options === \"number\"\n ? { length: options, prefix }\n : (options ?? { prefix })\n );\n }\n\n private withFormat(kind: IdentifierKind, options?: string | NanoidOptions) {\n const configuration: NanoidOptions | undefined =\n typeof options === \"string\" ? { prefix: options } : options;\n return this.withIdentifier(\n {\n kind,\n prefix: configuration?.prefix,\n length: kind === \"nanoid\" ? configuration?.length : undefined,\n generate: configuration?.generate ?? this.state.autoGenerate?.generate,\n },\n this.state.isId\n );\n }\n\n private withIdentifier(declaration: AutoGenerate, isId: boolean) {\n const generator = identifierGenerator(declaration);\n const customDefault =\n this.state.hasDefault && !isGeneratorDefault(this.state.default);\n const generate =\n declaration.generate === true || (isId && declaration.generate !== false);\n const installed = generate && !customDefault;\n if (this.state.array && installed) refuseListGenerator(\"s.string\");\n return new StringScalar(\n updateState(this, {\n isId,\n isUnique: isId || this.state.isUnique,\n autoGenerate: declaration,\n hasDefault: customDefault || installed,\n optional: customDefault || installed,\n default: installed\n ? generatorDefault(generator)\n : customDefault\n ? this.state.default\n : undefined,\n }),\n this._nativeType\n );\n }\n\n private _internal?: {\n state: State;\n nativeType: NativeTypeDeclaration | undefined;\n };\n\n get [\"~\"]() {\n return (this._internal ??= {\n state: this.state,\n nativeType: this._nativeType,\n });\n }\n}\n\nexport const string = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) => {\n return new StringScalar(\n createDefaultState(\"string\", stringBase),\n admitNativeType(\"s.string\", nativeType)\n );\n};\n\nfunction refuseSecondIdPrefix(declared: {\n readonly kind: string;\n readonly prefix?: string | undefined;\n}): never {\n return refuseId(\n \"s.string().id\",\n \"prefix\",\n `This field already declares a '${declared.kind}' generator${declared.prefix ? ` with the prefix '${declared.prefix}'` : \"\"}. A prefix is spelled once, on the call that declares the format`\n );\n}\n"],"mappings":"8dAWA,SAAgB,mCACd,EACmC,CACnC,IAAM,EAAoB,IAAI,IAC9B,IAAK,GAAM,CAAC,EAAU,KAAU,EAAe,CAC7C,GAEE,OAAO,GAAU,WADjB,GAEA,CAAC,EAAM,MAAM,OACb,CAAC,EAAM,MAAM,OAAO,QAEpB,MAAO,CACL,K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AAK,YACN,CAGH,UAKA,GAAK,KAAO,CACV,MAAQ,MAAK,YAAc,CACzB,MAAO,KAAK,MACZ,WAAY,KAAK,YAClB,GAIL,MAAa,OAIX,GAEO,IAAI,EACT,mBAAmB,SAAU,EAAW,CACxC,gBAAgB,WAAY,EAAW,CACxC,CAGH,SAAS,qBAAqB,EAGpB,CACR,OAAO,EACL,gBACA,SACA,kCAAkC,EAAS,KAAK,aAAa,EAAS,OAAS,qBAAqB,EAAS,OAAO,GAAK,GAAG,kEAC7H"}
|
package/dist/schema/json.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $r as JunctionReferentialAction, It as VibORMClient, Lt as VibORMConfig, Zn as IndexType, ar as AutoGenerateType, bn as Schema, ea as NativeType, ei as ReferentialAction, lr as ScalarType, ta as NativeTypeMap, wr as JsonValue } from "../index-
|
|
1
|
+
import { $r as JunctionReferentialAction, It as VibORMClient, Lt as VibORMConfig, Zn as IndexType, ar as AutoGenerateType, bn as Schema, ea as NativeType, ei as ReferentialAction, lr as ScalarType, ta as NativeTypeMap, wr as JsonValue } from "../index-BlBkgxtx.mjs";
|
|
2
2
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
3
|
|
|
4
4
|
//#region src/schema/json/document.d.ts
|
package/dist/schema/json.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"../chunk-BuuaeEvq.mjs";import{c as t,i as n,r}from"../value-guards-CK9guf2Z.mjs";import{k as i}from"../base-wlv81COV.mjs";import{t as a}from"../validation-pfpKPPZ_.mjs";import{A as o,D as s,E as c,_ as l,h as u}from"../v-C2XN11Gy.mjs";import{Pt as d}from"../geo-point-codec-CIZxuIvE.mjs";import{a as f,d as p,l as m,o as h,u as g}from"../model-D94xU8jq.mjs";import{i as _,r as v,s as y,t as b}from"../scalar-BgxfbRLw.mjs";import{t as x}from"../hydration-BNEFeV5v.mjs";import{a as S}from"../validator-DqI5RlVU.mjs";import{a as C,n as w}from"../native-types-CQH05hcr.mjs";import{_ as T,a as E,c as D,d as O,f as ee,g as te,h as ne,i as re,l as ie,m as ae,n as oe,o as se,p as ce,r as k,s as A,t as j}from"../to-many-CJ-8_caR.mjs";import{t as M}from"../types-C4v6iAmY.mjs";const N=/~/g,P=/\//g;function pointer(e,...t){let n=e;for(let e of t)n+=`/${e.replace(N,`~0`).replace(P,`~1`)}`;return n}function addIssue(e,t,n,r){e.push({path:t,message:`[${n}] ${r}`})}function refuseDocument(e,t){return new a({kind:`schema-builder`,builder:`schema-json`,path:``},e,t===void 0?void 0:{cause:t})}function throwIfRefused(e){if(e.length>0)throw refuseDocument(e)}function member(e,t,n,r){return guardedValue(e,t,n,r,`J004`)}function guardedValue(e,t,n,r,a){try{return Reflect.get(e,t)}catch(e){throw addIssue(r,pointer(n,t),a,`Reading this value threw`),refuseDocument(r,i(e))}}function inspectPlainRecord(e,t,n,r){try{return l(e)}catch(e){throw addIssue(n,t,r,`Inspecting this value's prototype threw`),refuseDocument(n,i(e))}}function inspectKeys(e,t,n,r){try{return u(e)}catch(e){throw addIssue(n,t,r,`Enumerating this value's keys threw`),refuseDocument(n,i(e))}}function renderValue(e){return typeof e==`bigint`?`${e}n`:typeof e==`object`?`[${typeof e}]`:String(e)}function refuseFromBuilder(e,t){let n=[];throw addIssue(n,e,`J010`,t.message),refuseDocument(n,t)}const F=`$bigint`,I=`$date`,L=`$bytes`,R=`$raw`,z=`$jsonNull`,B=new Set([F,I,L,R,z]),V=/^-?\d+$/,H=`'${F}' (a decimal integer string), '${I}' (an ISO timestamp), '${L}' (base64), '${R}' (the literal it wraps), '${z}' ('JsonNull' or 'DbNull')`;function reservedKey(e){let t=e.length===1?e[0]:void 0;return t?.startsWith(`$`)===!0?t:void 0}function readDefaultValue(e,t,n){return readValue(e,t,n,new Set)}function readValue(e,t,r,i){if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`){if(Number.isFinite(e))return e;addIssue(r,t,`J004`,`A default must be a finite number`);return}if(Array.isArray(e))return readArray(e,t,r,i);if(inspectPlainRecord(e,t,r,`J004`))return readRecord(e,t,r,i);addIssue(r,t,`J004`,n(e)?"A function default has no document spelling — use `generate`, a literal, or a database default through `native`":`A default must be a JSON value; a value outside JSON takes a tag — ${H}`)}function readArray(e,t,n,r){if(enterCycle(e,t,n,r,`J004`))return;let i=[];for(let a=0;a<e.length;a+=1){let o=pointer(t,String(a)),s=readValue(member(e,String(a),t,n),o,n,r);if(s===void 0)return;i.push(s)}return r.delete(e),i}function readRecord(e,t,n,r){if(enterCycle(e,t,n,r,`J004`))return;let i=inspectKeys(e,t,n,`J004`),a=reservedKey(i);if(a!==void 0&&!B.has(a)){addIssue(n,t,`J008`,`'${a}' is not a tag this format defines. The tags are ${H}`);return}let o=m();for(let a of i){let i=readValue(member(e,a,t,n),pointer(t,a),n,r);if(i===void 0)return;p(o,a,i)}return r.delete(e),o}function enterCycle(e,t,n,r,i){return r.has(e)?(addIssue(n,t,i,`This default contains a cycle; a document holds a finite value`),!0):(r.add(e),!1)}function decodeDefault(e,t){if(Array.isArray(e))return e.map((e,n)=>decodeDefault(e,pointer(t,String(n))));if(typeof e!=`object`||!e)return e;let n=reservedKey(Object.keys(e));if(n===void 0)return decodeBody(e,t);let r=e[n];if(n===R)return decodeRaw(r,t);if(n===F)return decodeBigInt(r,t);if(n===I)return decodeDate(r,t);if(n===z){if(r===`JsonNull`)return s;if(r===`DbNull`)return c;throw refuseTag(t,`'${z}' takes 'JsonNull' or 'DbNull'`)}return decodeBytes(r,t)}function decodeBody(e,t){let n=m();for(let r of Object.keys(e))p(n,r,decodeDefault(e[r]??null,pointer(t,r)));return n}function decodeRaw(e,t){return typeof e!=`object`||!e?e:Array.isArray(e)?decodeDefault(e,t):decodeBody(e,t)}function decodeBigInt(e,t){if(typeof e==`string`&&V.test(e))return BigInt(e);throw refuseTag(t,`'${F}' takes a decimal integer string`)}function decodeDate(e,t){if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}throw refuseTag(t,`'${I}' takes a string naming an instant`)}function decodeBytes(e,t){if(typeof e==`string`)try{return decodeBase64(e)}catch{}throw refuseTag(t,`'${L}' takes a base64 string`)}function refuseTag(e,t){let n=[];return addIssue(n,e,`J008`,`${t}. The tags are ${H}`),refuseDocument(n)}function decodeBase64(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function encodeDefault(e,t,n){return encodeValue(e,t,n,new Set)}function encodeValue(e,n,i,a){let s=o(e);if(s===`JsonNull`||s===`DbNull`)return tagged(z,s);if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isFinite(e)?e:refuseValue(i,n,"A non-finite number has no JSON spelling; `JSON.stringify` would write it as `null`");if(typeof e==`bigint`)return tagged(F,e.toString(10));if(t(e))try{return tagged(L,encodeBase64(e))}catch{return refuseValue(i,n,`This byte string has a detached buffer and cannot be serialized`)}return r(e)?Number.isNaN(Date.prototype.getTime.call(e))?refuseValue(i,n,`An invalid Date names no instant`):tagged(I,Date.prototype.toISOString.call(e)):Array.isArray(e)?encodeArray(e,n,i,a):inspectPlainRecord(e,n,i,`J009`)?encodeRecord(e,n,i,a):refuseValue(i,n,`This default holds a value the document cannot state — a JSON value, a bigint, a Date or a byte string is what a default may be`)}function tagged(e,t){let n=m();return p(n,e,t),n}function encodeArray(e,t,n,r){if(enterCycle(e,t,n,r,`J009`))return;let i=[];for(let a=0;a<e.length;a+=1){let o=String(a),s=encodeValue(guardedValue(e,o,t,n,`J009`),pointer(t,o),n,r);if(s===void 0)return;i.push(s)}return r.delete(e),i}function encodeRecord(e,t,n,r){if(enterCycle(e,t,n,r,`J009`))return;let i=m();for(let a of inspectKeys(e,t,n,`J009`)){let o=encodeValue(guardedValue(e,a,t,n,`J009`),pointer(t,a),n,r);if(o===void 0)return;p(i,a,o)}if(r.delete(e),reservedKey(Object.keys(i))===void 0)return i;let a=m();return p(a,R,i),a}function refuseValue(e,t,n){addIssue(e,t,`J009`,n)}function encodeBase64(e){let t=``,n=Uint8Array.prototype.values.call(e);for(let e of n)t+=String.fromCharCode(e);return btoa(t)}const U=1;function isRelationField(e){return e.type===`toOne`||e.type===`toMany`}const W={string:b,int:se,number:re,boolean:ne,datetime:ce,date:ae,time:ee,bigint:T,json:E,blob:te,vector:oe,point:k},G=new Set([...Object.keys(W),`decimal`,`enum`]);function builderMethod(e,t){let n=Reflect.get(e,t);return typeof n==`function`?n:void 0}function interpret(e,t){let n={},r=pointer(``,`models`);refuseUnknownFieldSchemas(e,t);for(let[i,a]of Object.entries(e.models))n[i]=buildModel(i,a,e,n,pointer(r,i),t);return n}function refuseUnknownFieldSchemas(e,t){if(t===void 0)return;let n=[];for(let r of Object.keys(t)){let t=r.indexOf(`.`),i=e.models[r.slice(0,t)]?.fields[r.slice(t+1)];i!==void 0&&!isRelationField(i)||addIssue(n,``,`J006`,`Field schema '${r}' does not name a scalar field of this schema; spell it '<model>.<field>'`)}if(n.length>0)throw refuseDocument(n)}function buildModel(e,t,n,r,i,a){let o=pointer(i,`fields`),s={};for(let[i,c]of Object.entries(t.fields)){let t=pointer(o,i);if(isRelationField(c)){s[i]=buildRelation(c,r,t);continue}s[i]=buildScalar(c,n,t,a?.[`${e}.${i}`])}let c=call(i,()=>f(s));if(t.table!==void 0){let e=t.table;c=call(pointer(i,`table`),()=>c.map(e))}for(let[e,n]of(t.indexes??[]).entries()){let t=pointer(i,`indexes`,String(e)),r={...n.name===void 0?{}:{name:n.name},...n.unique===void 0?{}:{unique:n.unique},...n.type===void 0?{}:{type:n.type}};c=call(t,()=>Reflect.apply(c.index,c,[n.fields,r]))}for(let[e,n]of(t.ids??[]).entries())c=call(pointer(i,`ids`,String(e)),()=>c.id(n.fields,options(n.name)));for(let[e,n]of(t.uniques??[]).entries())c=call(pointer(i,`uniques`,String(e)),()=>c.unique(n.fields,options(n.name)));if(t.omit!==void 0){let e={};for(let n of t.omit)e[n]=!0;c=call(pointer(i,`omit`),()=>c.omit(e))}return c}function options(e){return e===void 0?{}:{name:e}}function buildScalar(e,t,n,r){let i=e.type,a=createScalar(e,t,n);if(e.array&&(a=modify(a,`array`,[],i,pointer(n,`array`))),e.nullable&&(a=modify(a,`nullable`,[],i,pointer(n,`nullable`))),e.id){let t=e.generate?.implicit===!0,r=e.generate?.generate===!1?[{generate:!1,prefix:t?e.generate.prefix:void 0}]:t&&e.generate?.prefix!==void 0?[e.generate.prefix]:[];a=modify(a,`id`,r,i,pointer(n,`id`))}e.unique&&(a=modify(a,`unique`,[],i,pointer(n,`unique`))),e.withoutTimezone&&(a=modify(a,`withoutTimezone`,[],i,pointer(n,`withoutTimezone`))),e.dimension!==void 0&&(a=modify(a,`dimension`,[e.dimension],i,pointer(n,`dimension`))),e.generate!==void 0&&e.generate.implicit!==!0&&(a=applyGenerate(a,e.generate,i,n));let o=e.default;return o!==void 0&&(a=applyDefault(a,e,o,n)),e.column!==void 0&&(a=modify(a,`map`,[e.column],i,pointer(n,`column`))),r!==void 0&&(a=modify(a,`schema`,[r],i,pointer(n,`schema`))),a}function createScalar(e,t,n){if(e.type===`decimal`){let{precision:t,scale:r}=e;return call(n,()=>ie({precision:t,scale:r}))}let r=e.native??e.nativeByDialect;if(e.type!==`enum`){let t=W[e.type];return call(n,()=>r===void 0?t():t(r))}let i=resolveEnum(e,t,n),a=call(n,()=>A(i.values,r));if(i.name===void 0)return a;let o=i.name;return modify(a,`name`,[o],`enum`,pointer(n,`enum`))}function resolveEnum(e,t,n){let r=e.enum;if(Array.isArray(r))return{values:r};let i=t.enums?.[r];if(i!==void 0)return i;let a=[];throw addIssue(a,pointer(n,`enum`),`J006`,`\`enum\` names '${r}', which \`enums\` does not declare`),refuseDocument(a)}function modify(e,t,n,r,i){let a=builderMethod(e,t);if(a===void 0){let e=[];throw addIssue(e,i,`J007`,`A '${r}' field has no '${t}' modifier`),refuseDocument(e)}return call(i,()=>a.apply(e,n))}function applyGenerate(e,t,n,r){let i=pointer(r,`generate`),a=![`now`,`updatedAt`,`increment`].includes(t.kind),o=t.generate===!1?{prefix:t.prefix,length:t.length}:{prefix:t.prefix,length:t.length,generate:!0},s=a?[o]:[t.prefix],c=modify(e,t.kind,s,n,i),l=c[`~`].state.autoGenerate;if(l?.prefix===t.prefix&&l?.length===t.length)return c;let u=[];throw addIssue(u,i,`J007`,`The '${t.kind}' generator does not take the 'prefix' or 'length' this node declares`),refuseDocument(u)}function applyDefault(e,t,n,r){let i=pointer(r,`default`),a=decodeDefault(n,i);if(t.type===`json`&&o(a)!==void 0)return modify(e,`default`,[a],t.type,i);let s=e[`~`].state.base[`~standard`].validate(a),c=t.type===`bigint`&&[a].flat().some(e=>typeof e==`string`);if(s.issues||c){let e=s.issues?s.issues.map(e=>e.message).join(`; `):`a bigint is written {"$bigint": "<integer>"}`,n=[];throw addIssue(n,i,`J008`,`A '${t.type}' default must be a value of the field's own domain: ${e}`),refuseDocument(n)}return e instanceof D?O(e,s.value):modify(e,`default`,[a],t.type,i)}function buildRelation(e,t,n){let r=e.target===void 0?buildVariantRelation(e,t,n):buildModelRelation(e,t,n);if(e.name===void 0)return r;let i=e.name;return call(pointer(n,`name`),()=>r.name(i))}function buildModelRelation(e,t,n){let r=e.target,getter=()=>t[r],i=e.type===`toOne`?h:j,a=call(n,()=>Reflect.apply(i,void 0,[getter]));if(e.fields!==void 0){let t=e.fields;a=call(pointer(n,`fields`),()=>a.fields(...t))}if(e.references!==void 0){let t=e.references;a=call(pointer(n,`references`),()=>a.references(...t))}for(let t of[`onDelete`,`onUpdate`]){let r=e[t];r!==void 0&&(a=call(pointer(n,t),()=>a[t](r)))}return e.junction!==void 0&&(a=applyJunction(a,e.junction,n)),a}function buildVariantRelation(e,t,n){let r={};for(let[n,i]of Object.entries(e.variants))r[n]=()=>t[i];let i=e.type===`toOne`?h:j,a=e.values===void 0?[r]:[r,{values:e.values}],o=call(n,()=>Reflect.apply(i,void 0,a));if(e.through!==void 0){let t=e.through;o=call(pointer(n,`through`),()=>o.through(t))}return e.optional&&(o=call(pointer(n,`optional`),()=>o.optional())),o}const le=[[`table`,`through`],[`source`,`source`],[`target`,`target`],[`onDelete`,`onDelete`],[`onUpdate`,`onUpdate`],[`onDeleteSides`,`onDelete`],[`onUpdateSides`,`onUpdate`]];function applyJunction(e,t,n){let r=e,i=pointer(n,`junction`);for(let[e,n]of le){let a=t[e];a!==void 0&&(r=call(pointer(i,e),()=>r[n](a)))}return r}function call(e,t){try{return t()}catch(t){return refuseFromBuilder(e,i(t))}}const K={cascade:!0,setNull:!0,restrict:!0,noAction:!0},q={cascade:!0,restrict:!0,noAction:!0},J={btree:!0,hash:!0,gin:!0,gist:!0,fulltext:!0,spatial:!0},Y={uuid:!0,uuidv7:!0,ulid:!0,ksuid:!0,nanoid:!0,cuid:!0,increment:!0,now:!0,updatedAt:!0},isReferentialAction=e=>typeof e==`string`&&Object.hasOwn(K,e),isJunctionAction=e=>typeof e==`string`&&Object.hasOwn(q,e),isIndexType=e=>typeof e==`string`&&Object.hasOwn(J,e),isGenerateKind=e=>typeof e==`string`&&Object.hasOwn(Y,e),isNativeDialect=e=>typeof e==`string`&&w.some(t=>t===e),isScalarTypeName=e=>typeof e==`string`&&G.has(e),ue=[`version`,`enums`,`models`],de=[`values`,`name`],fe=[`table`,`fields`,`indexes`,`ids`,`uniques`,`omit`],pe=[`fields`,`name`,`unique`,`type`,`where`],me=[`fields`,`name`],he=[`db`,`type`],ge=[`kind`,`prefix`,`length`,`implicit`,`generate`],X=[`table`,`source`,`target`,`onDelete`,`onUpdate`,`onDeleteSides`,`onUpdateSides`],_e=[`source`,`target`],ve=[`table`,`source`,`target`],Z=[`type`,`native`,`nativeByDialect`,`nullable`,`array`,`id`,`unique`,`column`,`default`,`generate`,`enum`,`dimension`,`precision`,`scale`,`withoutTimezone`],ye=[...new Set([...Z,...relationKeys({cardinality:`one`,variants:!1}),...relationKeys({cardinality:`many`,variants:!1}),...relationKeys({cardinality:`one`,variants:!0}),...relationKeys({cardinality:`many`,variants:!0})])];function relationKeys(e){let t=[`type`,`name`];return e.variants?(t.push(`variants`,`values`),t.push(e.cardinality===`one`?`optional`:`through`),t):(t.push(`target`),e.cardinality===`one`?(t.push(`fields`,`references`,`onDelete`,`onUpdate`),t):(t.push(`junction`),t))}function elements(e,t,n){let r=[];for(let i=0;i<e.length;i+=1)r.push(member(e,String(i),t,n));return r}function asRecord(e,t,n,r){if(inspectPlainRecord(e,t,n,`J004`))return e;addIssue(n,t,`J004`,`${r} must be a plain JSON object`)}function asString(e,t,n,r){if(typeof e==`string`)return e;addIssue(n,t,`J004`,`${r} must be a string`)}function asBoolean(e,t,n,r){if(typeof e==`boolean`)return e;addIssue(n,t,`J004`,`${r} must be a boolean`)}function asNumber(e,t,n,r){if(typeof e==`number`&&Number.isFinite(e))return e;addIssue(n,t,`J004`,`${r} must be a finite number`)}function asStringArray(e,t,n,r){if(!Array.isArray(e)){addIssue(n,t,`J004`,`${r} must be an array of strings`);return}let i=[],a=!0;for(let[o,s]of elements(e,t,n).entries()){let e=asString(s,pointer(t,String(o)),n,r);if(e===void 0){a=!1;continue}i.push(e)}return a?i:void 0}function refuseUnknownKeys(e,t,n,r,i=`this node`){for(let a of inspectKeys(e,n,r,`J004`)){if(!t.includes(a)){addIssue(r,pointer(n,a),`J003`,`Unknown key '${a}'; ${i} declares ${renderKeys(t)}`);continue}member(e,a,n,r)===void 0&&addIssue(r,pointer(n,a),`J004`,`'${a}' is \`undefined\`; a document omits an absent key rather than setting it to \`undefined\``)}}function refuseInvalidKey(e,t,n,r){return d(e)?!0:(addIssue(n,t,`J005`,`${r} '${e}' is not a valid schema identifier`),!1)}function renderKeys(e){return e.map(e=>`'${e}'`).join(`, `)}function readDocument(e){let t=[],n=intake(e,t);throwIfRefused(t);let r=asRecord(n,``,t,`A schema document`);if(r===void 0)throw refuseDocument(t);refuseUnknownKeys(r,ue,``,t);let i=member(r,`version`,``,t);if(i!==1)throw addIssue(t,pointer(``,`version`),`J002`,`Unsupported document version ${renderValue(i)}; this parser reads version 1`),refuseDocument(t);let a={version:1,models:readModels(r,t)},o=readEnums(r,t);return o!==void 0&&(a.enums=o),resolveReferences(a,t),throwIfRefused(t),a}function intake(e,t){if(typeof e!=`string`)return e;try{return JSON.parse(e)}catch(e){addIssue(t,``,`J001`,`The document is not valid JSON: ${String(e)}`);return}}function readEnums(e,t){let n=pointer(``,`enums`),r=member(e,`enums`,``,t);if(r===void 0)return;let i=asRecord(r,n,t,"`enums`");if(i===void 0)return;let a={};for(let e of inspectKeys(i,n,t,`J004`)){let r=pointer(n,e);if(!refuseInvalidKey(e,r,t,`Enum reference`))continue;let o=readEnumNode(member(i,e,n,t),r,t);o!==void 0&&(a[e]=o)}return a}function readEnumNode(e,t,n){let r=asRecord(e,t,n,`An enum definition`);if(r===void 0)return;refuseUnknownKeys(r,de,t,n);let i=asStringArray(member(r,`values`,t,n),pointer(t,`values`),n,"`values`");if(i===void 0)return;let a={values:i},o=member(r,`name`,t,n);if(o!==void 0){let e=asString(o,pointer(t,`name`),n,"`name`");e!==void 0&&(a.name=e)}return a}function readModels(e,t){let n=pointer(``,`models`),r={},i=asRecord(member(e,`models`,``,t),n,t,"`models`");if(i===void 0)return r;for(let e of inspectKeys(i,n,t,`J004`)){let a=pointer(n,e);if(!refuseInvalidKey(e,a,t,`Model key`))continue;let o=readModelNode(member(i,e,n,t),a,t);o!==void 0&&(r[e]=o)}return r}function readModelNode(e,t,n){let r=asRecord(e,t,n,`A model`);if(r===void 0)return;refuseUnknownKeys(r,fe,t,n);let i={fields:readFields(r,t,n)},a=member(r,`table`,t,n);if(a!==void 0){let e=asString(a,pointer(t,`table`),n,"`table`");e!==void 0&&(i.table=e)}let o=readIndexes(r,t,n);o!==void 0&&(i.indexes=o);let s=readCompoundKeys(r,`ids`,t,n);s!==void 0&&(i.ids=s);let c=readCompoundKeys(r,`uniques`,t,n);c!==void 0&&(i.uniques=c);let l=readOmit(r,t,n);return l!==void 0&&(i.omit=l),i}function readFields(e,t,n){let r=pointer(t,`fields`),i={},a=asRecord(member(e,`fields`,t,n),r,n,"`fields`");if(a===void 0)return i;for(let e of inspectKeys(a,r,n,`J004`)){let t=pointer(r,e);if(!refuseInvalidKey(e,t,n,`Field key`))continue;let o=readFieldNode(member(a,e,r,n),t,n);o!==void 0&&(i[e]=o)}return i}function readIndexes(e,t,n){let r=pointer(t,`indexes`),i=member(e,`indexes`,t,n);if(i===void 0)return;if(!Array.isArray(i)){addIssue(n,r,`J004`,"`indexes` must be an array");return}let a=[];for(let[e,t]of elements(i,r,n).entries()){let i=readIndexNode(t,pointer(r,String(e)),n);i!==void 0&&a.push(i)}return a}function readIndexNode(e,t,n){let r=asRecord(e,t,n,`An index`);if(r===void 0)return;inspectKeys(r,t,n,`J004`).includes(`where`)&&addIssue(n,pointer(t,`where`),`J009`,"`where` is refused in v1: it is raw SQL interpolated unescaped into DDL, and a machine-written document must not carry an execution channel. It returns when a structured predicate form exists"),refuseUnknownKeys(r,pe,t,n);let i=asStringArray(member(r,`fields`,t,n),pointer(t,`fields`),n,"`fields`");if(i===void 0)return;let a={fields:i},o=member(r,`name`,t,n);if(o!==void 0){let e=asString(o,pointer(t,`name`),n,"`name`");e!==void 0&&(a.name=e)}let s=member(r,`unique`,t,n);if(s!==void 0){let e=asBoolean(s,pointer(t,`unique`),n,"`unique`");e!==void 0&&(a.unique=e)}let c=member(r,`type`,t,n);return c!==void 0&&(isIndexType(c)?a.type=c:addIssue(n,pointer(t,`type`),`J004`,`\`type\` must be one of ${renderKeys(Object.keys(J))}`)),a}function readCompoundKeys(e,t,n,r){let i=pointer(n,t),a=member(e,t,n,r);if(a===void 0)return;if(!Array.isArray(a)){addIssue(r,i,`J004`,`\`${t}\` must be an array`);return}let o=[];for(let[e,t]of elements(a,i,r).entries()){let n=readCompoundKeyNode(t,pointer(i,String(e)),r);n!==void 0&&o.push(n)}return o}function readCompoundKeyNode(e,t,n){let r=asRecord(e,t,n,`A compound key`);if(r===void 0)return;refuseUnknownKeys(r,me,t,n);let i=asStringArray(member(r,`fields`,t,n),pointer(t,`fields`),n,"`fields`");if(i===void 0)return;let a={fields:i},o=member(r,`name`,t,n);if(o!==void 0){let e=asString(o,pointer(t,`name`),n,"`name`");e!==void 0&&(a.name=e)}return a}function readOmit(e,t,n){let r=member(e,`omit`,t,n);if(r!==void 0)return asStringArray(r,pointer(t,`omit`),n,"`omit`")}function readFieldNode(e,t,n){let r=asRecord(e,t,n,`A field`);if(r===void 0)return;let i=member(r,`type`,t,n);if(i===`toOne`||i===`toMany`)return readRelationField(r,i,t,n);if(isScalarTypeName(i))return readScalarField(r,i,t,n);addIssue(n,pointer(t,`type`),`J004`,`\`type\` must be 'toOne', 'toMany', or one of ${renderKeys([...G])}`),refuseUnknownKeys(r,ye,t,n,`a field node`)}function readScalarField(e,t,n,r){refuseUnknownKeys(e,Z,n,r);let i=readScalarArm(e,t,n,r);if(i===void 0)return;readFlag(e,`nullable`,n,r,i),readFlag(e,`array`,n,r,i),readFlag(e,`id`,n,r,i),readFlag(e,`unique`,n,r,i),readFlag(e,`withoutTimezone`,n,r,i);let a=member(e,`column`,n,r);if(a!==void 0){let e=asString(a,pointer(n,`column`),r,"`column`");e!==void 0&&(i.column=e)}let o=member(e,`dimension`,n,r);if(o!==void 0)if(t===`point`)refusePointModifier(`dimension`,n,r);else{let e=asNumber(o,pointer(n,`dimension`),r,"`dimension`");e!==void 0&&(i.dimension=e)}t!==`decimal`&&(refuseDecimalDomainBound(e,`precision`,n,r),refuseDecimalDomainBound(e,`scale`,n,r));let s=member(e,`native`,n,r);if(s!==void 0)if(i.type===`point`)refusePointModifier(`native`,n,r);else if(i.type===`decimal`)addIssue(r,pointer(n,`native`),`J003`,"`native` does not belong to a decimal field; its physical type is derived from `precision` and `scale`");else{let e=readNativeNode(s,pointer(n,`native`),r);e!==void 0&&(i.native=e)}let c=member(e,`nativeByDialect`,n,r);if(c!==void 0)if(i.type===`point`)refusePointModifier(`nativeByDialect`,n,r);else if(i.type===`decimal`||s!==void 0)addIssue(r,pointer(n,`nativeByDialect`),`J003`,i.type===`decimal`?"`nativeByDialect` does not belong to a decimal field; its physical type is derived from `precision` and `scale`":"`native` and `nativeByDialect` are two spellings of one declaration; a field carries at most one");else{let e=readNativeByDialectNode(c,pointer(n,`nativeByDialect`),r);e!==void 0&&(i.nativeByDialect=e)}let l=member(e,`generate`,n,r);if(l!==void 0)if(t===`point`)refusePointModifier(`generate`,n,r);else{let e=readGenerateNode(l,pointer(n,`generate`),r,i.id===!0);e!==void 0&&(i.generate=e)}let u=member(e,`default`,n,r);if(u!==void 0){let e=readDefaultValue(u,pointer(n,`default`),r);e!==void 0&&(i.default=e)}return i}function readRequiredDomainBound(e,t,n,r){let i=member(e,t,n,r);if(i===void 0){addIssue(r,pointer(n,t),`J004`,`A decimal field must declare \`${t}\``);return}return asNumber(i,pointer(n,t),r,`\`${t}\``)}function refuseDecimalDomainBound(e,t,n,r){member(e,t,n,r)!==void 0&&addIssue(r,pointer(n,t),`J003`,`\`${t}\` belongs only to a field of type 'decimal'`)}function readScalarArm(e,t,n,r){let i=member(e,`enum`,n,r),a=pointer(n,`enum`);if(t!==`enum`){if(i!==void 0&&addIssue(r,a,`J003`,"`enum` belongs to a field of type 'enum'"),t===`decimal`){let i=readRequiredDomainBound(e,`precision`,n,r),a=readRequiredDomainBound(e,`scale`,n,r);return i===void 0||a===void 0?void 0:{type:t,precision:i,scale:a}}return{type:t}}if(i===void 0){addIssue(r,a,`J004`,"An enum field declares `enum` as an `enums` reference or an inline array of values");return}if(typeof i==`string`)return{type:t,enum:i};let o=asStringArray(i,a,r,"`enum`");if(o!==void 0)return{type:t,enum:o}}function readFlag(e,t,n,r,i){let a=member(e,t,n,r);if(a===void 0)return;if(i.type===`point`&&t!==`nullable`){refusePointModifier(t,n,r);return}let o=asBoolean(a,pointer(n,t),r,`\`${t}\``);if(o!==void 0){if(t===`nullable`){i.nullable=o;return}i.type!==`point`&&(i[t]=o)}}function refusePointModifier(e,t,n){addIssue(n,pointer(t,e),`J007`,`A 'point' field has no '${e}' modifier`)}function readNativeNode(e,t,n){let r=asRecord(e,t,n,"`native`");if(r===void 0)return;refuseUnknownKeys(r,he,t,n);let i=member(r,`db`,t,n),a=asString(member(r,`type`,t,n),pointer(t,`type`),n,"`native.type`");if(!isNativeDialect(i)){addIssue(n,pointer(t,`db`),`J004`,`\`native.db\` must be one of ${renderKeys(w)}`);return}if(a!==void 0){if(!v(i,a)){addIssue(n,pointer(t,`type`),`J011`,_(i));return}return{db:i,type:a}}}function readNativeByDialectNode(e,t,n){let r=asRecord(e,t,n,"`nativeByDialect`");if(r===void 0)return;refuseUnknownKeys(r,w,t,n);let i={},a=readDialectEntry(r,`pg`,t,n);a!==void 0&&(i.pg=a);let o=readDialectEntry(r,`mysql`,t,n);o!==void 0&&(i.mysql=o);let s=readDialectEntry(r,`sqlite`,t,n);return s!==void 0&&(i.sqlite=s),i}function readDialectEntry(e,t,n,r){let i=member(e,t,n,r);if(i===void 0)return;let a=pointer(n,t),o=readNativeNode(i,a,r);if(o!==void 0){if(o.db!==t){addIssue(r,pointer(a,`db`),`J004`,`The '${t}' entry's \`db\` must be '${t}'`);return}return{db:t,type:o.type}}}function readGenerateNode(e,t,n,r){let i=asRecord(e,t,n,"`generate`");if(i===void 0)return;refuseUnknownKeys(i,ge,t,n);let a=member(i,`kind`,t,n);if(!isGenerateKind(a)){addIssue(n,pointer(t,`kind`),`J004`,`\`generate.kind\` must be one of ${renderKeys(Object.keys(Y))}`);return}let o={kind:a},s=member(i,`generate`,t,n);if(s!==void 0){let e=asBoolean(s,pointer(t,`generate`),n,"`generate`");a===`now`||a===`updatedAt`||a===`increment`?addIssue(n,pointer(t,`generate`),`J004`,`An explicit generation choice belongs only to string identifier formats`):e!==void 0&&(o.generate=e)}let c=member(i,`prefix`,t,n);if(c!==void 0){let e=asString(c,pointer(t,`prefix`),n,"`prefix`");e!==void 0&&(o.prefix=e)}let l=member(i,`length`,t,n);if(l!==void 0){let e=asNumber(l,pointer(t,`length`),n,"`length`");e!==void 0&&(o.length=e)}let u=member(i,`implicit`,t,n);return u!==void 0&&asBoolean(u,pointer(t,`implicit`),n,"`implicit`")===!0&&(a===`ulid`?r?o.implicit=!0:addIssue(n,pointer(t,`implicit`),`J004`,"`generate.implicit` describes the ULID `.id()` installs, so it belongs only beside `id: true`"):addIssue(n,pointer(t,`implicit`),`J004`,'`generate.implicit` describes the ULID `.id()` installs, so it belongs only to `kind: "ulid"`')),o}function readRelationField(e,t,n,r){let i=member(e,`target`,n,r),a=member(e,`variants`,n,r);if(i===void 0==(a===void 0)){addIssue(r,n,`J004`,"A relation names exactly one target domain: `target` for one model, or `variants` for named variants");return}let o=t===`toOne`?`one`:`many`;refuseUnknownKeys(e,relationKeys({cardinality:o,variants:a!==void 0}),n,r);let s=readName(e,n,r);if(i===void 0)return readVariantTargetArm(e,{type:t,variants:a},s,o,n,r);let c=asString(i,pointer(n,`target`),r,"`target`");if(c!==void 0)return readModelTargetArm(e,{type:t,target:c},s,o,n,r)}function readName(e,t,n){let r=member(e,`name`,t,n);if(r!==void 0)return asString(r,pointer(t,`name`),n,"`name`")}function readModelTargetArm(e,t,n,r,i,a){if(n!==void 0&&(t.name=n),r===`many`){let n=member(e,`junction`,i,a);if(n!==void 0){let e=readJunctionNode(n,pointer(i,`junction`),a);e!==void 0&&(t.junction=e)}return t}for(let n of[`fields`,`references`]){let r=member(e,n,i,a);if(r===void 0)continue;let o=asStringArray(r,pointer(i,n),a,`\`${n}\``);o!==void 0&&(t[n]=o)}for(let n of[`onDelete`,`onUpdate`]){let r=member(e,n,i,a);if(r!==void 0){if(isReferentialAction(r)){t[n]=r;continue}addIssue(a,pointer(i,n),`J004`,`\`${n}\` must be one of ${renderKeys(Object.keys(K))}`)}}return t}function readVariantTargetArm(e,t,n,r,i,a){let o=readVariantMap(t.variants,pointer(i,`variants`),a);if(o===void 0)return;let s={type:t.type,variants:o};n!==void 0&&(s.name=n);let c=member(e,`values`,i,a);if(c!==void 0){let e=readStringMap(c,pointer(i,`values`),a,"`values`");e!==void 0&&(s.values=e)}if(r===`one`){let t=member(e,`optional`,i,a);if(t!==void 0){let e=asBoolean(t,pointer(i,`optional`),a,"`optional`");e!==void 0&&(s.optional=e)}return s}let l=member(e,`through`,i,a);if(l!==void 0){let e=readThroughMap(l,pointer(i,`through`),a);e!==void 0&&(s.through=e)}return s}function readVariantMap(e,t,n){let r=asRecord(e,t,n,"`variants`");if(r===void 0)return;let i={};for(let e of inspectKeys(r,t,n,`J004`)){let a=pointer(t,e);if(!refuseInvalidKey(e,a,n,`Variant key`))continue;let o=asString(member(r,e,t,n),a,n,`A variant target`);o!==void 0&&(i[e]=o)}return i}function readStringMap(e,t,n,r){let i=asRecord(e,t,n,r);if(i===void 0)return;let a={};for(let e of inspectKeys(i,t,n,`J004`)){let o=pointer(t,e);if(!refuseInvalidKey(e,o,n,`Variant key`))continue;let s=asString(member(i,e,t,n),o,n,r);s!==void 0&&(a[e]=s)}return a}function readThroughMap(e,t,n){let r=asRecord(e,t,n,"`through`");if(r===void 0)return;let i={};for(let e of inspectKeys(r,t,n,`J004`)){let a=pointer(t,e);if(!refuseInvalidKey(e,a,n,`Variant key`))continue;let o=readVariantJunctionNode(member(r,e,t,n),a,n);o!==void 0&&(i[e]=o)}return i}function readVariantJunctionNode(e,t,n){let r=asRecord(e,t,n,`A member junction`);if(r===void 0)return;refuseUnknownKeys(r,ve,t,n);let i=asString(member(r,`table`,t,n),pointer(t,`table`),n,"`table`"),a=asString(member(r,`source`,t,n),pointer(t,`source`),n,"`source`"),o=asString(member(r,`target`,t,n),pointer(t,`target`),n,"`target`");if(!(i===void 0||a===void 0||o===void 0))return{table:i,source:a,target:o}}function readJunctionNode(e,t,n){let r=asRecord(e,t,n,"`junction`");if(r===void 0)return;if(refuseUnknownKeys(r,X,t,n),inspectKeys(r,t,n,`J004`).length===0){addIssue(n,t,`J004`,"`junction` declares at least one of 'table', 'source', 'target', 'onDelete', 'onUpdate', 'onDeleteSides', 'onUpdateSides'; omit it to keep the derived defaults");return}let i={};for(let e of[`table`,`source`,`target`]){let a=member(r,e,t,n);if(a===void 0)continue;let o=asString(a,pointer(t,e),n,`\`${e}\``);o!==void 0&&(i[e]=o)}let a=readJunctionActionSpelling(r,`onDelete`,t,n),o=readJunctionActionSpelling(r,`onUpdate`,t,n);return{...i,...typeof a==`string`?{onDelete:a}:a&&{onDeleteSides:a},...typeof o==`string`?{onUpdate:o}:o&&{onUpdateSides:o}}}function readJunctionActionSpelling(e,t,n,r){let i=member(e,t,n,r),a=`${t}Sides`,o=member(e,a,n,r);if(i!==void 0&&o!==void 0){addIssue(r,pointer(n,a),`J004`,`\`${t}\` and \`${a}\` are exclusive: one action for both foreign keys, or one per side`);return}if(o!==void 0)return readJunctionSides(o,pointer(n,a),r,a);if(i!==void 0)return readJunctionAction(i,pointer(n,t),r,t)}function readJunctionSides(e,t,n,r){let i=asRecord(e,t,n,`\`${r}\``);if(i===void 0)return;refuseUnknownKeys(i,_e,t,n);let readSide=e=>{let a=member(i,e,t,n);if(a!==void 0)return readJunctionAction(a,pointer(t,e),n,`${r}.${e}`);addIssue(n,pointer(t,e),`J004`,`\`${r}\` states both 'source' and 'target'; '${e}' is missing`)},a=readSide(`source`),o=readSide(`target`);if(!(a===void 0||o===void 0))return{source:a,target:o}}function readJunctionAction(e,t,n,r){if(isJunctionAction(e))return e;addIssue(n,t,`J004`,`A junction \`${r}\` must be one of ${renderKeys(Object.keys(q))}; 'setNull' cannot null a membership-key member`)}function resolveReferences(e,t){let n=pointer(``,`models`);for(let[r,i]of Object.entries(e.models)){let a=pointer(n,r),o=pointer(a,`fields`);for(let[n,r]of Object.entries(i.fields))resolveTargetReferences(e,r,pointer(o,n),t);resolveOmitReferences(i,a,t)}}function resolveTargetReferences(e,t,n,r){if(isRelationField(t)){t.target!==void 0&&refuseUnknownModel(e,t.target,pointer(n,`target`),r);for(let[i,a]of Object.entries(t.variants??{}))refuseUnknownModel(e,a,pointer(n,`variants`,i),r)}}function refuseUnknownModel(e,t,n,r){Object.hasOwn(e.models,t)||addIssue(r,n,`J006`,`Model '${t}' is not declared in \`models\``)}function resolveOmitReferences(e,t,n){for(let[r,i]of(e.omit??[]).entries()){let a=e.fields[i];a!==void 0&&!isRelationField(a)||addIssue(n,pointer(t,`omit`,String(r)),`J006`,`\`omit\` names '${i}', which is not a scalar field of this model`)}}const Q=[`validate`],be=Q.map(e=>`'${e}'`).join(`, `),$=pointer(``,`options`);function readValidateOption(e){if(e===void 0)return!1;let t=[];if(!inspectPlainRecord(e,$,t,`J004`))throw addIssue(t,$,`J004`,"`options` must be a plain object"),refuseDocument(t);for(let n of inspectKeys(e,$,t,`J004`))Q.includes(n)||addIssue(t,pointer($,n),`J003`,`Unknown option '${n}'; this call declares ${be}`);let n=member(e,`validate`,$,t);return n!==void 0&&typeof n!=`boolean`&&addIssue(t,pointer($,`validate`),`J004`,"`validate` must be a boolean"),throwIfRefused(t),n===!0}function validateGraph(e){x(e),S(e)}function serializeSchema(e,t){readValidateOption(t)&&validateGraph(e);let n=[],r={refs:new Map,definitions:m()},i=m(),a=pointer(``,`models`);for(let[t,o]of Object.entries(e))p(i,t,serializeModel(o,e,r,pointer(a,t),n));throwIfRefused(n);let o={version:1,models:i};return Object.keys(r.definitions).length>0&&(o.enums=r.definitions),o}function serializeModel(e,t,n,r,i){let a=e[`~`].state,o=a.relations,s=a.scalars,c=m(),l=pointer(r,`fields`);for(let e of Object.keys(a.shape)){let r=g(o,e),a=g(s,e),u=pointer(l,e);if(r!==void 0){p(c,e,serializeRelation(r,t,u,i));continue}a!==void 0&&p(c,e,serializeScalar(a,n,u,i))}let u={fields:c};a.tableName!==void 0&&(u.table=a.tableName);let d=serializeIndexes(a.indexes,r,i);d.length>0&&(u.indexes=d);let f=serializeCompound(a.compoundId);f.length>0&&(u.ids=f);let h=serializeCompound(a.compoundUniques);return h.length>0&&(u.uniques=h),a.omit!==void 0&&(u.omit=Object.keys(a.omit).sort()),u}function serializeIndexes(e,t,n){let r=[];for(let[i,a]of e.entries()){let e=pointer(t,`indexes`,String(i));if(a.options.where!==void 0){addIssue(n,e,`J009`,"This index carries a `where` predicate — raw SQL the v1 document refuses to carry. Drop the partial index or keep this schema in code");continue}let o={fields:[...a.fields]};a.options.name!==void 0&&(o.name=a.options.name),a.options.unique!==void 0&&(o.unique=a.options.unique),a.options.type!==void 0&&(o.type=a.options.type),r.push(o)}return r}function serializeCompound(e){let t=[];for(let[n,r]of Object.entries(e??{})){let e=Object.keys(r.entries),i={fields:e};n!==e.join(`_`)&&(i.name=n),t.push(i)}return t}function serializeScalar(e,t,n,r){let i=e[`~`].state,a=i.type===`enum`?{type:`enum`,enum:serializeEnum(e,i,t,n,r)}:i.type===`decimal`?{type:`decimal`,precision:i.decimal.precision,scale:i.decimal.scale}:{type:i.type},o=e[`~`].nativeType;o!==void 0&&(a.type===`point`?refusePointState(n,`native`,r):a.type===`decimal`?addIssue(r,pointer(n,`native`),`J009`,`A fixed decimal cannot carry a native-type override`):C(o)?v(o.db,o.type)?a.native={db:o.db,type:o.type}:addIssue(r,pointer(n,`native`,`type`),`J011`,_(o.db)):a.nativeByDialect=nativeTypeMapDocument(o)),i.array&&(a.type===`point`?refusePointState(n,`array`,r):a.array=!0),i.nullable&&(a.nullable=!0),i.isId&&(a.type===`point`?refusePointState(n,`id`,r):a.id=!0),i.isUnique&&!i.isId&&(a.type===`point`?refusePointState(n,`unique`,r):a.unique=!0),i.withTimezone===!1&&builderMethod(e,`withoutTimezone`)!==void 0&&(a.withoutTimezone=!0),i.dimension!==void 0&&(a.type===`point`?refusePointState(n,`dimension`,r):a.dimension=i.dimension),i.columnName!==void 0&&(a.column=i.columnName),i.autoGenerate!==void 0&&(a.type===`point`?refusePointState(n,`generate`,r):writeGenerate(a,i.autoGenerate,i.isId||y(i.default))),i.schema!==void 0&&addIssue(r,n,`J009`,"This field carries a custom `.schema()` validator — arbitrary code the document cannot hold. Re-attach it with `attachFieldSchemas`");let s=serializeDefault(i,n,r);return s!==void 0&&(a.default=s),a}function nativeTypeMapDocument(e){let t={};return e.pg!==void 0&&(t.pg={db:`pg`,type:e.pg.type}),e.mysql!==void 0&&(t.mysql={db:`mysql`,type:e.mysql.type}),e.sqlite!==void 0&&(t.sqlite={db:`sqlite`,type:e.sqlite.type}),t}function refusePointState(e,t,n){addIssue(n,pointer(e,t),`J009`,`A GeoPoint cannot carry a '${t}' declaration`)}function serializeEnum(e,t,n,r,i){let a=readEnumValues(e),o=t.enumName;if(o===void 0)return a;let s=n.refs.get(o);if(s!==void 0)return sameValues(g(n.definitions,s)?.values,a)||addIssue(i,r,`J009`,`Enum type '${o}' is declared with two different value sets; one database enum type holds one set`),s;let c=claimRef(o,n);return n.refs.set(o,c),p(n.definitions,c,{values:a,name:o}),c}function claimRef(e,t){let taken=e=>g(t.definitions,e)!==void 0;if(d(e)&&!taken(e))return e;let n=t.refs.size+1;for(;taken(`enum_${n}`);)n+=1;return`enum_${n}`}function sameValues(e,t){return e!==void 0&&e.length===t.length&&e.every((e,n)=>e===t[n])}function readEnumValues(e){return[...Reflect.get(e,`enumValues`)]}function serializeDefault(e,t,r){if(!e.hasDefault)return;let i=e.default;if(i!==void 0)return i===null?e.nullable?void 0:null:n(i)?serializeFunctionDefault(e,t,r):encodeDefault(i,pointer(t,`default`),r)}function serializeFunctionDefault(e,t,n){e.autoGenerate!==void 0&&y(e.default)||addIssue(n,pointer(t,`default`),`J009`,"This field carries a function default, which the document cannot hold. Use one of the nine `generate` kinds, a literal default, or a database default through `native`")}function serializeRelation(e,t,n,r){let i=e[`~`].state,a=i.cardinality===`one`?`toOne`:`toMany`,o=M(i)?withVariantTargetFacts(a,i,t,n,r):withModelTargetFacts({type:a,target:resolveTargetKey(i.target.getter,t,n,r)},i);return i.name!==void 0&&(o.name=i.name),o}function withModelTargetFacts(e,t){let n=t.foreignKey;n!==void 0&&(e.fields=[...n.fields],e.references=[...n.references],n.onDelete!==void 0&&(e.onDelete=n.onDelete),n.onUpdate!==void 0&&(e.onUpdate=n.onUpdate));let r=t.junction;if(r!==void 0){let t={};r.table!==void 0&&(t.table=r.table),r.source!==void 0&&(t.source=r.source),r.target!==void 0&&(t.target=r.target);let n=canonicalJunctionActions(r.onDelete),i=canonicalJunctionActions(r.onUpdate);e.junction={...t,...typeof n==`string`?{onDelete:n}:n&&{onDeleteSides:n},...typeof i==`string`?{onUpdate:i}:i&&{onUpdateSides:i}}}return e}function canonicalJunctionActions(e){if(e!==void 0)return e.source===e.target?e.source:{...e}}function withVariantTargetFacts(e,t,n,r,i){let a={},o={},s={},c=!1;for(let[e,l]of Object.entries(t.target.entries)){let t=l;a[e]=resolveTargetKey(t.getter,n,pointer(r,`variants`,e),i),o[e]=t.storedValue,t.storedValue!==e&&(c=!0);let u=readVariantJunction(t);u!==void 0&&(s[e]=u)}let l={type:e,variants:a};return c&&(l.values=o),Object.keys(s).length>0&&(l.through=s),t.optional===!0&&(l.optional=!0),l}function readVariantJunction(e){let t=Reflect.get(e,`junction`);if(t!==void 0)return{table:t.table,source:t.source,target:t.target}}function resolveTargetKey(e,t,n,r){let i=readTarget(e,n);for(let[e,n]of Object.entries(t))if(n===i)return e;return addIssue(r,n,`J006`,`This relation targets a model that is not a member of the schema record being serialized`),``}function readTarget(e,t){try{return e()}catch(e){let n=[];throw addIssue(n,t,`J006`,`This relation's target getter threw; the schema cannot be serialized`),refuseDocument(n,i(e))}}function writeGenerate(e,t,n){let r=t.implicit===!0,i=t.generate??n;if(r&&t.prefix===void 0&&i)return;let a={kind:t.kind};[`uuid`,`uuidv7`,`ulid`,`ksuid`,`nanoid`,`cuid`].includes(t.kind)&&!i&&(a.generate=!1),t.prefix!==void 0&&(a.prefix=t.prefix),t.length!==void 0&&(a.length=t.length),r&&(a.implicit=!0),e.generate=a}function parseSchema(e,t){let n=readValidateOption(t),r=interpret(readDocument(e));return n&&validateGraph(r),r}function attachFieldSchemas(e,t){return interpret(readDocument(serializeSchema(e)),t)}export{U as SCHEMA_DOCUMENT_VERSION,attachFieldSchemas,parseSchema,serializeSchema};
|
|
1
|
+
import{n as e}from"../chunk-BuuaeEvq.mjs";import{c as t,i as n,r}from"../value-guards-CK9guf2Z.mjs";import{k as i}from"../base-wlv81COV.mjs";import{t as a}from"../validation-pfpKPPZ_.mjs";import{A as o,D as s,E as c,_ as l,h as u}from"../v-CWY9ntMb.mjs";import{Pt as d}from"../geo-point-codec-Ggv29hSH.mjs";import{a as f,d as p,l as m,o as h,u as g}from"../model-u8Ug971J.mjs";import{i as _,r as v,s as y,t as b}from"../scalar-DNshDNz3.mjs";import{t as x}from"../hydration-Dd2H4EyY.mjs";import{a as S}from"../validator-CYKdGTvX.mjs";import{a as C,n as w}from"../native-types-CQH05hcr.mjs";import{_ as T,a as E,c as D,d as O,f as ee,g as te,h as ne,i as re,l as ie,m as ae,n as oe,o as se,p as ce,r as k,s as A,t as j}from"../to-many-5gt2AWLE.mjs";import{t as M}from"../types-C4v6iAmY.mjs";const N=/~/g,P=/\//g;function pointer(e,...t){let n=e;for(let e of t)n+=`/${e.replace(N,`~0`).replace(P,`~1`)}`;return n}function addIssue(e,t,n,r){e.push({path:t,message:`[${n}] ${r}`})}function refuseDocument(e,t){return new a({kind:`schema-builder`,builder:`schema-json`,path:``},e,t===void 0?void 0:{cause:t})}function throwIfRefused(e){if(e.length>0)throw refuseDocument(e)}function member(e,t,n,r){return guardedValue(e,t,n,r,`J004`)}function guardedValue(e,t,n,r,a){try{return Reflect.get(e,t)}catch(e){throw addIssue(r,pointer(n,t),a,`Reading this value threw`),refuseDocument(r,i(e))}}function inspectPlainRecord(e,t,n,r){try{return l(e)}catch(e){throw addIssue(n,t,r,`Inspecting this value's prototype threw`),refuseDocument(n,i(e))}}function inspectKeys(e,t,n,r){try{return u(e)}catch(e){throw addIssue(n,t,r,`Enumerating this value's keys threw`),refuseDocument(n,i(e))}}function renderValue(e){return typeof e==`bigint`?`${e}n`:typeof e==`object`?`[${typeof e}]`:String(e)}function refuseFromBuilder(e,t){let n=[];throw addIssue(n,e,`J010`,t.message),refuseDocument(n,t)}const F=`$bigint`,I=`$date`,L=`$bytes`,R=`$raw`,z=`$jsonNull`,B=new Set([F,I,L,R,z]),V=/^-?\d+$/,H=`'${F}' (a decimal integer string), '${I}' (an ISO timestamp), '${L}' (base64), '${R}' (the literal it wraps), '${z}' ('JsonNull' or 'DbNull')`;function reservedKey(e){let t=e.length===1?e[0]:void 0;return t?.startsWith(`$`)===!0?t:void 0}function readDefaultValue(e,t,n){return readValue(e,t,n,new Set)}function readValue(e,t,r,i){if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`){if(Number.isFinite(e))return e;addIssue(r,t,`J004`,`A default must be a finite number`);return}if(Array.isArray(e))return readArray(e,t,r,i);if(inspectPlainRecord(e,t,r,`J004`))return readRecord(e,t,r,i);addIssue(r,t,`J004`,n(e)?"A function default has no document spelling — use `generate`, a literal, or a database default through `native`":`A default must be a JSON value; a value outside JSON takes a tag — ${H}`)}function readArray(e,t,n,r){if(enterCycle(e,t,n,r,`J004`))return;let i=[];for(let a=0;a<e.length;a+=1){let o=pointer(t,String(a)),s=readValue(member(e,String(a),t,n),o,n,r);if(s===void 0)return;i.push(s)}return r.delete(e),i}function readRecord(e,t,n,r){if(enterCycle(e,t,n,r,`J004`))return;let i=inspectKeys(e,t,n,`J004`),a=reservedKey(i);if(a!==void 0&&!B.has(a)){addIssue(n,t,`J008`,`'${a}' is not a tag this format defines. The tags are ${H}`);return}let o=m();for(let a of i){let i=readValue(member(e,a,t,n),pointer(t,a),n,r);if(i===void 0)return;p(o,a,i)}return r.delete(e),o}function enterCycle(e,t,n,r,i){return r.has(e)?(addIssue(n,t,i,`This default contains a cycle; a document holds a finite value`),!0):(r.add(e),!1)}function decodeDefault(e,t){if(Array.isArray(e))return e.map((e,n)=>decodeDefault(e,pointer(t,String(n))));if(typeof e!=`object`||!e)return e;let n=reservedKey(Object.keys(e));if(n===void 0)return decodeBody(e,t);let r=e[n];if(n===R)return decodeRaw(r,t);if(n===F)return decodeBigInt(r,t);if(n===I)return decodeDate(r,t);if(n===z){if(r===`JsonNull`)return s;if(r===`DbNull`)return c;throw refuseTag(t,`'${z}' takes 'JsonNull' or 'DbNull'`)}return decodeBytes(r,t)}function decodeBody(e,t){let n=m();for(let r of Object.keys(e))p(n,r,decodeDefault(e[r]??null,pointer(t,r)));return n}function decodeRaw(e,t){return typeof e!=`object`||!e?e:Array.isArray(e)?decodeDefault(e,t):decodeBody(e,t)}function decodeBigInt(e,t){if(typeof e==`string`&&V.test(e))return BigInt(e);throw refuseTag(t,`'${F}' takes a decimal integer string`)}function decodeDate(e,t){if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}throw refuseTag(t,`'${I}' takes a string naming an instant`)}function decodeBytes(e,t){if(typeof e==`string`)try{return decodeBase64(e)}catch{}throw refuseTag(t,`'${L}' takes a base64 string`)}function refuseTag(e,t){let n=[];return addIssue(n,e,`J008`,`${t}. The tags are ${H}`),refuseDocument(n)}function decodeBase64(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function encodeDefault(e,t,n){return encodeValue(e,t,n,new Set)}function encodeValue(e,n,i,a){let s=o(e);if(s===`JsonNull`||s===`DbNull`)return tagged(z,s);if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isFinite(e)?e:refuseValue(i,n,"A non-finite number has no JSON spelling; `JSON.stringify` would write it as `null`");if(typeof e==`bigint`)return tagged(F,e.toString(10));if(t(e))try{return tagged(L,encodeBase64(e))}catch{return refuseValue(i,n,`This byte string has a detached buffer and cannot be serialized`)}return r(e)?Number.isNaN(Date.prototype.getTime.call(e))?refuseValue(i,n,`An invalid Date names no instant`):tagged(I,Date.prototype.toISOString.call(e)):Array.isArray(e)?encodeArray(e,n,i,a):inspectPlainRecord(e,n,i,`J009`)?encodeRecord(e,n,i,a):refuseValue(i,n,`This default holds a value the document cannot state — a JSON value, a bigint, a Date or a byte string is what a default may be`)}function tagged(e,t){let n=m();return p(n,e,t),n}function encodeArray(e,t,n,r){if(enterCycle(e,t,n,r,`J009`))return;let i=[];for(let a=0;a<e.length;a+=1){let o=String(a),s=encodeValue(guardedValue(e,o,t,n,`J009`),pointer(t,o),n,r);if(s===void 0)return;i.push(s)}return r.delete(e),i}function encodeRecord(e,t,n,r){if(enterCycle(e,t,n,r,`J009`))return;let i=m();for(let a of inspectKeys(e,t,n,`J009`)){let o=encodeValue(guardedValue(e,a,t,n,`J009`),pointer(t,a),n,r);if(o===void 0)return;p(i,a,o)}if(r.delete(e),reservedKey(Object.keys(i))===void 0)return i;let a=m();return p(a,R,i),a}function refuseValue(e,t,n){addIssue(e,t,`J009`,n)}function encodeBase64(e){let t=``,n=Uint8Array.prototype.values.call(e);for(let e of n)t+=String.fromCharCode(e);return btoa(t)}const U=1;function isRelationField(e){return e.type===`toOne`||e.type===`toMany`}const W={string:b,int:se,number:re,boolean:ne,datetime:ce,date:ae,time:ee,bigint:T,json:E,blob:te,vector:oe,point:k},G=new Set([...Object.keys(W),`decimal`,`enum`]);function builderMethod(e,t){let n=Reflect.get(e,t);return typeof n==`function`?n:void 0}function interpret(e,t){let n={},r=pointer(``,`models`);refuseUnknownFieldSchemas(e,t);for(let[i,a]of Object.entries(e.models))n[i]=buildModel(i,a,e,n,pointer(r,i),t);return n}function refuseUnknownFieldSchemas(e,t){if(t===void 0)return;let n=[];for(let r of Object.keys(t)){let t=r.indexOf(`.`),i=e.models[r.slice(0,t)]?.fields[r.slice(t+1)];i!==void 0&&!isRelationField(i)||addIssue(n,``,`J006`,`Field schema '${r}' does not name a scalar field of this schema; spell it '<model>.<field>'`)}if(n.length>0)throw refuseDocument(n)}function buildModel(e,t,n,r,i,a){let o=pointer(i,`fields`),s={};for(let[i,c]of Object.entries(t.fields)){let t=pointer(o,i);if(isRelationField(c)){s[i]=buildRelation(c,r,t);continue}s[i]=buildScalar(c,n,t,a?.[`${e}.${i}`])}let c=call(i,()=>f(s));if(t.table!==void 0){let e=t.table;c=call(pointer(i,`table`),()=>c.map(e))}for(let[e,n]of(t.indexes??[]).entries()){let t=pointer(i,`indexes`,String(e)),r={...n.name===void 0?{}:{name:n.name},...n.unique===void 0?{}:{unique:n.unique},...n.type===void 0?{}:{type:n.type}};c=call(t,()=>Reflect.apply(c.index,c,[n.fields,r]))}for(let[e,n]of(t.ids??[]).entries())c=call(pointer(i,`ids`,String(e)),()=>c.id(n.fields,options(n.name)));for(let[e,n]of(t.uniques??[]).entries())c=call(pointer(i,`uniques`,String(e)),()=>c.unique(n.fields,options(n.name)));if(t.omit!==void 0){let e={};for(let n of t.omit)e[n]=!0;c=call(pointer(i,`omit`),()=>c.omit(e))}return c}function options(e){return e===void 0?{}:{name:e}}function buildScalar(e,t,n,r){let i=e.type,a=createScalar(e,t,n);if(e.array&&(a=modify(a,`array`,[],i,pointer(n,`array`))),e.nullable&&(a=modify(a,`nullable`,[],i,pointer(n,`nullable`))),e.id){let t=e.generate?.implicit===!0,r=e.generate?.generate===!1?[{generate:!1,prefix:t?e.generate.prefix:void 0}]:t&&e.generate?.prefix!==void 0?[e.generate.prefix]:[];a=modify(a,`id`,r,i,pointer(n,`id`))}e.unique&&(a=modify(a,`unique`,[],i,pointer(n,`unique`))),e.withoutTimezone&&(a=modify(a,`withoutTimezone`,[],i,pointer(n,`withoutTimezone`))),e.dimension!==void 0&&(a=modify(a,`dimension`,[e.dimension],i,pointer(n,`dimension`))),e.generate!==void 0&&e.generate.implicit!==!0&&(a=applyGenerate(a,e.generate,i,n));let o=e.default;return o!==void 0&&(a=applyDefault(a,e,o,n)),e.column!==void 0&&(a=modify(a,`map`,[e.column],i,pointer(n,`column`))),r!==void 0&&(a=modify(a,`schema`,[r],i,pointer(n,`schema`))),a}function createScalar(e,t,n){if(e.type===`decimal`){let{precision:t,scale:r}=e;return call(n,()=>ie({precision:t,scale:r}))}let r=e.native??e.nativeByDialect;if(e.type!==`enum`){let t=W[e.type];return call(n,()=>r===void 0?t():t(r))}let i=resolveEnum(e,t,n),a=call(n,()=>A(i.values,r));if(i.name===void 0)return a;let o=i.name;return modify(a,`name`,[o],`enum`,pointer(n,`enum`))}function resolveEnum(e,t,n){let r=e.enum;if(Array.isArray(r))return{values:r};let i=t.enums?.[r];if(i!==void 0)return i;let a=[];throw addIssue(a,pointer(n,`enum`),`J006`,`\`enum\` names '${r}', which \`enums\` does not declare`),refuseDocument(a)}function modify(e,t,n,r,i){let a=builderMethod(e,t);if(a===void 0){let e=[];throw addIssue(e,i,`J007`,`A '${r}' field has no '${t}' modifier`),refuseDocument(e)}return call(i,()=>a.apply(e,n))}function applyGenerate(e,t,n,r){let i=pointer(r,`generate`),a=![`now`,`updatedAt`,`increment`].includes(t.kind),o=t.generate===!1?{prefix:t.prefix,length:t.length}:{prefix:t.prefix,length:t.length,generate:!0},s=a?[o]:[t.prefix],c=modify(e,t.kind,s,n,i),l=c[`~`].state.autoGenerate;if(l?.prefix===t.prefix&&l?.length===t.length)return c;let u=[];throw addIssue(u,i,`J007`,`The '${t.kind}' generator does not take the 'prefix' or 'length' this node declares`),refuseDocument(u)}function applyDefault(e,t,n,r){let i=pointer(r,`default`),a=decodeDefault(n,i);if(t.type===`json`&&o(a)!==void 0)return modify(e,`default`,[a],t.type,i);let s=e[`~`].state.base[`~standard`].validate(a),c=t.type===`bigint`&&[a].flat().some(e=>typeof e==`string`);if(s.issues||c){let e=s.issues?s.issues.map(e=>e.message).join(`; `):`a bigint is written {"$bigint": "<integer>"}`,n=[];throw addIssue(n,i,`J008`,`A '${t.type}' default must be a value of the field's own domain: ${e}`),refuseDocument(n)}return e instanceof D?O(e,s.value):modify(e,`default`,[a],t.type,i)}function buildRelation(e,t,n){let r=e.target===void 0?buildVariantRelation(e,t,n):buildModelRelation(e,t,n);if(e.name===void 0)return r;let i=e.name;return call(pointer(n,`name`),()=>r.name(i))}function buildModelRelation(e,t,n){let r=e.target,getter=()=>t[r],i=e.type===`toOne`?h:j,a=call(n,()=>Reflect.apply(i,void 0,[getter]));if(e.fields!==void 0){let t=e.fields;a=call(pointer(n,`fields`),()=>a.fields(...t))}if(e.references!==void 0){let t=e.references;a=call(pointer(n,`references`),()=>a.references(...t))}for(let t of[`onDelete`,`onUpdate`]){let r=e[t];r!==void 0&&(a=call(pointer(n,t),()=>a[t](r)))}return e.junction!==void 0&&(a=applyJunction(a,e.junction,n)),a}function buildVariantRelation(e,t,n){let r={};for(let[n,i]of Object.entries(e.variants))r[n]=()=>t[i];let i=e.type===`toOne`?h:j,a=e.values===void 0?[r]:[r,{values:e.values}],o=call(n,()=>Reflect.apply(i,void 0,a));if(e.through!==void 0){let t=e.through;o=call(pointer(n,`through`),()=>o.through(t))}return e.optional&&(o=call(pointer(n,`optional`),()=>o.optional())),o}const le=[[`table`,`through`],[`source`,`source`],[`target`,`target`],[`onDelete`,`onDelete`],[`onUpdate`,`onUpdate`],[`onDeleteSides`,`onDelete`],[`onUpdateSides`,`onUpdate`]];function applyJunction(e,t,n){let r=e,i=pointer(n,`junction`);for(let[e,n]of le){let a=t[e];a!==void 0&&(r=call(pointer(i,e),()=>r[n](a)))}return r}function call(e,t){try{return t()}catch(t){return refuseFromBuilder(e,i(t))}}const K={cascade:!0,setNull:!0,restrict:!0,noAction:!0},q={cascade:!0,restrict:!0,noAction:!0},J={btree:!0,hash:!0,gin:!0,gist:!0,fulltext:!0,spatial:!0},Y={uuid:!0,uuidv7:!0,ulid:!0,ksuid:!0,nanoid:!0,cuid:!0,increment:!0,now:!0,updatedAt:!0},isReferentialAction=e=>typeof e==`string`&&Object.hasOwn(K,e),isJunctionAction=e=>typeof e==`string`&&Object.hasOwn(q,e),isIndexType=e=>typeof e==`string`&&Object.hasOwn(J,e),isGenerateKind=e=>typeof e==`string`&&Object.hasOwn(Y,e),isNativeDialect=e=>typeof e==`string`&&w.some(t=>t===e),isScalarTypeName=e=>typeof e==`string`&&G.has(e),ue=[`version`,`enums`,`models`],de=[`values`,`name`],fe=[`table`,`fields`,`indexes`,`ids`,`uniques`,`omit`],pe=[`fields`,`name`,`unique`,`type`,`where`],me=[`fields`,`name`],he=[`db`,`type`],ge=[`kind`,`prefix`,`length`,`implicit`,`generate`],X=[`table`,`source`,`target`,`onDelete`,`onUpdate`,`onDeleteSides`,`onUpdateSides`],_e=[`source`,`target`],ve=[`table`,`source`,`target`],Z=[`type`,`native`,`nativeByDialect`,`nullable`,`array`,`id`,`unique`,`column`,`default`,`generate`,`enum`,`dimension`,`precision`,`scale`,`withoutTimezone`],ye=[...new Set([...Z,...relationKeys({cardinality:`one`,variants:!1}),...relationKeys({cardinality:`many`,variants:!1}),...relationKeys({cardinality:`one`,variants:!0}),...relationKeys({cardinality:`many`,variants:!0})])];function relationKeys(e){let t=[`type`,`name`];return e.variants?(t.push(`variants`,`values`),t.push(e.cardinality===`one`?`optional`:`through`),t):(t.push(`target`),e.cardinality===`one`?(t.push(`fields`,`references`,`onDelete`,`onUpdate`),t):(t.push(`junction`),t))}function elements(e,t,n){let r=[];for(let i=0;i<e.length;i+=1)r.push(member(e,String(i),t,n));return r}function asRecord(e,t,n,r){if(inspectPlainRecord(e,t,n,`J004`))return e;addIssue(n,t,`J004`,`${r} must be a plain JSON object`)}function asString(e,t,n,r){if(typeof e==`string`)return e;addIssue(n,t,`J004`,`${r} must be a string`)}function asBoolean(e,t,n,r){if(typeof e==`boolean`)return e;addIssue(n,t,`J004`,`${r} must be a boolean`)}function asNumber(e,t,n,r){if(typeof e==`number`&&Number.isFinite(e))return e;addIssue(n,t,`J004`,`${r} must be a finite number`)}function asStringArray(e,t,n,r){if(!Array.isArray(e)){addIssue(n,t,`J004`,`${r} must be an array of strings`);return}let i=[],a=!0;for(let[o,s]of elements(e,t,n).entries()){let e=asString(s,pointer(t,String(o)),n,r);if(e===void 0){a=!1;continue}i.push(e)}return a?i:void 0}function refuseUnknownKeys(e,t,n,r,i=`this node`){for(let a of inspectKeys(e,n,r,`J004`)){if(!t.includes(a)){addIssue(r,pointer(n,a),`J003`,`Unknown key '${a}'; ${i} declares ${renderKeys(t)}`);continue}member(e,a,n,r)===void 0&&addIssue(r,pointer(n,a),`J004`,`'${a}' is \`undefined\`; a document omits an absent key rather than setting it to \`undefined\``)}}function refuseInvalidKey(e,t,n,r){return d(e)?!0:(addIssue(n,t,`J005`,`${r} '${e}' is not a valid schema identifier`),!1)}function renderKeys(e){return e.map(e=>`'${e}'`).join(`, `)}function readDocument(e){let t=[],n=intake(e,t);throwIfRefused(t);let r=asRecord(n,``,t,`A schema document`);if(r===void 0)throw refuseDocument(t);refuseUnknownKeys(r,ue,``,t);let i=member(r,`version`,``,t);if(i!==1)throw addIssue(t,pointer(``,`version`),`J002`,`Unsupported document version ${renderValue(i)}; this parser reads version 1`),refuseDocument(t);let a={version:1,models:readModels(r,t)},o=readEnums(r,t);return o!==void 0&&(a.enums=o),resolveReferences(a,t),throwIfRefused(t),a}function intake(e,t){if(typeof e!=`string`)return e;try{return JSON.parse(e)}catch(e){addIssue(t,``,`J001`,`The document is not valid JSON: ${String(e)}`);return}}function readEnums(e,t){let n=pointer(``,`enums`),r=member(e,`enums`,``,t);if(r===void 0)return;let i=asRecord(r,n,t,"`enums`");if(i===void 0)return;let a={};for(let e of inspectKeys(i,n,t,`J004`)){let r=pointer(n,e);if(!refuseInvalidKey(e,r,t,`Enum reference`))continue;let o=readEnumNode(member(i,e,n,t),r,t);o!==void 0&&(a[e]=o)}return a}function readEnumNode(e,t,n){let r=asRecord(e,t,n,`An enum definition`);if(r===void 0)return;refuseUnknownKeys(r,de,t,n);let i=asStringArray(member(r,`values`,t,n),pointer(t,`values`),n,"`values`");if(i===void 0)return;let a={values:i},o=member(r,`name`,t,n);if(o!==void 0){let e=asString(o,pointer(t,`name`),n,"`name`");e!==void 0&&(a.name=e)}return a}function readModels(e,t){let n=pointer(``,`models`),r={},i=asRecord(member(e,`models`,``,t),n,t,"`models`");if(i===void 0)return r;for(let e of inspectKeys(i,n,t,`J004`)){let a=pointer(n,e);if(!refuseInvalidKey(e,a,t,`Model key`))continue;let o=readModelNode(member(i,e,n,t),a,t);o!==void 0&&(r[e]=o)}return r}function readModelNode(e,t,n){let r=asRecord(e,t,n,`A model`);if(r===void 0)return;refuseUnknownKeys(r,fe,t,n);let i={fields:readFields(r,t,n)},a=member(r,`table`,t,n);if(a!==void 0){let e=asString(a,pointer(t,`table`),n,"`table`");e!==void 0&&(i.table=e)}let o=readIndexes(r,t,n);o!==void 0&&(i.indexes=o);let s=readCompoundKeys(r,`ids`,t,n);s!==void 0&&(i.ids=s);let c=readCompoundKeys(r,`uniques`,t,n);c!==void 0&&(i.uniques=c);let l=readOmit(r,t,n);return l!==void 0&&(i.omit=l),i}function readFields(e,t,n){let r=pointer(t,`fields`),i={},a=asRecord(member(e,`fields`,t,n),r,n,"`fields`");if(a===void 0)return i;for(let e of inspectKeys(a,r,n,`J004`)){let t=pointer(r,e);if(!refuseInvalidKey(e,t,n,`Field key`))continue;let o=readFieldNode(member(a,e,r,n),t,n);o!==void 0&&(i[e]=o)}return i}function readIndexes(e,t,n){let r=pointer(t,`indexes`),i=member(e,`indexes`,t,n);if(i===void 0)return;if(!Array.isArray(i)){addIssue(n,r,`J004`,"`indexes` must be an array");return}let a=[];for(let[e,t]of elements(i,r,n).entries()){let i=readIndexNode(t,pointer(r,String(e)),n);i!==void 0&&a.push(i)}return a}function readIndexNode(e,t,n){let r=asRecord(e,t,n,`An index`);if(r===void 0)return;inspectKeys(r,t,n,`J004`).includes(`where`)&&addIssue(n,pointer(t,`where`),`J009`,"`where` is refused in v1: it is raw SQL interpolated unescaped into DDL, and a machine-written document must not carry an execution channel. It returns when a structured predicate form exists"),refuseUnknownKeys(r,pe,t,n);let i=asStringArray(member(r,`fields`,t,n),pointer(t,`fields`),n,"`fields`");if(i===void 0)return;let a={fields:i},o=member(r,`name`,t,n);if(o!==void 0){let e=asString(o,pointer(t,`name`),n,"`name`");e!==void 0&&(a.name=e)}let s=member(r,`unique`,t,n);if(s!==void 0){let e=asBoolean(s,pointer(t,`unique`),n,"`unique`");e!==void 0&&(a.unique=e)}let c=member(r,`type`,t,n);return c!==void 0&&(isIndexType(c)?a.type=c:addIssue(n,pointer(t,`type`),`J004`,`\`type\` must be one of ${renderKeys(Object.keys(J))}`)),a}function readCompoundKeys(e,t,n,r){let i=pointer(n,t),a=member(e,t,n,r);if(a===void 0)return;if(!Array.isArray(a)){addIssue(r,i,`J004`,`\`${t}\` must be an array`);return}let o=[];for(let[e,t]of elements(a,i,r).entries()){let n=readCompoundKeyNode(t,pointer(i,String(e)),r);n!==void 0&&o.push(n)}return o}function readCompoundKeyNode(e,t,n){let r=asRecord(e,t,n,`A compound key`);if(r===void 0)return;refuseUnknownKeys(r,me,t,n);let i=asStringArray(member(r,`fields`,t,n),pointer(t,`fields`),n,"`fields`");if(i===void 0)return;let a={fields:i},o=member(r,`name`,t,n);if(o!==void 0){let e=asString(o,pointer(t,`name`),n,"`name`");e!==void 0&&(a.name=e)}return a}function readOmit(e,t,n){let r=member(e,`omit`,t,n);if(r!==void 0)return asStringArray(r,pointer(t,`omit`),n,"`omit`")}function readFieldNode(e,t,n){let r=asRecord(e,t,n,`A field`);if(r===void 0)return;let i=member(r,`type`,t,n);if(i===`toOne`||i===`toMany`)return readRelationField(r,i,t,n);if(isScalarTypeName(i))return readScalarField(r,i,t,n);addIssue(n,pointer(t,`type`),`J004`,`\`type\` must be 'toOne', 'toMany', or one of ${renderKeys([...G])}`),refuseUnknownKeys(r,ye,t,n,`a field node`)}function readScalarField(e,t,n,r){refuseUnknownKeys(e,Z,n,r);let i=readScalarArm(e,t,n,r);if(i===void 0)return;readFlag(e,`nullable`,n,r,i),readFlag(e,`array`,n,r,i),readFlag(e,`id`,n,r,i),readFlag(e,`unique`,n,r,i),readFlag(e,`withoutTimezone`,n,r,i);let a=member(e,`column`,n,r);if(a!==void 0){let e=asString(a,pointer(n,`column`),r,"`column`");e!==void 0&&(i.column=e)}let o=member(e,`dimension`,n,r);if(o!==void 0)if(t===`point`)refusePointModifier(`dimension`,n,r);else{let e=asNumber(o,pointer(n,`dimension`),r,"`dimension`");e!==void 0&&(i.dimension=e)}t!==`decimal`&&(refuseDecimalDomainBound(e,`precision`,n,r),refuseDecimalDomainBound(e,`scale`,n,r));let s=member(e,`native`,n,r);if(s!==void 0)if(i.type===`point`)refusePointModifier(`native`,n,r);else if(i.type===`decimal`)addIssue(r,pointer(n,`native`),`J003`,"`native` does not belong to a decimal field; its physical type is derived from `precision` and `scale`");else{let e=readNativeNode(s,pointer(n,`native`),r);e!==void 0&&(i.native=e)}let c=member(e,`nativeByDialect`,n,r);if(c!==void 0)if(i.type===`point`)refusePointModifier(`nativeByDialect`,n,r);else if(i.type===`decimal`||s!==void 0)addIssue(r,pointer(n,`nativeByDialect`),`J003`,i.type===`decimal`?"`nativeByDialect` does not belong to a decimal field; its physical type is derived from `precision` and `scale`":"`native` and `nativeByDialect` are two spellings of one declaration; a field carries at most one");else{let e=readNativeByDialectNode(c,pointer(n,`nativeByDialect`),r);e!==void 0&&(i.nativeByDialect=e)}let l=member(e,`generate`,n,r);if(l!==void 0)if(t===`point`)refusePointModifier(`generate`,n,r);else{let e=readGenerateNode(l,pointer(n,`generate`),r,i.id===!0);e!==void 0&&(i.generate=e)}let u=member(e,`default`,n,r);if(u!==void 0){let e=readDefaultValue(u,pointer(n,`default`),r);e!==void 0&&(i.default=e)}return i}function readRequiredDomainBound(e,t,n,r){let i=member(e,t,n,r);if(i===void 0){addIssue(r,pointer(n,t),`J004`,`A decimal field must declare \`${t}\``);return}return asNumber(i,pointer(n,t),r,`\`${t}\``)}function refuseDecimalDomainBound(e,t,n,r){member(e,t,n,r)!==void 0&&addIssue(r,pointer(n,t),`J003`,`\`${t}\` belongs only to a field of type 'decimal'`)}function readScalarArm(e,t,n,r){let i=member(e,`enum`,n,r),a=pointer(n,`enum`);if(t!==`enum`){if(i!==void 0&&addIssue(r,a,`J003`,"`enum` belongs to a field of type 'enum'"),t===`decimal`){let i=readRequiredDomainBound(e,`precision`,n,r),a=readRequiredDomainBound(e,`scale`,n,r);return i===void 0||a===void 0?void 0:{type:t,precision:i,scale:a}}return{type:t}}if(i===void 0){addIssue(r,a,`J004`,"An enum field declares `enum` as an `enums` reference or an inline array of values");return}if(typeof i==`string`)return{type:t,enum:i};let o=asStringArray(i,a,r,"`enum`");if(o!==void 0)return{type:t,enum:o}}function readFlag(e,t,n,r,i){let a=member(e,t,n,r);if(a===void 0)return;if(i.type===`point`&&t!==`nullable`){refusePointModifier(t,n,r);return}let o=asBoolean(a,pointer(n,t),r,`\`${t}\``);if(o!==void 0){if(t===`nullable`){i.nullable=o;return}i.type!==`point`&&(i[t]=o)}}function refusePointModifier(e,t,n){addIssue(n,pointer(t,e),`J007`,`A 'point' field has no '${e}' modifier`)}function readNativeNode(e,t,n){let r=asRecord(e,t,n,"`native`");if(r===void 0)return;refuseUnknownKeys(r,he,t,n);let i=member(r,`db`,t,n),a=asString(member(r,`type`,t,n),pointer(t,`type`),n,"`native.type`");if(!isNativeDialect(i)){addIssue(n,pointer(t,`db`),`J004`,`\`native.db\` must be one of ${renderKeys(w)}`);return}if(a!==void 0){if(!v(i,a)){addIssue(n,pointer(t,`type`),`J011`,_(i));return}return{db:i,type:a}}}function readNativeByDialectNode(e,t,n){let r=asRecord(e,t,n,"`nativeByDialect`");if(r===void 0)return;refuseUnknownKeys(r,w,t,n);let i={},a=readDialectEntry(r,`pg`,t,n);a!==void 0&&(i.pg=a);let o=readDialectEntry(r,`mysql`,t,n);o!==void 0&&(i.mysql=o);let s=readDialectEntry(r,`sqlite`,t,n);return s!==void 0&&(i.sqlite=s),i}function readDialectEntry(e,t,n,r){let i=member(e,t,n,r);if(i===void 0)return;let a=pointer(n,t),o=readNativeNode(i,a,r);if(o!==void 0){if(o.db!==t){addIssue(r,pointer(a,`db`),`J004`,`The '${t}' entry's \`db\` must be '${t}'`);return}return{db:t,type:o.type}}}function readGenerateNode(e,t,n,r){let i=asRecord(e,t,n,"`generate`");if(i===void 0)return;refuseUnknownKeys(i,ge,t,n);let a=member(i,`kind`,t,n);if(!isGenerateKind(a)){addIssue(n,pointer(t,`kind`),`J004`,`\`generate.kind\` must be one of ${renderKeys(Object.keys(Y))}`);return}let o={kind:a},s=member(i,`generate`,t,n);if(s!==void 0){let e=asBoolean(s,pointer(t,`generate`),n,"`generate`");a===`now`||a===`updatedAt`||a===`increment`?addIssue(n,pointer(t,`generate`),`J004`,`An explicit generation choice belongs only to string identifier formats`):e!==void 0&&(o.generate=e)}let c=member(i,`prefix`,t,n);if(c!==void 0){let e=asString(c,pointer(t,`prefix`),n,"`prefix`");e!==void 0&&(o.prefix=e)}let l=member(i,`length`,t,n);if(l!==void 0){let e=asNumber(l,pointer(t,`length`),n,"`length`");e!==void 0&&(o.length=e)}let u=member(i,`implicit`,t,n);return u!==void 0&&asBoolean(u,pointer(t,`implicit`),n,"`implicit`")===!0&&(a===`ulid`?r?o.implicit=!0:addIssue(n,pointer(t,`implicit`),`J004`,"`generate.implicit` describes the ULID `.id()` installs, so it belongs only beside `id: true`"):addIssue(n,pointer(t,`implicit`),`J004`,'`generate.implicit` describes the ULID `.id()` installs, so it belongs only to `kind: "ulid"`')),o}function readRelationField(e,t,n,r){let i=member(e,`target`,n,r),a=member(e,`variants`,n,r);if(i===void 0==(a===void 0)){addIssue(r,n,`J004`,"A relation names exactly one target domain: `target` for one model, or `variants` for named variants");return}let o=t===`toOne`?`one`:`many`;refuseUnknownKeys(e,relationKeys({cardinality:o,variants:a!==void 0}),n,r);let s=readName(e,n,r);if(i===void 0)return readVariantTargetArm(e,{type:t,variants:a},s,o,n,r);let c=asString(i,pointer(n,`target`),r,"`target`");if(c!==void 0)return readModelTargetArm(e,{type:t,target:c},s,o,n,r)}function readName(e,t,n){let r=member(e,`name`,t,n);if(r!==void 0)return asString(r,pointer(t,`name`),n,"`name`")}function readModelTargetArm(e,t,n,r,i,a){if(n!==void 0&&(t.name=n),r===`many`){let n=member(e,`junction`,i,a);if(n!==void 0){let e=readJunctionNode(n,pointer(i,`junction`),a);e!==void 0&&(t.junction=e)}return t}for(let n of[`fields`,`references`]){let r=member(e,n,i,a);if(r===void 0)continue;let o=asStringArray(r,pointer(i,n),a,`\`${n}\``);o!==void 0&&(t[n]=o)}for(let n of[`onDelete`,`onUpdate`]){let r=member(e,n,i,a);if(r!==void 0){if(isReferentialAction(r)){t[n]=r;continue}addIssue(a,pointer(i,n),`J004`,`\`${n}\` must be one of ${renderKeys(Object.keys(K))}`)}}return t}function readVariantTargetArm(e,t,n,r,i,a){let o=readVariantMap(t.variants,pointer(i,`variants`),a);if(o===void 0)return;let s={type:t.type,variants:o};n!==void 0&&(s.name=n);let c=member(e,`values`,i,a);if(c!==void 0){let e=readStringMap(c,pointer(i,`values`),a,"`values`");e!==void 0&&(s.values=e)}if(r===`one`){let t=member(e,`optional`,i,a);if(t!==void 0){let e=asBoolean(t,pointer(i,`optional`),a,"`optional`");e!==void 0&&(s.optional=e)}return s}let l=member(e,`through`,i,a);if(l!==void 0){let e=readThroughMap(l,pointer(i,`through`),a);e!==void 0&&(s.through=e)}return s}function readVariantMap(e,t,n){let r=asRecord(e,t,n,"`variants`");if(r===void 0)return;let i={};for(let e of inspectKeys(r,t,n,`J004`)){let a=pointer(t,e);if(!refuseInvalidKey(e,a,n,`Variant key`))continue;let o=asString(member(r,e,t,n),a,n,`A variant target`);o!==void 0&&(i[e]=o)}return i}function readStringMap(e,t,n,r){let i=asRecord(e,t,n,r);if(i===void 0)return;let a={};for(let e of inspectKeys(i,t,n,`J004`)){let o=pointer(t,e);if(!refuseInvalidKey(e,o,n,`Variant key`))continue;let s=asString(member(i,e,t,n),o,n,r);s!==void 0&&(a[e]=s)}return a}function readThroughMap(e,t,n){let r=asRecord(e,t,n,"`through`");if(r===void 0)return;let i={};for(let e of inspectKeys(r,t,n,`J004`)){let a=pointer(t,e);if(!refuseInvalidKey(e,a,n,`Variant key`))continue;let o=readVariantJunctionNode(member(r,e,t,n),a,n);o!==void 0&&(i[e]=o)}return i}function readVariantJunctionNode(e,t,n){let r=asRecord(e,t,n,`A member junction`);if(r===void 0)return;refuseUnknownKeys(r,ve,t,n);let i=asString(member(r,`table`,t,n),pointer(t,`table`),n,"`table`"),a=asString(member(r,`source`,t,n),pointer(t,`source`),n,"`source`"),o=asString(member(r,`target`,t,n),pointer(t,`target`),n,"`target`");if(!(i===void 0||a===void 0||o===void 0))return{table:i,source:a,target:o}}function readJunctionNode(e,t,n){let r=asRecord(e,t,n,"`junction`");if(r===void 0)return;if(refuseUnknownKeys(r,X,t,n),inspectKeys(r,t,n,`J004`).length===0){addIssue(n,t,`J004`,"`junction` declares at least one of 'table', 'source', 'target', 'onDelete', 'onUpdate', 'onDeleteSides', 'onUpdateSides'; omit it to keep the derived defaults");return}let i={};for(let e of[`table`,`source`,`target`]){let a=member(r,e,t,n);if(a===void 0)continue;let o=asString(a,pointer(t,e),n,`\`${e}\``);o!==void 0&&(i[e]=o)}let a=readJunctionActionSpelling(r,`onDelete`,t,n),o=readJunctionActionSpelling(r,`onUpdate`,t,n);return{...i,...typeof a==`string`?{onDelete:a}:a&&{onDeleteSides:a},...typeof o==`string`?{onUpdate:o}:o&&{onUpdateSides:o}}}function readJunctionActionSpelling(e,t,n,r){let i=member(e,t,n,r),a=`${t}Sides`,o=member(e,a,n,r);if(i!==void 0&&o!==void 0){addIssue(r,pointer(n,a),`J004`,`\`${t}\` and \`${a}\` are exclusive: one action for both foreign keys, or one per side`);return}if(o!==void 0)return readJunctionSides(o,pointer(n,a),r,a);if(i!==void 0)return readJunctionAction(i,pointer(n,t),r,t)}function readJunctionSides(e,t,n,r){let i=asRecord(e,t,n,`\`${r}\``);if(i===void 0)return;refuseUnknownKeys(i,_e,t,n);let readSide=e=>{let a=member(i,e,t,n);if(a!==void 0)return readJunctionAction(a,pointer(t,e),n,`${r}.${e}`);addIssue(n,pointer(t,e),`J004`,`\`${r}\` states both 'source' and 'target'; '${e}' is missing`)},a=readSide(`source`),o=readSide(`target`);if(!(a===void 0||o===void 0))return{source:a,target:o}}function readJunctionAction(e,t,n,r){if(isJunctionAction(e))return e;addIssue(n,t,`J004`,`A junction \`${r}\` must be one of ${renderKeys(Object.keys(q))}; 'setNull' cannot null a membership-key member`)}function resolveReferences(e,t){let n=pointer(``,`models`);for(let[r,i]of Object.entries(e.models)){let a=pointer(n,r),o=pointer(a,`fields`);for(let[n,r]of Object.entries(i.fields))resolveTargetReferences(e,r,pointer(o,n),t);resolveOmitReferences(i,a,t)}}function resolveTargetReferences(e,t,n,r){if(isRelationField(t)){t.target!==void 0&&refuseUnknownModel(e,t.target,pointer(n,`target`),r);for(let[i,a]of Object.entries(t.variants??{}))refuseUnknownModel(e,a,pointer(n,`variants`,i),r)}}function refuseUnknownModel(e,t,n,r){Object.hasOwn(e.models,t)||addIssue(r,n,`J006`,`Model '${t}' is not declared in \`models\``)}function resolveOmitReferences(e,t,n){for(let[r,i]of(e.omit??[]).entries()){let a=e.fields[i];a!==void 0&&!isRelationField(a)||addIssue(n,pointer(t,`omit`,String(r)),`J006`,`\`omit\` names '${i}', which is not a scalar field of this model`)}}const Q=[`validate`],be=Q.map(e=>`'${e}'`).join(`, `),$=pointer(``,`options`);function readValidateOption(e){if(e===void 0)return!1;let t=[];if(!inspectPlainRecord(e,$,t,`J004`))throw addIssue(t,$,`J004`,"`options` must be a plain object"),refuseDocument(t);for(let n of inspectKeys(e,$,t,`J004`))Q.includes(n)||addIssue(t,pointer($,n),`J003`,`Unknown option '${n}'; this call declares ${be}`);let n=member(e,`validate`,$,t);return n!==void 0&&typeof n!=`boolean`&&addIssue(t,pointer($,`validate`),`J004`,"`validate` must be a boolean"),throwIfRefused(t),n===!0}function validateGraph(e){x(e),S(e)}function serializeSchema(e,t){readValidateOption(t)&&validateGraph(e);let n=[],r={refs:new Map,definitions:m()},i=m(),a=pointer(``,`models`);for(let[t,o]of Object.entries(e))p(i,t,serializeModel(o,e,r,pointer(a,t),n));throwIfRefused(n);let o={version:1,models:i};return Object.keys(r.definitions).length>0&&(o.enums=r.definitions),o}function serializeModel(e,t,n,r,i){let a=e[`~`].state,o=a.relations,s=a.scalars,c=m(),l=pointer(r,`fields`);for(let e of Object.keys(a.shape)){let r=g(o,e),a=g(s,e),u=pointer(l,e);if(r!==void 0){p(c,e,serializeRelation(r,t,u,i));continue}a!==void 0&&p(c,e,serializeScalar(a,n,u,i))}let u={fields:c};a.tableName!==void 0&&(u.table=a.tableName);let d=serializeIndexes(a.indexes,r,i);d.length>0&&(u.indexes=d);let f=serializeCompound(a.compoundId);f.length>0&&(u.ids=f);let h=serializeCompound(a.compoundUniques);return h.length>0&&(u.uniques=h),a.omit!==void 0&&(u.omit=Object.keys(a.omit).sort()),u}function serializeIndexes(e,t,n){let r=[];for(let[i,a]of e.entries()){let e=pointer(t,`indexes`,String(i));if(a.options.where!==void 0){addIssue(n,e,`J009`,"This index carries a `where` predicate — raw SQL the v1 document refuses to carry. Drop the partial index or keep this schema in code");continue}let o={fields:[...a.fields]};a.options.name!==void 0&&(o.name=a.options.name),a.options.unique!==void 0&&(o.unique=a.options.unique),a.options.type!==void 0&&(o.type=a.options.type),r.push(o)}return r}function serializeCompound(e){let t=[];for(let[n,r]of Object.entries(e??{})){let e=Object.keys(r.entries),i={fields:e};n!==e.join(`_`)&&(i.name=n),t.push(i)}return t}function serializeScalar(e,t,n,r){let i=e[`~`].state,a=i.type===`enum`?{type:`enum`,enum:serializeEnum(e,i,t,n,r)}:i.type===`decimal`?{type:`decimal`,precision:i.decimal.precision,scale:i.decimal.scale}:{type:i.type},o=e[`~`].nativeType;o!==void 0&&(a.type===`point`?refusePointState(n,`native`,r):a.type===`decimal`?addIssue(r,pointer(n,`native`),`J009`,`A fixed decimal cannot carry a native-type override`):C(o)?v(o.db,o.type)?a.native={db:o.db,type:o.type}:addIssue(r,pointer(n,`native`,`type`),`J011`,_(o.db)):a.nativeByDialect=nativeTypeMapDocument(o)),i.array&&(a.type===`point`?refusePointState(n,`array`,r):a.array=!0),i.nullable&&(a.nullable=!0),i.isId&&(a.type===`point`?refusePointState(n,`id`,r):a.id=!0),i.isUnique&&!i.isId&&(a.type===`point`?refusePointState(n,`unique`,r):a.unique=!0),i.withTimezone===!1&&builderMethod(e,`withoutTimezone`)!==void 0&&(a.withoutTimezone=!0),i.dimension!==void 0&&(a.type===`point`?refusePointState(n,`dimension`,r):a.dimension=i.dimension),i.columnName!==void 0&&(a.column=i.columnName),i.autoGenerate!==void 0&&(a.type===`point`?refusePointState(n,`generate`,r):writeGenerate(a,i.autoGenerate,i.isId||y(i.default))),i.schema!==void 0&&addIssue(r,n,`J009`,"This field carries a custom `.schema()` validator — arbitrary code the document cannot hold. Re-attach it with `attachFieldSchemas`");let s=serializeDefault(i,n,r);return s!==void 0&&(a.default=s),a}function nativeTypeMapDocument(e){let t={};return e.pg!==void 0&&(t.pg={db:`pg`,type:e.pg.type}),e.mysql!==void 0&&(t.mysql={db:`mysql`,type:e.mysql.type}),e.sqlite!==void 0&&(t.sqlite={db:`sqlite`,type:e.sqlite.type}),t}function refusePointState(e,t,n){addIssue(n,pointer(e,t),`J009`,`A GeoPoint cannot carry a '${t}' declaration`)}function serializeEnum(e,t,n,r,i){let a=readEnumValues(e),o=t.enumName;if(o===void 0)return a;let s=n.refs.get(o);if(s!==void 0)return sameValues(g(n.definitions,s)?.values,a)||addIssue(i,r,`J009`,`Enum type '${o}' is declared with two different value sets; one database enum type holds one set`),s;let c=claimRef(o,n);return n.refs.set(o,c),p(n.definitions,c,{values:a,name:o}),c}function claimRef(e,t){let taken=e=>g(t.definitions,e)!==void 0;if(d(e)&&!taken(e))return e;let n=t.refs.size+1;for(;taken(`enum_${n}`);)n+=1;return`enum_${n}`}function sameValues(e,t){return e!==void 0&&e.length===t.length&&e.every((e,n)=>e===t[n])}function readEnumValues(e){return[...Reflect.get(e,`enumValues`)]}function serializeDefault(e,t,r){if(!e.hasDefault)return;let i=e.default;if(i!==void 0)return i===null?e.nullable?void 0:null:n(i)?serializeFunctionDefault(e,t,r):encodeDefault(i,pointer(t,`default`),r)}function serializeFunctionDefault(e,t,n){e.autoGenerate!==void 0&&y(e.default)||addIssue(n,pointer(t,`default`),`J009`,"This field carries a function default, which the document cannot hold. Use one of the nine `generate` kinds, a literal default, or a database default through `native`")}function serializeRelation(e,t,n,r){let i=e[`~`].state,a=i.cardinality===`one`?`toOne`:`toMany`,o=M(i)?withVariantTargetFacts(a,i,t,n,r):withModelTargetFacts({type:a,target:resolveTargetKey(i.target.getter,t,n,r)},i);return i.name!==void 0&&(o.name=i.name),o}function withModelTargetFacts(e,t){let n=t.foreignKey;n!==void 0&&(e.fields=[...n.fields],e.references=[...n.references],n.onDelete!==void 0&&(e.onDelete=n.onDelete),n.onUpdate!==void 0&&(e.onUpdate=n.onUpdate));let r=t.junction;if(r!==void 0){let t={};r.table!==void 0&&(t.table=r.table),r.source!==void 0&&(t.source=r.source),r.target!==void 0&&(t.target=r.target);let n=canonicalJunctionActions(r.onDelete),i=canonicalJunctionActions(r.onUpdate);e.junction={...t,...typeof n==`string`?{onDelete:n}:n&&{onDeleteSides:n},...typeof i==`string`?{onUpdate:i}:i&&{onUpdateSides:i}}}return e}function canonicalJunctionActions(e){if(e!==void 0)return e.source===e.target?e.source:{...e}}function withVariantTargetFacts(e,t,n,r,i){let a={},o={},s={},c=!1;for(let[e,l]of Object.entries(t.target.entries)){let t=l;a[e]=resolveTargetKey(t.getter,n,pointer(r,`variants`,e),i),o[e]=t.storedValue,t.storedValue!==e&&(c=!0);let u=readVariantJunction(t);u!==void 0&&(s[e]=u)}let l={type:e,variants:a};return c&&(l.values=o),Object.keys(s).length>0&&(l.through=s),t.optional===!0&&(l.optional=!0),l}function readVariantJunction(e){let t=Reflect.get(e,`junction`);if(t!==void 0)return{table:t.table,source:t.source,target:t.target}}function resolveTargetKey(e,t,n,r){let i=readTarget(e,n);for(let[e,n]of Object.entries(t))if(n===i)return e;return addIssue(r,n,`J006`,`This relation targets a model that is not a member of the schema record being serialized`),``}function readTarget(e,t){try{return e()}catch(e){let n=[];throw addIssue(n,t,`J006`,`This relation's target getter threw; the schema cannot be serialized`),refuseDocument(n,i(e))}}function writeGenerate(e,t,n){let r=t.implicit===!0,i=t.generate??n;if(r&&t.prefix===void 0&&i)return;let a={kind:t.kind};[`uuid`,`uuidv7`,`ulid`,`ksuid`,`nanoid`,`cuid`].includes(t.kind)&&!i&&(a.generate=!1),t.prefix!==void 0&&(a.prefix=t.prefix),t.length!==void 0&&(a.length=t.length),r&&(a.implicit=!0),e.generate=a}function parseSchema(e,t){let n=readValidateOption(t),r=interpret(readDocument(e));return n&&validateGraph(r),r}function attachFieldSchemas(e,t){return interpret(readDocument(serializeSchema(e)),t)}export{U as SCHEMA_DOCUMENT_VERSION,attachFieldSchemas,parseSchema,serializeSchema};
|
|
2
2
|
//# sourceMappingURL=json.mjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as e,o as t}from"./model-u8Ug971J.mjs";import{t as n}from"./scalar-DNshDNz3.mjs";import{_ as r,a as i,f as a,g as o,h as s,i as c,m as l,n as u,o as d,p as f,r as p,s as m,t as h,u as g}from"./to-many-5gt2AWLE.mjs";const _={model:e,string:n,boolean:s,int:d,number:c,decimal:g,bigInt:r,dateTime:f,date:l,time:a,json:i,blob:o,enum:m,point:p,vector:u,toOne:t,toMany:h};export{_ as t};
|
|
2
|
+
//# sourceMappingURL=schema-DYPfTOQl.mjs.map
|