@prisma-next/contract 0.3.0-dev.139 → 0.3.0-dev.140
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/hashing-CVS9sXxd.mjs +215 -0
- package/dist/hashing-CVS9sXxd.mjs.map +1 -0
- package/dist/hashing.d.mts +38 -0
- package/dist/hashing.d.mts.map +1 -0
- package/dist/hashing.mjs +3 -0
- package/dist/testing.d.mts +28 -0
- package/dist/testing.d.mts.map +1 -0
- package/dist/testing.mjs +56 -0
- package/dist/testing.mjs.map +1 -0
- package/dist/{contract-types-C0y-Bn8M.d.mts → types-D-iOS0Ks.d.mts} +52 -53
- package/dist/types-D-iOS0Ks.d.mts.map +1 -0
- package/dist/types-DokLaU9G.mjs +30 -0
- package/dist/types-DokLaU9G.mjs.map +1 -0
- package/dist/types.d.mts +1 -1
- package/dist/types.mjs +2 -29
- package/dist/validate-contract.d.mts +1 -1
- package/dist/validate-contract.mjs +1 -1
- package/dist/{validate-domain-WfuBWGsF.mjs → validate-domain-CTQiBiei.mjs} +1 -1
- package/dist/{validate-domain-WfuBWGsF.mjs.map → validate-domain-CTQiBiei.mjs.map} +1 -1
- package/dist/validate-domain.mjs +1 -1
- package/package.json +8 -7
- package/schemas/data-contract-document-v1.json +0 -5
- package/src/canonicalization.ts +286 -0
- package/src/contract-types.ts +1 -1
- package/src/exports/hashing.ts +6 -0
- package/src/exports/testing.ts +1 -0
- package/src/hashing.ts +69 -0
- package/src/testing-factories.ts +93 -0
- package/src/types.ts +7 -7
- package/dist/contract-types-C0y-Bn8M.d.mts.map +0 -1
- package/dist/ir-BPkihpFL.d.mts +0 -86
- package/dist/ir-BPkihpFL.d.mts.map +0 -1
- package/dist/ir.d.mts +0 -2
- package/dist/ir.mjs +0 -52
- package/dist/ir.mjs.map +0 -1
- package/dist/types.mjs.map +0 -1
- package/src/exports/ir.ts +0 -1
- package/src/ir.ts +0 -131
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-DokLaU9G.mjs","names":[],"sources":["../src/types.ts"],"sourcesContent":["import type { OperationRegistry } from '@prisma-next/operations';\nimport type { Contract } from './contract-types';\nimport type { DomainModel } from './domain-types';\n\n/**\n * Unique symbol used as the key for branding types.\n */\nexport const $: unique symbol = Symbol('__prisma_next_brand__');\n\n/**\n * A helper type to brand a given type with a unique identifier.\n *\n * @template TKey Text used as the brand key.\n * @template TValue Optional value associated with the brand key. Defaults to `true`.\n */\nexport type Brand<TKey extends string | number | symbol, TValue = true> = {\n [$]: {\n [K in TKey]: TValue;\n };\n};\n\n/**\n * Context passed to type renderers during contract.d.ts generation.\n */\nexport interface RenderTypeContext {\n /** The name of the CodecTypes type alias (typically 'CodecTypes') */\n readonly codecTypesName: string;\n}\n\n/**\n * Base type for storage contract hashes.\n * Emitted contract.d.ts files use this with the hash value as a type parameter:\n * `type StorageHash = StorageHashBase<'sha256:abc123...'>`\n */\nexport type StorageHashBase<THash extends string> = THash & Brand<'StorageHash'>;\n\n/**\n * Base type for execution contract hashes.\n * Emitted contract.d.ts files use this with the hash value as a type parameter:\n * `type ExecutionHash = ExecutionHashBase<'sha256:def456...'>`\n */\nexport type ExecutionHashBase<THash extends string> = THash & Brand<'ExecutionHash'>;\n\nexport function coreHash<const T extends string>(value: T): StorageHashBase<T> {\n return value as StorageHashBase<T>;\n}\n\n/**\n * Base type for profile contract hashes.\n * Emitted contract.d.ts files use this with the hash value as a type parameter:\n * `type ProfileHash = ProfileHashBase<'sha256:def456...'>`\n */\nexport type ProfileHashBase<THash extends string> = THash & Brand<'ProfileHash'>;\n\nexport function profileHash<const T extends string>(value: T): ProfileHashBase<T> {\n return value as ProfileHashBase<T>;\n}\n\n/**\n * Base type for family-specific storage blocks.\n * Family storage types (SqlStorage, MongoStorage, etc.) extend this to carry the\n * storage hash alongside family-specific data (tables, collections, etc.).\n */\nexport interface StorageBase<THash extends string = string> {\n readonly storageHash: StorageHashBase<THash>;\n}\n\nexport interface ContractBase<\n TStorageHash extends StorageHashBase<string> = StorageHashBase<string>,\n TExecutionHash extends ExecutionHashBase<string> = ExecutionHashBase<string>,\n TProfileHash extends ProfileHashBase<string> = ProfileHashBase<string>,\n> {\n readonly schemaVersion: string;\n readonly target: string;\n readonly targetFamily: string;\n readonly storageHash: TStorageHash;\n readonly executionHash?: TExecutionHash | undefined;\n readonly profileHash?: TProfileHash | undefined;\n readonly capabilities: Record<string, Record<string, boolean>>;\n readonly extensionPacks: Record<string, unknown>;\n readonly meta: Record<string, unknown>;\n readonly sources: Record<string, Source>;\n readonly execution?: ExecutionSection;\n readonly roots: Record<string, string>;\n readonly models: Record<string, DomainModel>;\n}\n\nexport interface FieldType {\n readonly type: string;\n readonly nullable: boolean;\n readonly items?: FieldType;\n readonly properties?: Record<string, FieldType>;\n}\n\nexport type GeneratedValueSpec = {\n readonly id: string;\n readonly params?: Record<string, unknown>;\n};\n\nexport type JsonPrimitive = string | number | boolean | null;\n\nexport type JsonValue =\n | JsonPrimitive\n | { readonly [key: string]: JsonValue }\n | readonly JsonValue[];\n\nexport type TaggedBigInt = { readonly $type: 'bigint'; readonly value: string };\n\nexport function isTaggedBigInt(value: unknown): value is TaggedBigInt {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { $type?: unknown }).$type === 'bigint' &&\n typeof (value as { value?: unknown }).value === 'string'\n );\n}\n\nexport function bigintJsonReplacer(_key: string, value: unknown): unknown {\n if (typeof value === 'bigint') {\n return { $type: 'bigint', value: value.toString() } satisfies TaggedBigInt;\n }\n return value;\n}\n\nexport type TaggedRaw = { readonly $type: 'raw'; readonly value: JsonValue };\n\nexport function isTaggedRaw(value: unknown): value is TaggedRaw {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { $type?: unknown }).$type === 'raw' &&\n 'value' in (value as object)\n );\n}\n\nexport type TaggedLiteralValue = TaggedBigInt | TaggedRaw;\n\nexport type ColumnDefaultLiteralValue = JsonValue | TaggedLiteralValue;\n\nexport type ColumnDefaultLiteralInputValue = ColumnDefaultLiteralValue | bigint | Date;\n\nexport type ColumnDefault =\n | {\n readonly kind: 'literal';\n readonly value: ColumnDefaultLiteralInputValue;\n }\n | { readonly kind: 'function'; readonly expression: string };\n\nexport type ExecutionMutationDefaultValue = {\n readonly kind: 'generator';\n readonly id: GeneratedValueSpec['id'];\n readonly params?: Record<string, unknown>;\n};\n\nexport type ExecutionMutationDefault = {\n readonly ref: { readonly table: string; readonly column: string };\n readonly onCreate?: ExecutionMutationDefaultValue;\n readonly onUpdate?: ExecutionMutationDefaultValue;\n};\n\nexport type ExecutionSection = {\n readonly mutations: {\n readonly defaults: ReadonlyArray<ExecutionMutationDefault>;\n };\n};\n\nexport interface Source {\n readonly readOnly: boolean;\n readonly projection: Record<string, FieldType>;\n readonly origin?: Record<string, unknown>;\n readonly capabilities?: Record<string, boolean>;\n}\n\n// Document family types\nexport interface DocIndex {\n readonly name: string;\n readonly keys: Record<string, 'asc' | 'desc'>;\n readonly unique?: boolean;\n readonly where?: Expr;\n}\n\nexport type Expr =\n | { readonly kind: 'eq'; readonly path: ReadonlyArray<string>; readonly value: unknown }\n | { readonly kind: 'exists'; readonly path: ReadonlyArray<string> };\n\nexport interface DocCollection {\n readonly name: string;\n readonly id?: {\n readonly strategy: 'auto' | 'client' | 'uuid' | 'objectId';\n };\n readonly fields: Record<string, FieldType>;\n readonly indexes?: ReadonlyArray<DocIndex>;\n readonly readOnly?: boolean;\n}\n\nexport interface DocumentStorage {\n readonly document: {\n readonly collections: Record<string, DocCollection>;\n };\n}\n\nexport interface DocumentContract<\n TStorageHash extends StorageHashBase<string> = StorageHashBase<string>,\n TExecutionHash extends ExecutionHashBase<string> = ExecutionHashBase<string>,\n TProfileHash extends ProfileHashBase<string> = ProfileHashBase<string>,\n> extends ContractBase<TStorageHash, TExecutionHash, TProfileHash> {\n // Accept string to work with JSON imports; runtime validation ensures 'document'\n readonly targetFamily: string;\n readonly storage: DocumentStorage;\n}\n\n// Plan types - target-family agnostic execution types\nexport interface ParamDescriptor {\n readonly index?: number;\n readonly name?: string;\n readonly codecId?: string;\n readonly nativeType?: string;\n readonly nullable?: boolean;\n readonly source: 'dsl' | 'raw' | 'lane';\n readonly refs?: { table: string; column: string };\n}\n\nexport interface PlanRefs {\n readonly tables?: readonly string[];\n readonly columns?: ReadonlyArray<{ table: string; column: string }>;\n readonly indexes?: ReadonlyArray<{\n readonly table: string;\n readonly columns: ReadonlyArray<string>;\n readonly name?: string;\n }>;\n}\n\nexport interface PlanMeta {\n readonly target: string;\n readonly targetFamily?: string;\n readonly storageHash: string;\n readonly profileHash?: string;\n readonly lane: string;\n readonly annotations?: {\n codecs?: Record<string, string>; // alias/param → codec id ('ns/name@v')\n [key: string]: unknown;\n };\n readonly paramDescriptors: ReadonlyArray<ParamDescriptor>;\n readonly refs?: PlanRefs;\n readonly projection?: Record<string, string> | ReadonlyArray<string>;\n /**\n * Optional mapping of projection alias → column type ID (fully qualified ns/name@version).\n * Used for codec resolution when AST+refs don't provide enough type info.\n */\n readonly projectionTypes?: Record<string, string>;\n}\n\n/**\n * Canonical execution plan shape used by runtimes.\n *\n * - Row is the inferred result row type (TypeScript-only).\n * - Ast is the optional, family-specific AST type (e.g. SQL QueryAst).\n *\n * The payload executed by the runtime is represented by the sql + params pair\n * for now; future families can specialize this via Ast or additional metadata.\n */\nexport interface ExecutionPlan<Row = unknown, Ast = unknown> {\n readonly sql: string;\n readonly params: readonly unknown[];\n readonly ast?: Ast;\n readonly meta: PlanMeta;\n /**\n * Phantom property to carry the Row generic for type-level utilities.\n * Not set at runtime; used only for ResultType extraction.\n */\n readonly _row?: Row;\n}\n\n/**\n * Utility type to extract the Row type from an ExecutionPlan.\n * Example: `type Row = ResultType<typeof plan>`\n *\n * Works with both ExecutionPlan and SqlQueryPlan (SQL query plans before lowering).\n * SqlQueryPlan includes a phantom `_Row` property to preserve the generic parameter\n * for type extraction.\n */\nexport type ResultType<P> =\n P extends ExecutionPlan<infer R, unknown> ? R : P extends { readonly _Row?: infer R } ? R : never;\n\n/**\n * Type guard to check if a contract is a Document contract\n */\nexport function isDocumentContract(contract: unknown): contract is DocumentContract {\n return (\n typeof contract === 'object' &&\n contract !== null &&\n 'targetFamily' in contract &&\n contract.targetFamily === 'document'\n );\n}\n\n/**\n * Contract marker record stored in the database.\n * Represents the current contract identity for a database.\n */\nexport interface ContractMarkerRecord {\n readonly storageHash: string;\n readonly profileHash: string;\n readonly contractJson: unknown | null;\n readonly canonicalVersion: number | null;\n readonly updatedAt: Date;\n readonly appTag: string | null;\n readonly meta: Record<string, unknown>;\n}\n\n// Emitter types - moved from @prisma-next/emitter to shared location\n/**\n * Specifies how to import TypeScript types from a package.\n * Used in extension pack manifests to declare codec and operation type imports.\n */\nexport interface TypesImportSpec {\n readonly package: string;\n readonly named: string;\n readonly alias: string;\n}\n\n/**\n * Validation context passed to TargetFamilyHook.validateTypes().\n * Contains pre-assembled operation registry, type imports, and extension IDs.\n */\nexport interface ValidationContext {\n readonly operationRegistry?: OperationRegistry;\n readonly codecTypeImports?: ReadonlyArray<TypesImportSpec>;\n readonly operationTypeImports?: ReadonlyArray<TypesImportSpec>;\n readonly extensionIds?: ReadonlyArray<string>;\n /**\n * Parameterized codec descriptors collected from adapters and extensions.\n * Map of codecId → descriptor for quick lookup during type generation.\n */\n readonly parameterizedCodecs?: Map<string, ParameterizedCodecDescriptor>;\n}\n\n/**\n * Context for rendering parameterized types during contract.d.ts generation.\n * Passed to type renderers so they can reference CodecTypes by name.\n */\nexport interface TypeRenderContext {\n readonly codecTypesName: string;\n}\n\n/**\n * A normalized type renderer for parameterized codecs.\n * This is the interface expected by TargetFamilyHook.generateContractTypes.\n */\nexport interface TypeRenderEntry {\n readonly codecId: string;\n readonly render: (params: Record<string, unknown>, ctx: TypeRenderContext) => string;\n}\n\n/**\n * Additional options for generateContractTypes.\n */\nexport interface GenerateContractTypesOptions {\n /**\n * Normalized parameterized type renderers, keyed by codecId.\n * When a column has typeParams and a renderer exists for its codecId,\n * the renderer is called to produce the TypeScript type expression.\n */\n readonly parameterizedRenderers?: Map<string, TypeRenderEntry>;\n /**\n * Type imports for parameterized codecs.\n * These are merged with codec and operation type imports in contract.d.ts.\n */\n readonly parameterizedTypeImports?: ReadonlyArray<TypesImportSpec>;\n /**\n * Query operation type imports for the query builder.\n * Flat operation signatures keyed by operation name, emitted as standalone QueryOperationTypes.\n */\n readonly queryOperationTypeImports?: ReadonlyArray<TypesImportSpec>;\n}\n\n/**\n * SPI interface for target family hooks that extend emission behavior.\n * Implemented by family-specific emitter hooks (e.g., SQL family).\n */\nexport interface TargetFamilyHook {\n readonly id: string;\n\n /**\n * Validates that all type IDs in the contract come from referenced extension packs.\n * @param contract - Contract to validate\n * @param ctx - Validation context with operation registry and extension IDs\n */\n validateTypes(contract: Contract, ctx: ValidationContext): void;\n\n /**\n * Validates family-specific contract structure.\n * @param contract - Contract to validate\n */\n validateStructure(contract: Contract): void;\n\n /**\n * Generates contract.d.ts file content.\n * @param contract - Contract\n * @param codecTypeImports - Array of codec type import specs\n * @param operationTypeImports - Array of operation type import specs\n * @param hashes - Contract hash values (storageHash, executionHash, profileHash)\n * @param options - Additional options including parameterized type renderers\n * @returns Generated TypeScript type definitions as string\n */\n generateContractTypes(\n contract: Contract,\n codecTypeImports: ReadonlyArray<TypesImportSpec>,\n operationTypeImports: ReadonlyArray<TypesImportSpec>,\n hashes: {\n readonly storageHash: string;\n readonly executionHash?: string;\n readonly profileHash: string;\n },\n options?: GenerateContractTypesOptions,\n ): string;\n}\n\n// ============================================================================\n// Parameterized Codec Descriptor Types\n// ============================================================================\n//\n// Types for codecs that support type parameters (e.g., Vector<1536>, Decimal<2>).\n// These enable precise TypeScript types for parameterized columns without\n// coupling the SQL family emitter to specific adapter codec IDs.\n//\n// ============================================================================\n\n/**\n * Declarative type renderer that produces a TypeScript type expression.\n *\n * Renderers can be:\n * - A template string with `{{paramName}}` placeholders (e.g., `Vector<{{length}}>`)\n * - A function that receives typeParams and context and returns a type expression\n *\n * **Prefer template strings** for most cases:\n * - Templates are JSON-serializable (safe for pack-ref metadata)\n * - Templates can be statically analyzed by tooling\n *\n * Function renderers are allowed but have tradeoffs:\n * - Require runtime execution during emission (the emitter runs code)\n * - Not JSON-serializable (can't be stored in contract.json)\n * - The emitted artifacts (contract.json, contract.d.ts) still contain no\n * executable code - this constraint applies to outputs, not the emission process\n */\nexport type TypeRenderer =\n | string\n | ((params: Record<string, unknown>, ctx: RenderTypeContext) => string);\n\n/**\n * Descriptor for a codec that supports type parameters.\n *\n * Parameterized codecs allow columns to carry additional metadata (typeParams)\n * that affects the generated TypeScript types. For example:\n * - A vector codec can use `{ length: 1536 }` to generate `Vector<1536>`\n * - A decimal codec can use `{ precision: 10, scale: 2 }` to generate `Decimal<10, 2>`\n *\n * The SQL family emitter uses these descriptors to generate precise types\n * without hard-coding knowledge of specific codec IDs.\n *\n * @example\n * ```typescript\n * const vectorCodecDescriptor: ParameterizedCodecDescriptor = {\n * codecId: 'pg/vector@1',\n * outputTypeRenderer: 'Vector<{{length}}>',\n * // Optional: paramsSchema for runtime validation\n * };\n * ```\n */\nexport interface ParameterizedCodecDescriptor {\n /** The codec ID this descriptor applies to (e.g., 'pg/vector@1') */\n readonly codecId: string;\n\n /**\n * Renderer for the output (read) type.\n * Can be a template string or function.\n *\n * This is the primary renderer used by SQL emission to generate\n * model field types in contract.d.ts.\n */\n readonly outputTypeRenderer: TypeRenderer;\n\n /**\n * Optional renderer for the input (write) type.\n * If not provided, outputTypeRenderer is used for both.\n *\n * **Reserved for future use**: Currently, SQL emission only uses\n * outputTypeRenderer. This field is defined for future support of\n * asymmetric codecs where input and output types differ (e.g., a\n * codec that accepts `string | number` but always returns `number`).\n */\n readonly inputTypeRenderer?: TypeRenderer;\n\n /**\n * Optional import spec for types used by this codec's renderers.\n * The emitter will add this import to contract.d.ts.\n */\n readonly typesImport?: TypesImportSpec;\n}\n"],"mappings":";AA2CA,SAAgB,SAAiC,OAA8B;AAC7E,QAAO;;AAUT,SAAgB,YAAoC,OAA8B;AAChF,QAAO;;AAqDT,SAAgB,eAAe,OAAuC;AACpE,QACE,OAAO,UAAU,YACjB,UAAU,QACT,MAA8B,UAAU,YACzC,OAAQ,MAA8B,UAAU;;AAIpD,SAAgB,mBAAmB,MAAc,OAAyB;AACxE,KAAI,OAAO,UAAU,SACnB,QAAO;EAAE,OAAO;EAAU,OAAO,MAAM,UAAU;EAAE;AAErD,QAAO;;AAKT,SAAgB,YAAY,OAAoC;AAC9D,QACE,OAAO,UAAU,YACjB,UAAU,QACT,MAA8B,UAAU,SACzC,WAAY;;;;;AA4JhB,SAAgB,mBAAmB,UAAiD;AAClF,QACE,OAAO,aAAa,YACpB,aAAa,QACb,kBAAkB,YAClB,SAAS,iBAAiB"}
|
package/dist/types.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as ContractModel, A as
|
|
1
|
+
import { $ as ContractModel, A as Source, B as TypesImportSpec, C as ParamDescriptor, D as ProfileHashBase, E as PlanRefs, F as TaggedRaw, G as isTaggedBigInt, H as bigintJsonReplacer, I as TargetFamilyHook, J as Contract, K as isTaggedRaw, L as TypeRenderContext, M as StorageHashBase, N as TaggedBigInt, O as RenderTypeContext, P as TaggedLiteralValue, Q as ContractField, R as TypeRenderEntry, S as JsonValue, T as PlanMeta, U as coreHash, V as ValidationContext, W as isDocumentContract, X as ContractDiscriminator, Y as ContractExecutionSection, Z as ContractEmbedRelation, _ as Expr, a as ColumnDefaultLiteralValue, at as DomainEmbedRelation, b as GeneratedValueSpec, c as DocCollection, ct as DomainReferenceRelation, d as DocumentStorage, dt as DomainVariantEntry, et as ContractReferenceRelation, f as ExecutionHashBase, ft as EmbedRelationKeys, g as ExecutionSection, h as ExecutionPlan, i as ColumnDefaultLiteralInputValue, it as DomainDiscriminator, j as StorageBase, k as ResultType, l as DocIndex, lt as DomainRelation, m as ExecutionMutationDefaultValue, mt as ReferenceRelationKeys, n as Brand, nt as ContractRelationOn, o as ContractBase, ot as DomainField, p as ExecutionMutationDefault, pt as ModelStorageBase, q as profileHash, r as ColumnDefault, rt as ContractVariantEntry, s as ContractMarkerRecord, st as DomainModel, t as $, tt as ContractRelation, u as DocumentContract, ut as DomainRelationOn, v as FieldType, w as ParameterizedCodecDescriptor, x as JsonPrimitive, y as GenerateContractTypesOptions, z as TypeRenderer } from "./types-D-iOS0Ks.mjs";
|
|
2
2
|
export { type $, type Brand, type ColumnDefault, type ColumnDefaultLiteralInputValue, type ColumnDefaultLiteralValue, type Contract, type ContractBase, type ContractDiscriminator, type ContractEmbedRelation, type ContractExecutionSection, type ContractField, type ContractMarkerRecord, type ContractModel, type ContractReferenceRelation, type ContractRelation, type ContractRelationOn, type ContractVariantEntry, type DocCollection, type DocIndex, type DocumentContract, type DocumentStorage, type DomainDiscriminator, type DomainEmbedRelation, type DomainField, type DomainModel, type DomainReferenceRelation, type DomainRelation, type DomainRelationOn, type DomainVariantEntry, type EmbedRelationKeys, type ExecutionHashBase, type ExecutionMutationDefault, type ExecutionMutationDefaultValue, type ExecutionPlan, type ExecutionSection, type Expr, type FieldType, type GenerateContractTypesOptions, type GeneratedValueSpec, type JsonPrimitive, type JsonValue, type ModelStorageBase, type ParamDescriptor, type ParameterizedCodecDescriptor, type PlanMeta, type PlanRefs, type ProfileHashBase, type ReferenceRelationKeys, type RenderTypeContext, type ResultType, type Source, type StorageBase, type StorageHashBase, type TaggedBigInt, type TaggedLiteralValue, type TaggedRaw, type TargetFamilyHook, type TypeRenderContext, type TypeRenderEntry, type TypeRenderer, type TypesImportSpec, type ValidationContext, bigintJsonReplacer, coreHash, isDocumentContract, isTaggedBigInt, isTaggedRaw, profileHash };
|
package/dist/types.mjs
CHANGED
|
@@ -1,30 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
function coreHash(value) {
|
|
3
|
-
return value;
|
|
4
|
-
}
|
|
5
|
-
function profileHash(value) {
|
|
6
|
-
return value;
|
|
7
|
-
}
|
|
8
|
-
function isTaggedBigInt(value) {
|
|
9
|
-
return typeof value === "object" && value !== null && value.$type === "bigint" && typeof value.value === "string";
|
|
10
|
-
}
|
|
11
|
-
function bigintJsonReplacer(_key, value) {
|
|
12
|
-
if (typeof value === "bigint") return {
|
|
13
|
-
$type: "bigint",
|
|
14
|
-
value: value.toString()
|
|
15
|
-
};
|
|
16
|
-
return value;
|
|
17
|
-
}
|
|
18
|
-
function isTaggedRaw(value) {
|
|
19
|
-
return typeof value === "object" && value !== null && value.$type === "raw" && "value" in value;
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* Type guard to check if a contract is a Document contract
|
|
23
|
-
*/
|
|
24
|
-
function isDocumentContract(contract) {
|
|
25
|
-
return typeof contract === "object" && contract !== null && "targetFamily" in contract && contract.targetFamily === "document";
|
|
26
|
-
}
|
|
1
|
+
import { a as isTaggedRaw, i as isTaggedBigInt, n as coreHash, o as profileHash, r as isDocumentContract, t as bigintJsonReplacer } from "./types-DokLaU9G.mjs";
|
|
27
2
|
|
|
28
|
-
|
|
29
|
-
export { bigintJsonReplacer, coreHash, isDocumentContract, isTaggedBigInt, isTaggedRaw, profileHash };
|
|
30
|
-
//# sourceMappingURL=types.mjs.map
|
|
3
|
+
export { bigintJsonReplacer, coreHash, isDocumentContract, isTaggedBigInt, isTaggedRaw, profileHash };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate-domain-
|
|
1
|
+
{"version":3,"file":"validate-domain-CTQiBiei.mjs","names":["errors: string[]","warnings: string[]"],"sources":["../src/validate-domain.ts"],"sourcesContent":["export interface DomainModelShape {\n readonly fields: Record<string, unknown>;\n readonly relations?: Record<string, { readonly to: string }>;\n readonly discriminator?: { readonly field: string };\n readonly variants?: Record<string, unknown>;\n readonly base?: string;\n readonly owner?: string;\n}\n\nexport interface DomainContractShape {\n readonly roots: Record<string, string>;\n readonly models: Record<string, DomainModelShape>;\n}\n\nexport interface DomainValidationResult {\n readonly warnings: string[];\n}\n\nexport function validateContractDomain(contract: DomainContractShape): DomainValidationResult {\n const errors: string[] = [];\n const warnings: string[] = [];\n const modelNames = new Set(Object.keys(contract.models));\n\n validateRoots(contract, modelNames, errors);\n validateVariantsAndBases(contract, modelNames, errors);\n validateRelationTargets(contract, modelNames, errors);\n validateDiscriminators(contract, errors);\n validateOwnership(contract, modelNames, errors);\n detectOrphanedModels(contract, modelNames, warnings);\n\n if (errors.length > 0) {\n throw new Error(`Contract domain validation failed:\\n- ${errors.join('\\n- ')}`);\n }\n\n return { warnings };\n}\n\nfunction validateRoots(\n contract: DomainContractShape,\n modelNames: Set<string>,\n errors: string[],\n): void {\n const seenValues = new Set<string>();\n for (const [rootKey, modelName] of Object.entries(contract.roots)) {\n if (seenValues.has(modelName)) {\n errors.push(`Duplicate root value: \"${modelName}\" is mapped by multiple root keys`);\n }\n seenValues.add(modelName);\n\n if (!modelNames.has(modelName)) {\n errors.push(\n `Root \"${rootKey}\" references model \"${modelName}\" which does not exist in models`,\n );\n }\n }\n}\n\nfunction validateVariantsAndBases(\n contract: DomainContractShape,\n modelNames: Set<string>,\n errors: string[],\n): void {\n const models = new Map(Object.entries(contract.models));\n\n for (const [modelName, model] of models) {\n if (model.variants) {\n for (const variantName of Object.keys(model.variants)) {\n if (!modelNames.has(variantName)) {\n errors.push(\n `Model \"${modelName}\" lists variant \"${variantName}\" which does not exist in models`,\n );\n continue;\n }\n const variantModel = models.get(variantName);\n if (!variantModel) continue;\n if (variantModel.base !== modelName) {\n errors.push(\n `Variant \"${variantName}\" has base \"${variantModel.base ?? '(none)'}\" but expected \"${modelName}\"`,\n );\n }\n }\n }\n\n if (model.base) {\n if (!modelNames.has(model.base)) {\n errors.push(`Model \"${modelName}\" has base \"${model.base}\" which does not exist in models`);\n continue;\n }\n const baseModel = models.get(model.base);\n if (!baseModel) continue;\n if (!baseModel.variants || !Object.hasOwn(baseModel.variants, modelName)) {\n errors.push(\n `Model \"${modelName}\" has base \"${model.base}\" which does not list it as a variant`,\n );\n }\n }\n }\n}\n\nfunction validateRelationTargets(\n contract: DomainContractShape,\n modelNames: Set<string>,\n errors: string[],\n): void {\n for (const [modelName, model] of Object.entries(contract.models)) {\n for (const [relName, relation] of Object.entries(model.relations ?? {})) {\n if (!modelNames.has(relation.to)) {\n errors.push(\n `Relation \"${relName}\" on model \"${modelName}\" targets \"${relation.to}\" which does not exist in models`,\n );\n }\n }\n }\n}\n\nfunction validateDiscriminators(contract: DomainContractShape, errors: string[]): void {\n for (const [modelName, model] of Object.entries(contract.models)) {\n if (model.discriminator) {\n if (!model.variants || Object.keys(model.variants).length === 0) {\n errors.push(`Model \"${modelName}\" has discriminator but no variants`);\n }\n if (!Object.hasOwn(model.fields, model.discriminator.field)) {\n errors.push(\n `Discriminator field \"${model.discriminator.field}\" is not a field on model \"${modelName}\"`,\n );\n }\n }\n\n if (model.variants && Object.keys(model.variants).length > 0 && !model.discriminator) {\n errors.push(`Model \"${modelName}\" has variants but no discriminator`);\n }\n\n if (model.base) {\n if (model.discriminator) {\n errors.push(`Model \"${modelName}\" has base and must not have discriminator`);\n }\n if (model.variants && Object.keys(model.variants).length > 0) {\n errors.push(`Model \"${modelName}\" has base and must not have variants`);\n }\n }\n }\n}\n\nfunction validateOwnership(\n contract: DomainContractShape,\n modelNames: Set<string>,\n errors: string[],\n): void {\n for (const [modelName, model] of Object.entries(contract.models)) {\n if (!model.owner) continue;\n\n if (model.owner === modelName) {\n errors.push(`Model \"${modelName}\" cannot own itself`);\n }\n\n if (!modelNames.has(model.owner)) {\n errors.push(`Model \"${modelName}\" has owner \"${model.owner}\" which does not exist in models`);\n }\n\n for (const [rootKey, rootModel] of Object.entries(contract.roots)) {\n if (rootModel === modelName) {\n errors.push(\n `Owned model \"${modelName}\" must not appear in roots (found as root \"${rootKey}\")`,\n );\n }\n }\n }\n}\n\nfunction detectOrphanedModels(\n contract: DomainContractShape,\n modelNames: Set<string>,\n warnings: string[],\n): void {\n const referenced = new Set<string>();\n\n for (const modelName of Object.values(contract.roots)) {\n referenced.add(modelName);\n }\n\n for (const [modelName, model] of Object.entries(contract.models)) {\n for (const relation of Object.values(model.relations ?? {})) {\n referenced.add(relation.to);\n }\n if (model.variants) {\n for (const variantName of Object.keys(model.variants)) {\n referenced.add(variantName);\n }\n }\n if (model.base) {\n referenced.add(model.base);\n }\n if (model.owner) {\n referenced.add(modelName);\n }\n }\n\n for (const modelName of modelNames) {\n if (!referenced.has(modelName)) {\n warnings.push(\n `Orphaned model: \"${modelName}\" is not referenced by any root, relation, or variant`,\n );\n }\n }\n}\n"],"mappings":"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"}
|
package/dist/validate-domain.mjs
CHANGED
package/package.json
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/contract",
|
|
3
|
-
"version": "0.3.0-dev.
|
|
3
|
+
"version": "0.3.0-dev.140",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"description": "Data contract type definitions and JSON schema for Prisma Next",
|
|
7
7
|
"dependencies": {
|
|
8
8
|
"arktype": "^2.1.29",
|
|
9
|
-
"@prisma-next/
|
|
10
|
-
"@prisma-next/
|
|
9
|
+
"@prisma-next/operations": "0.3.0-dev.140",
|
|
10
|
+
"@prisma-next/utils": "0.3.0-dev.140"
|
|
11
11
|
},
|
|
12
12
|
"devDependencies": {
|
|
13
13
|
"tsdown": "0.18.4",
|
|
14
14
|
"typescript": "5.9.3",
|
|
15
15
|
"vitest": "4.0.17",
|
|
16
|
+
"@prisma-next/tsconfig": "0.0.0",
|
|
16
17
|
"@prisma-next/test-utils": "0.0.1",
|
|
17
|
-
"@prisma-next/tsdown": "0.0.0"
|
|
18
|
-
"@prisma-next/tsconfig": "0.0.0"
|
|
18
|
+
"@prisma-next/tsdown": "0.0.0"
|
|
19
19
|
},
|
|
20
20
|
"files": [
|
|
21
21
|
"dist",
|
|
@@ -26,10 +26,11 @@
|
|
|
26
26
|
"node": ">=20"
|
|
27
27
|
},
|
|
28
28
|
"exports": {
|
|
29
|
-
"./
|
|
29
|
+
"./hashing": "./dist/hashing.mjs",
|
|
30
|
+
"./testing": "./dist/testing.mjs",
|
|
30
31
|
"./types": "./dist/types.mjs",
|
|
31
|
-
"./validate-domain": "./dist/validate-domain.mjs",
|
|
32
32
|
"./validate-contract": "./dist/validate-contract.mjs",
|
|
33
|
+
"./validate-domain": "./dist/validate-domain.mjs",
|
|
33
34
|
"./package.json": "./package.json"
|
|
34
35
|
},
|
|
35
36
|
"repository": {
|
|
@@ -29,11 +29,6 @@
|
|
|
29
29
|
"pattern": "^sha256:[a-f0-9]{64}$",
|
|
30
30
|
"description": "SHA-256 hash of the storage section (DB-satisfied expectations)"
|
|
31
31
|
},
|
|
32
|
-
"executionHash": {
|
|
33
|
-
"type": "string",
|
|
34
|
-
"pattern": "^sha256:[a-f0-9]{64}$",
|
|
35
|
-
"description": "SHA-256 hash of the execution section (client-side behavior)"
|
|
36
|
-
},
|
|
37
32
|
"profileHash": {
|
|
38
33
|
"type": "string",
|
|
39
34
|
"pattern": "^sha256:[a-f0-9]{64}$",
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import { isArrayEqual } from '@prisma-next/utils/array-equal';
|
|
2
|
+
|
|
3
|
+
import type { StorageBase } from './types';
|
|
4
|
+
import { bigintJsonReplacer } from './types';
|
|
5
|
+
|
|
6
|
+
const TOP_LEVEL_ORDER = [
|
|
7
|
+
'schemaVersion',
|
|
8
|
+
'canonicalVersion',
|
|
9
|
+
'targetFamily',
|
|
10
|
+
'target',
|
|
11
|
+
'profileHash',
|
|
12
|
+
'roots',
|
|
13
|
+
'models',
|
|
14
|
+
'storage',
|
|
15
|
+
'execution',
|
|
16
|
+
'capabilities',
|
|
17
|
+
'extensionPacks',
|
|
18
|
+
'meta',
|
|
19
|
+
] as const;
|
|
20
|
+
|
|
21
|
+
function isDefaultValue(value: unknown): boolean {
|
|
22
|
+
if (value === false) return true;
|
|
23
|
+
if (value === null) return false;
|
|
24
|
+
if (value instanceof Date) return false;
|
|
25
|
+
if (Array.isArray(value) && value.length === 0) return true;
|
|
26
|
+
if (typeof value === 'object' && value !== null) {
|
|
27
|
+
const keys = Object.keys(value);
|
|
28
|
+
return keys.length === 0;
|
|
29
|
+
}
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function omitDefaults(obj: unknown, path: readonly string[]): unknown {
|
|
34
|
+
if (obj === null || typeof obj !== 'object') {
|
|
35
|
+
return obj;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (obj instanceof Date) {
|
|
39
|
+
return obj;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (Array.isArray(obj)) {
|
|
43
|
+
return obj.map((item) => omitDefaults(item, path));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const result: Record<string, unknown> = {};
|
|
47
|
+
|
|
48
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
49
|
+
const currentPath = [...path, key];
|
|
50
|
+
|
|
51
|
+
if (key === '_generated') {
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (key === 'nullable' && value === false) {
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (key === 'generated' && value === false) {
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if ((key === 'onDelete' || key === 'onUpdate') && value === 'noAction') {
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (isDefaultValue(value)) {
|
|
68
|
+
const isRequiredModels = isArrayEqual(currentPath, ['models']);
|
|
69
|
+
const isRequiredTables = isArrayEqual(currentPath, ['storage', 'tables']);
|
|
70
|
+
const isRequiredCollections = isArrayEqual(currentPath, ['storage', 'collections']);
|
|
71
|
+
const isCollectionEntry =
|
|
72
|
+
currentPath.length === 3 &&
|
|
73
|
+
isArrayEqual([currentPath[0], currentPath[1]], ['storage', 'collections']);
|
|
74
|
+
const isRequiredRoots = isArrayEqual(currentPath, ['roots']);
|
|
75
|
+
const isRequiredExtensionPacks = isArrayEqual(currentPath, ['extensionPacks']);
|
|
76
|
+
const isRequiredCapabilities = isArrayEqual(currentPath, ['capabilities']);
|
|
77
|
+
const isRequiredMeta = isArrayEqual(currentPath, ['meta']);
|
|
78
|
+
const isRequiredExecutionDefaults = isArrayEqual(currentPath, [
|
|
79
|
+
'execution',
|
|
80
|
+
'mutations',
|
|
81
|
+
'defaults',
|
|
82
|
+
]);
|
|
83
|
+
const isExtensionNamespace = currentPath.length === 2 && currentPath[0] === 'extensionPacks';
|
|
84
|
+
const isModelRelations =
|
|
85
|
+
currentPath.length === 3 &&
|
|
86
|
+
isArrayEqual([currentPath[0], currentPath[2]], ['models', 'relations']);
|
|
87
|
+
const isModelStorage =
|
|
88
|
+
currentPath.length === 3 &&
|
|
89
|
+
isArrayEqual([currentPath[0], currentPath[2]], ['models', 'storage']);
|
|
90
|
+
const isTableUniques =
|
|
91
|
+
currentPath.length === 4 &&
|
|
92
|
+
isArrayEqual(
|
|
93
|
+
[currentPath[0], currentPath[1], currentPath[3]],
|
|
94
|
+
['storage', 'tables', 'uniques'],
|
|
95
|
+
);
|
|
96
|
+
const isTableIndexes =
|
|
97
|
+
currentPath.length === 4 &&
|
|
98
|
+
isArrayEqual(
|
|
99
|
+
[currentPath[0], currentPath[1], currentPath[3]],
|
|
100
|
+
['storage', 'tables', 'indexes'],
|
|
101
|
+
);
|
|
102
|
+
const isTableForeignKeys =
|
|
103
|
+
currentPath.length === 4 &&
|
|
104
|
+
isArrayEqual(
|
|
105
|
+
[currentPath[0], currentPath[1], currentPath[3]],
|
|
106
|
+
['storage', 'tables', 'foreignKeys'],
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
const isFkBooleanField =
|
|
110
|
+
currentPath.length === 5 &&
|
|
111
|
+
currentPath[0] === 'storage' &&
|
|
112
|
+
currentPath[1] === 'tables' &&
|
|
113
|
+
currentPath[3] === 'foreignKeys' &&
|
|
114
|
+
(key === 'constraint' || key === 'index');
|
|
115
|
+
|
|
116
|
+
if (
|
|
117
|
+
!isRequiredModels &&
|
|
118
|
+
!isRequiredTables &&
|
|
119
|
+
!isRequiredCollections &&
|
|
120
|
+
!isCollectionEntry &&
|
|
121
|
+
!isRequiredRoots &&
|
|
122
|
+
!isRequiredExtensionPacks &&
|
|
123
|
+
!isRequiredCapabilities &&
|
|
124
|
+
!isRequiredMeta &&
|
|
125
|
+
!isRequiredExecutionDefaults &&
|
|
126
|
+
!isExtensionNamespace &&
|
|
127
|
+
!isModelRelations &&
|
|
128
|
+
!isModelStorage &&
|
|
129
|
+
!isTableUniques &&
|
|
130
|
+
!isTableIndexes &&
|
|
131
|
+
!isTableForeignKeys &&
|
|
132
|
+
!isFkBooleanField
|
|
133
|
+
) {
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
result[key] = omitDefaults(value, currentPath);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return result;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function sortObjectKeys(obj: unknown): unknown {
|
|
145
|
+
if (obj === null || typeof obj !== 'object') {
|
|
146
|
+
return obj;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (obj instanceof Date) {
|
|
150
|
+
return obj;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (Array.isArray(obj)) {
|
|
154
|
+
return obj.map((item) => sortObjectKeys(item));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const sorted: Record<string, unknown> = {};
|
|
158
|
+
const keys = Object.keys(obj).sort();
|
|
159
|
+
for (const key of keys) {
|
|
160
|
+
sorted[key] = sortObjectKeys((obj as Record<string, unknown>)[key]);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
return sorted;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
type StorageObject = {
|
|
167
|
+
tables?: Record<string, unknown>;
|
|
168
|
+
[key: string]: unknown;
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
type TableObject = {
|
|
172
|
+
indexes?: unknown[];
|
|
173
|
+
uniques?: unknown[];
|
|
174
|
+
[key: string]: unknown;
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
function sortIndexesAndUniques(storage: unknown): unknown {
|
|
178
|
+
if (!storage || typeof storage !== 'object') {
|
|
179
|
+
return storage;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const storageObj = storage as StorageObject;
|
|
183
|
+
if (!storageObj.tables || typeof storageObj.tables !== 'object') {
|
|
184
|
+
return storage;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const tables = storageObj.tables;
|
|
188
|
+
const result: StorageObject = { ...storageObj };
|
|
189
|
+
|
|
190
|
+
result.tables = {};
|
|
191
|
+
const sortedTableNames = Object.keys(tables).sort();
|
|
192
|
+
for (const tableName of sortedTableNames) {
|
|
193
|
+
const table = tables[tableName];
|
|
194
|
+
if (!table || typeof table !== 'object') {
|
|
195
|
+
result.tables[tableName] = table;
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const tableObj = table as TableObject;
|
|
200
|
+
const sortedTable: TableObject = { ...tableObj };
|
|
201
|
+
|
|
202
|
+
if (Array.isArray(tableObj.indexes)) {
|
|
203
|
+
sortedTable.indexes = [...tableObj.indexes].sort((a, b) => {
|
|
204
|
+
const nameA = (a as { name?: string })?.name || '';
|
|
205
|
+
const nameB = (b as { name?: string })?.name || '';
|
|
206
|
+
return nameA.localeCompare(nameB);
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (Array.isArray(tableObj.uniques)) {
|
|
211
|
+
sortedTable.uniques = [...tableObj.uniques].sort((a, b) => {
|
|
212
|
+
const nameA = (a as { name?: string })?.name || '';
|
|
213
|
+
const nameB = (b as { name?: string })?.name || '';
|
|
214
|
+
return nameA.localeCompare(nameB);
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
result.tables[tableName] = sortedTable;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return result;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function orderTopLevel(obj: Record<string, unknown>): Record<string, unknown> {
|
|
225
|
+
const ordered: Record<string, unknown> = {};
|
|
226
|
+
const remaining = new Set(Object.keys(obj));
|
|
227
|
+
|
|
228
|
+
for (const key of TOP_LEVEL_ORDER) {
|
|
229
|
+
if (remaining.has(key)) {
|
|
230
|
+
ordered[key] = obj[key];
|
|
231
|
+
remaining.delete(key);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
for (const key of Array.from(remaining).sort()) {
|
|
236
|
+
ordered[key] = obj[key];
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
return ordered;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export type CanonicalContractInput = {
|
|
243
|
+
readonly schemaVersion?: string | undefined;
|
|
244
|
+
readonly targetFamily: string;
|
|
245
|
+
readonly target: string;
|
|
246
|
+
readonly profileHash?: string | undefined;
|
|
247
|
+
readonly roots: Record<string, string>;
|
|
248
|
+
readonly models: Record<string, unknown>;
|
|
249
|
+
// StorageBase is an interface without an index signature, so it is not
|
|
250
|
+
// assignable to Record<string, unknown>. The union allows callers to pass
|
|
251
|
+
// either the typed StorageBase or a plain record.
|
|
252
|
+
readonly storage: StorageBase | Record<string, unknown>;
|
|
253
|
+
readonly execution?: Record<string, unknown> | undefined;
|
|
254
|
+
readonly extensionPacks: Record<string, unknown>;
|
|
255
|
+
readonly capabilities: Record<string, Record<string, boolean>>;
|
|
256
|
+
readonly meta: Record<string, unknown>;
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
export function canonicalizeContractToObject(
|
|
260
|
+
input: CanonicalContractInput,
|
|
261
|
+
): Record<string, unknown> {
|
|
262
|
+
const i = input as Record<string, unknown>;
|
|
263
|
+
const normalized: Record<string, unknown> = {
|
|
264
|
+
...(i['schemaVersion'] !== undefined ? { schemaVersion: i['schemaVersion'] } : {}),
|
|
265
|
+
targetFamily: i['targetFamily'],
|
|
266
|
+
target: i['target'],
|
|
267
|
+
...(i['profileHash'] !== undefined ? { profileHash: i['profileHash'] } : {}),
|
|
268
|
+
roots: i['roots'],
|
|
269
|
+
models: i['models'],
|
|
270
|
+
storage: i['storage'],
|
|
271
|
+
...(i['execution'] !== undefined ? { execution: i['execution'] } : {}),
|
|
272
|
+
extensionPacks: i['extensionPacks'],
|
|
273
|
+
capabilities: i['capabilities'],
|
|
274
|
+
meta: i['meta'],
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
const withDefaultsOmitted = omitDefaults(normalized, []) as Record<string, unknown>;
|
|
278
|
+
const withSortedIndexes = sortIndexesAndUniques(withDefaultsOmitted['storage']);
|
|
279
|
+
const withSortedStorage = { ...withDefaultsOmitted, storage: withSortedIndexes };
|
|
280
|
+
const withSortedKeys = sortObjectKeys(withSortedStorage) as Record<string, unknown>;
|
|
281
|
+
return orderTopLevel(withSortedKeys);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export function canonicalizeContract(input: CanonicalContractInput): string {
|
|
285
|
+
return JSON.stringify(canonicalizeContractToObject(input), bigintJsonReplacer, 2);
|
|
286
|
+
}
|
package/src/contract-types.ts
CHANGED
|
@@ -49,6 +49,6 @@ export interface Contract<
|
|
|
49
49
|
readonly capabilities: Record<string, Record<string, boolean>>;
|
|
50
50
|
readonly extensionPacks: Record<string, unknown>;
|
|
51
51
|
readonly execution?: ContractExecutionSection;
|
|
52
|
-
readonly profileHash
|
|
52
|
+
readonly profileHash: ProfileHashBase<string>;
|
|
53
53
|
readonly meta: Record<string, unknown>;
|
|
54
54
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createContract, createSqlContract, DUMMY_HASH } from '../testing-factories';
|
package/src/hashing.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { canonicalizeContract } from './canonicalization';
|
|
3
|
+
import type { ExecutionHashBase, ProfileHashBase, StorageHashBase } from './types';
|
|
4
|
+
|
|
5
|
+
const SCHEMA_VERSION = '1';
|
|
6
|
+
|
|
7
|
+
function sha256(content: string): string {
|
|
8
|
+
const hash = createHash('sha256');
|
|
9
|
+
hash.update(content);
|
|
10
|
+
return `sha256:${hash.digest('hex')}`;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function computeStorageHash(args: {
|
|
14
|
+
target: string;
|
|
15
|
+
targetFamily: string;
|
|
16
|
+
storage: Record<string, unknown>;
|
|
17
|
+
}): StorageHashBase<string> {
|
|
18
|
+
const canonical = canonicalizeContract({
|
|
19
|
+
schemaVersion: SCHEMA_VERSION,
|
|
20
|
+
targetFamily: args.targetFamily,
|
|
21
|
+
target: args.target,
|
|
22
|
+
storage: args.storage,
|
|
23
|
+
roots: {},
|
|
24
|
+
models: {},
|
|
25
|
+
extensionPacks: {},
|
|
26
|
+
capabilities: {},
|
|
27
|
+
meta: {},
|
|
28
|
+
});
|
|
29
|
+
return sha256(canonical) as StorageHashBase<string>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function computeExecutionHash(args: {
|
|
33
|
+
target: string;
|
|
34
|
+
targetFamily: string;
|
|
35
|
+
execution: Record<string, unknown>;
|
|
36
|
+
}): ExecutionHashBase<string> {
|
|
37
|
+
const canonical = canonicalizeContract({
|
|
38
|
+
schemaVersion: SCHEMA_VERSION,
|
|
39
|
+
targetFamily: args.targetFamily,
|
|
40
|
+
target: args.target,
|
|
41
|
+
execution: args.execution,
|
|
42
|
+
roots: {},
|
|
43
|
+
models: {},
|
|
44
|
+
storage: {},
|
|
45
|
+
extensionPacks: {},
|
|
46
|
+
capabilities: {},
|
|
47
|
+
meta: {},
|
|
48
|
+
});
|
|
49
|
+
return sha256(canonical) as ExecutionHashBase<string>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function computeProfileHash(args: {
|
|
53
|
+
target: string;
|
|
54
|
+
targetFamily: string;
|
|
55
|
+
capabilities: Record<string, Record<string, boolean>>;
|
|
56
|
+
}): ProfileHashBase<string> {
|
|
57
|
+
const canonical = canonicalizeContract({
|
|
58
|
+
schemaVersion: SCHEMA_VERSION,
|
|
59
|
+
targetFamily: args.targetFamily,
|
|
60
|
+
target: args.target,
|
|
61
|
+
capabilities: args.capabilities,
|
|
62
|
+
roots: {},
|
|
63
|
+
models: {},
|
|
64
|
+
storage: {},
|
|
65
|
+
extensionPacks: {},
|
|
66
|
+
meta: {},
|
|
67
|
+
});
|
|
68
|
+
return sha256(canonical) as ProfileHashBase<string>;
|
|
69
|
+
}
|