@confect/core 10.0.0-next.20 → 10.0.0-next.22
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/CHANGELOG.md +162 -80
- package/dist/FunctionProvenance.d.ts +5 -6
- package/dist/FunctionProvenance.d.ts.map +1 -1
- package/dist/FunctionProvenance.js +3 -4
- package/dist/FunctionProvenance.js.map +1 -1
- package/dist/FunctionSpec.d.ts +3 -1
- package/dist/FunctionSpec.d.ts.map +1 -1
- package/dist/FunctionSpec.js +12 -6
- package/dist/FunctionSpec.js.map +1 -1
- package/dist/GroupSpec.d.ts +5 -1
- package/dist/GroupSpec.d.ts.map +1 -1
- package/dist/GroupSpec.js +31 -17
- package/dist/GroupSpec.js.map +1 -1
- package/dist/Identifier.d.ts +1 -1
- package/dist/Identifier.js +1 -1
- package/dist/Identifier.js.map +1 -1
- package/dist/Lazy.d.ts +4 -5
- package/dist/Lazy.d.ts.map +1 -1
- package/dist/Lazy.js +4 -5
- package/dist/Lazy.js.map +1 -1
- package/dist/MiddlewareAttachment.d.ts +171 -0
- package/dist/MiddlewareAttachment.d.ts.map +1 -0
- package/dist/MiddlewareAttachment.js +48 -0
- package/dist/MiddlewareAttachment.js.map +1 -0
- package/dist/MiddlewareSpec.d.ts +35 -23
- package/dist/MiddlewareSpec.d.ts.map +1 -1
- package/dist/MiddlewareSpec.js +1 -0
- package/dist/MiddlewareSpec.js.map +1 -1
- package/dist/PaginationOptions.d.ts +1 -1
- package/dist/PaginationOptions.js +1 -1
- package/dist/PaginationOptions.js.map +1 -1
- package/dist/Ref.d.ts +8 -7
- package/dist/Ref.d.ts.map +1 -1
- package/dist/Ref.js +11 -9
- package/dist/Ref.js.map +1 -1
- package/dist/Refs.js +1 -1
- package/dist/Refs.js.map +1 -1
- package/dist/SchemaToValidator.d.ts.map +1 -1
- package/dist/SchemaToValidator.js +4 -2
- package/dist/SchemaToValidator.js.map +1 -1
- package/dist/Spec.d.ts +1 -1
- package/dist/Spec.js.map +1 -1
- package/dist/SystemFields.d.ts +3 -4
- package/dist/SystemFields.d.ts.map +1 -1
- package/dist/SystemFields.js +5 -6
- package/dist/SystemFields.js.map +1 -1
- package/dist/Table.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/package.json +10 -10
- package/src/FunctionProvenance.ts +6 -8
- package/src/FunctionSpec.ts +21 -7
- package/src/GroupSpec.ts +74 -26
- package/src/Identifier.ts +1 -1
- package/src/Lazy.ts +4 -5
- package/src/MiddlewareAttachment.ts +106 -0
- package/src/MiddlewareSpec.ts +55 -21
- package/src/PaginationOptions.ts +1 -1
- package/src/Ref.ts +42 -37
- package/src/Refs.ts +1 -1
- package/src/SchemaToValidator.ts +56 -45
- package/src/Spec.ts +1 -1
- package/src/SystemFields.ts +9 -10
- package/src/Table.ts +2 -2
- package/src/index.ts +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SchemaToValidator.js","names":["GenericId.tableName"],"sources":["../src/SchemaToValidator.ts"],"sourcesContent":["import type {\n PropertyValidators,\n Validator,\n VAny,\n VArray,\n VBoolean,\n VBytes,\n VFloat64,\n VId,\n VInt64,\n VLiteral,\n VNull,\n VObject,\n VOptional,\n VRecord,\n VString,\n VUnion,\n} from \"convex/values\";\nimport { v } from \"convex/values\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\nimport * as Match from \"effect/Match\";\nimport * as Number from \"effect/Number\";\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaAST from \"effect/SchemaAST\";\nimport * as String from \"effect/String\";\n\nimport * as GenericId from \"./GenericId\";\nimport type {\n IsAny,\n IsOptional,\n IsRecord,\n IsRecursive,\n IsUnion,\n TypeError,\n UnionToTuple,\n} from \"./Types\";\n\n// Args\n\nexport const compileArgsSchema = <ConfectValue, ConvexValue>(\n argsSchema: Schema.Codec<ConfectValue, ConvexValue>,\n): PropertyValidators => {\n const ast = Schema.toEncoded(argsSchema).ast;\n\n return pipe(\n ast,\n Match.value,\n Match.tag(\"Objects\", (objectsAst) =>\n Array.isReadonlyArrayEmpty(objectsAst.indexSignatures)\n ? handlePropertySignatures(objectsAst)\n : Effect.fail(new IndexSignaturesAreNotSupportedError()),\n ),\n Match.orElse(() => Effect.fail(new TopLevelMustBeObjectError())),\n Effect.runSync,\n );\n};\n\n// Returns\n\nexport const compileReturnsSchema = <ConfectValue, ConvexValue>(\n schema: Schema.Codec<ConfectValue, ConvexValue>,\n): Validator<any, any, any> =>\n Effect.runSync(compileAst(Schema.toEncoded(schema).ast));\n\n// Table\n\n/**\n * Convert a table `Schema` to a table `Validator`.\n */\nexport type TableSchemaToTableValidator<\n TableSchema extends Schema.Codec<any, any>,\n> =\n ValueToValidator<TableSchema[\"Encoded\"]> extends infer Vd extends\n | VObject<any, any, any, any>\n | VUnion<any, any, any, any>\n ? Vd\n : never;\n\nexport const compileTableSchema = <TableSchema extends Schema.Codec<any, any>>(\n schema: TableSchema,\n): TableSchemaToTableValidator<TableSchema> => {\n const ast = Schema.toEncoded(schema).ast;\n\n return pipe(\n ast,\n Match.value,\n Match.tag(\"Objects\", ({ indexSignatures }) =>\n Array.isReadonlyArrayEmpty(indexSignatures)\n ? (compileAst(ast) as Effect.Effect<any>)\n : Effect.fail(new IndexSignaturesAreNotSupportedError()),\n ),\n Match.tag(\"Union\", (unionAst) => compileAst(unionAst)),\n Match.orElse(() => Effect.fail(new TopLevelMustBeObjectOrUnionError())),\n Effect.runSync,\n );\n};\n\n// Compiler\n\nexport type ReadonlyValue =\n | string\n | number\n | bigint\n | boolean\n | ArrayBuffer\n | ReadonlyArrayValue\n | ReadonlyRecordValue\n | null;\n\ntype ReadonlyArrayValue = readonly ReadonlyValue[];\n\nexport type ReadonlyRecordValue = {\n readonly [key: string]: ReadonlyValue | undefined;\n};\n\ntype MutableValue<T> =\n T extends ReadonlyArray<infer El>\n ? MutableValue<El>[]\n : T extends ReadonlyRecordValue\n ? { -readonly [K in keyof T]: MutableValue<Exclude<T[K], undefined>> }\n : T;\n\nexport type ValueToValidator<Vl> = [Vl] extends [never]\n ? never\n : IsAny<Vl> extends true\n ? VAny\n : [Vl] extends [null]\n ? VNull\n : [Vl] extends [boolean]\n ? [boolean] extends [Vl]\n ? VBoolean\n : VLiteral<Vl>\n : IsUnion<Vl> extends true\n ? IsRecursive<Vl> extends true\n ? VAny\n : [Vl] extends [ReadonlyValue]\n ? UnionValueToValidator<Vl>\n : TypeError<\"Provided value is not a valid Convex value\", Vl>\n : [Vl] extends [number]\n ? [number] extends [Vl]\n ? VFloat64\n : VLiteral<Vl>\n : [Vl] extends [bigint]\n ? [bigint] extends [Vl]\n ? VInt64\n : VLiteral<Vl>\n : [Vl] extends [string]\n ? Vl extends {\n __tableName: infer TableName extends string;\n }\n ? VId<GenericId.GenericId<TableName>>\n : [string] extends [Vl]\n ? VString\n : VLiteral<Vl>\n : [Vl] extends [ArrayBuffer]\n ? VBytes\n : IsRecursive<Vl> extends true\n ? VAny\n : [Vl] extends [ReadonlyValue]\n ? Vl extends ReadonlyArray<ReadonlyValue>\n ? ArrayValueToValidator<Vl>\n : Vl extends ReadonlyRecordValue\n ? RecordValueToValidator<Vl>\n : TypeError<\"Unexpected value\", Vl>\n : TypeError<\n \"Provided value is not a valid Convex value\",\n Vl\n >;\n\ntype ArrayValueToValidator<Vl extends ReadonlyArray<ReadonlyValue>> =\n Vl extends ReadonlyArray<infer El extends ReadonlyValue>\n ? ValueToValidator<El> extends infer Vd extends Validator<any, any, any>\n ? VArray<MutableValue<El[]>, Vd>\n : never\n : never;\n\ntype RecordValueToValidator<Vl> = Vl extends ReadonlyRecordValue\n ? {\n -readonly [K in keyof Vl]-?: IsAny<Vl[K]> extends true\n ? IsOptional<Vl, K> extends true\n ? VOptional<VAny>\n : VAny\n : UndefinedOrValueToValidator<Vl[K]>;\n } extends infer VdRecord extends Record<string, any>\n ? MutableValue<Vl> extends infer VlRecord extends Record<string, any>\n ? IsRecord<VlRecord> extends true\n ? VRecord<VlRecord, VString, VdRecord[keyof VdRecord]>\n : VObject<VlRecord, VdRecord>\n : never\n : never\n : never;\n\nexport type UndefinedOrValueToValidator<Vl extends ReadonlyValue | undefined> =\n undefined extends Vl\n ? [Vl] extends [(infer Val extends ReadonlyValue) | undefined]\n ? ValueToValidator<Val> extends infer Vd extends Validator<\n any,\n \"required\",\n any\n >\n ? VOptional<Vd>\n : never\n : never\n : [Vl] extends [ReadonlyValue]\n ? ValueToValidator<Vl>\n : never;\n\ntype UnionValueToValidator<Vl extends ReadonlyValue> = [Vl] extends [\n ReadonlyValue,\n]\n ? IsUnion<Vl> extends true\n ? UnionToTuple<Vl> extends infer VlTuple extends\n ReadonlyArray<ReadonlyValue>\n ? ValueTupleToValidatorTuple<VlTuple> extends infer VdTuple extends\n Validator<any, \"required\", any>[]\n ? VUnion<MutableValue<Vl>, VdTuple>\n : TypeError<\"Failed to convert value tuple to validator tuple\">\n : TypeError<\"Failed to convert union to tuple\">\n : TypeError<\"Expected a union of values, but got a single value instead\">\n : TypeError<\"Provided value is not a valid Convex value\">;\n\ntype ValueTupleToValidatorTuple<VlTuple extends ReadonlyArray<ReadonlyValue>> =\n VlTuple extends\n | [true, false, ...infer VlRest extends ReadonlyArray<ReadonlyValue>]\n | [false, true, ...infer VlRest extends ReadonlyArray<ReadonlyValue>]\n ? ValueTupleToValidatorTuple<VlRest> extends infer VdRest extends Validator<\n any,\n any,\n any\n >[]\n ? [VBoolean<boolean>, ...VdRest]\n : never\n : VlTuple extends [\n infer Vl extends ReadonlyValue,\n ...infer VlRest extends ReadonlyArray<ReadonlyValue>,\n ]\n ? ValueToValidator<Vl> extends infer Vd extends Validator<any, any, any>\n ? ValueTupleToValidatorTuple<VlRest> extends infer VdRest extends\n Validator<any, \"required\", any>[]\n ? [Vd, ...VdRest]\n : never\n : never\n : [];\n\nexport const compileSchema = <T, E>(\n schema: Schema.Codec<T, E>,\n): ValueToValidator<(typeof schema)[\"Encoded\"]> =>\n Effect.runSync(compileAst(schema.ast)) as any;\n\nexport const isRecursive = (ast: SchemaAST.AST): boolean =>\n pipe(\n ast,\n Match.value,\n Match.tag(\n \"Literal\",\n \"Null\",\n \"Boolean\",\n \"String\",\n \"Number\",\n \"BigInt\",\n \"Unknown\",\n \"Any\",\n \"Declaration\",\n \"UniqueSymbol\",\n \"Symbol\",\n \"Undefined\",\n \"Void\",\n \"Never\",\n \"Enum\",\n \"TemplateLiteral\",\n \"ObjectKeyword\",\n () => false,\n ),\n Match.tag(\"Union\", ({ types }) =>\n Array.some(types, (type) => isRecursive(type)),\n ),\n Match.tag(\"Objects\", ({ propertySignatures }) =>\n Array.some(propertySignatures, ({ type }) => isRecursive(type)),\n ),\n Match.tag(\n \"Arrays\",\n ({ elements, rest }) =>\n Array.some(elements, (element) => isRecursive(element)) ||\n Array.some(rest, (element) => isRecursive(element)),\n ),\n Match.tag(\"Suspend\", () => true),\n Match.exhaustive,\n );\n\nexport const compileAst = (\n ast: SchemaAST.AST,\n isOptionalPropertyOfTypeLiteral = false,\n): Effect.Effect<\n Validator<any, any, any>,\n | UnsupportedSchemaTypeError\n | UnsupportedPropertySignatureKeyTypeError\n | IndexSignaturesAreNotSupportedError\n | MixedIndexAndPropertySignaturesAreNotSupportedError\n | OptionalTupleElementsAreNotSupportedError\n | EmptyTupleIsNotSupportedError\n | EmptyUnionIsNotSupportedError\n> =>\n isRecursive(ast)\n ? Effect.succeed(v.any())\n : pipe(\n ast,\n Match.value,\n Match.tag(\"Literal\", ({ literal }) =>\n pipe(\n literal,\n Match.value,\n Match.whenOr(\n Match.string,\n Match.number,\n Match.bigint,\n Match.boolean,\n (l) => v.literal(l),\n ),\n Match.exhaustive,\n Effect.succeed,\n ),\n ),\n Match.tag(\"Null\", () => Effect.succeed(v.null())),\n Match.tag(\"Boolean\", () => Effect.succeed(v.boolean())),\n Match.tag(\"String\", (stringAst) =>\n GenericId.tableName(stringAst).pipe(\n Option.match({\n onNone: () => Effect.succeed(v.string()),\n onSome: (tableName) => Effect.succeed(v.id(tableName)),\n }),\n ),\n ),\n Match.tag(\"Number\", () => Effect.succeed(v.float64())),\n Match.tag(\"BigInt\", () => Effect.succeed(v.int64())),\n Match.tag(\"Union\", (unionAst) =>\n handleUnion(unionAst, isOptionalPropertyOfTypeLiteral),\n ),\n Match.tag(\"Objects\", (objectsAst) => handleObjects(objectsAst)),\n Match.tag(\"Arrays\", (arraysAst) => handleArrays(arraysAst)),\n Match.tag(\"Unknown\", \"Any\", () => Effect.succeed(v.any())),\n Match.tag(\"Declaration\", (declaration) =>\n Effect.mapBoth(\n declaration.run(declaration.typeParameters)(\n new ArrayBuffer(0),\n declaration,\n {},\n ) as Effect.Effect<ArrayBuffer, unknown, never>,\n {\n onSuccess: () => v.bytes(),\n onFailure: () =>\n new UnsupportedSchemaTypeError({\n schemaType: declaration._tag,\n }),\n },\n ),\n ),\n Match.tag(\"Suspend\", () => Effect.succeed(v.any())),\n Match.tag(\n \"UniqueSymbol\",\n \"Symbol\",\n \"Undefined\",\n \"Void\",\n \"Never\",\n \"Enum\",\n \"TemplateLiteral\",\n \"ObjectKeyword\",\n () =>\n Effect.fail(\n new UnsupportedSchemaTypeError({\n schemaType: ast._tag,\n }),\n ),\n ),\n Match.exhaustive,\n );\n\nconst handleUnion = (\n { types }: SchemaAST.Union,\n isOptionalPropertyOfTypeLiteral: boolean,\n) =>\n Effect.gen(function* () {\n const members = isOptionalPropertyOfTypeLiteral\n ? Array.filter(types, Predicate.not(SchemaAST.isUndefined))\n : types;\n\n const [firstValidator, secondValidator, ...restValidators] =\n yield* Effect.all(Array.map(members, (type) => compileAst(type)));\n\n if (firstValidator === undefined) {\n return yield* new EmptyUnionIsNotSupportedError();\n } else if (secondValidator === undefined) {\n return firstValidator;\n } else {\n return v.union(firstValidator, secondValidator, ...restValidators);\n }\n });\n\nconst handleObjects = (objectsAst: SchemaAST.Objects) =>\n pipe(\n objectsAst.indexSignatures,\n Array.head,\n Option.match({\n onNone: () => Effect.map(handlePropertySignatures(objectsAst), v.object),\n onSome: ({ parameter, type }) =>\n pipe(\n objectsAst.propertySignatures,\n Array.head,\n Option.match({\n onNone: () =>\n Effect.map(\n Effect.all({\n parameter_: compileAst(parameter),\n type_: compileAst(type),\n }),\n ({ parameter_, type_ }) => v.record(parameter_, type_),\n ),\n onSome: () =>\n Effect.fail(\n new MixedIndexAndPropertySignaturesAreNotSupportedError(),\n ),\n }),\n ),\n }),\n );\n\nconst handleArrays = ({ elements, rest }: SchemaAST.Arrays) =>\n Effect.gen(function* () {\n const [f, s, ...r] = elements;\n\n const elementToValidator = (element: SchemaAST.AST) =>\n SchemaAST.isOptional(element)\n ? Effect.fail(new OptionalTupleElementsAreNotSupportedError())\n : compileAst(element);\n\n const arrayItemsValidator = yield* f === undefined\n ? pipe(\n rest,\n Array.head,\n Option.match({\n onNone: () => Effect.fail(new EmptyTupleIsNotSupportedError()),\n onSome: (type) => compileAst(type),\n }),\n )\n : s === undefined\n ? elementToValidator(f)\n : Effect.gen(function* () {\n const firstValidator = yield* elementToValidator(f);\n const secondValidator = yield* elementToValidator(s);\n const restValidators = yield* Effect.forEach(r, elementToValidator);\n\n return v.union(firstValidator, secondValidator, ...restValidators);\n });\n\n return v.array(arrayItemsValidator);\n });\n\nconst handlePropertySignatures = (objectsAst: SchemaAST.Objects) =>\n pipe(\n objectsAst.propertySignatures,\n Effect.forEach(({ type, name }) => {\n const isOptional = SchemaAST.isOptional(type);\n if (String.isString(name)) {\n // Somehow, somewhere, keys of type number are being coerced to strings…\n return Option.match(Number.parse(name), {\n onNone: () =>\n Effect.gen(function* () {\n const validator = yield* compileAst(type, isOptional);\n\n return {\n propertyName: name,\n validator: isOptional ? v.optional(validator) : validator,\n };\n }),\n onSome: (number) =>\n Effect.fail(\n new UnsupportedPropertySignatureKeyTypeError({\n propertyKey: number,\n }),\n ),\n });\n } else {\n return Effect.fail(\n new UnsupportedPropertySignatureKeyTypeError({ propertyKey: name }),\n );\n }\n }),\n Effect.andThen((propertyNamesWithValidators) =>\n pipe(\n propertyNamesWithValidators,\n Array.reduce(\n {} as Record<string, Validator<any, any, any>>,\n (acc, { propertyName, validator }) => ({\n [propertyName]: validator,\n ...acc,\n }),\n ),\n Effect.succeed,\n ),\n ),\n );\n\n// Errors\n\nexport class TopLevelMustBeObjectError extends Data.TaggedError(\n \"TopLevelMustBeObjectError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Top level schema must be an object\";\n }\n /* v8 ignore stop */\n}\n\nexport class TopLevelMustBeObjectOrUnionError extends Data.TaggedError(\n \"TopLevelMustBeObjectOrUnionError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Top level schema must be an object or a union\";\n }\n /* v8 ignore stop */\n}\n\nexport class UnsupportedPropertySignatureKeyTypeError extends Data.TaggedError(\n \"UnsupportedPropertySignatureKeyTypeError\",\n)<{\n readonly propertyKey: number | symbol;\n}> {\n /* v8 ignore start */\n override get message() {\n return `Unsupported property signature '${this.propertyKey.toString()}'. Property is of type '${typeof this.propertyKey}' but only 'string' properties are supported.`;\n }\n /* v8 ignore stop */\n}\n\nexport class EmptyTupleIsNotSupportedError extends Data.TaggedError(\n \"EmptyTupleIsNotSupportedError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Tuple must have at least one element\";\n }\n /* v8 ignore stop */\n}\n\nexport class EmptyUnionIsNotSupportedError extends Data.TaggedError(\n \"EmptyUnionIsNotSupportedError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Union must have at least one member that compiles to a validator\";\n }\n /* v8 ignore stop */\n}\n\nexport class UnsupportedSchemaTypeError extends Data.TaggedError(\n \"UnsupportedSchemaTypeError\",\n)<{\n readonly schemaType: SchemaAST.AST[\"_tag\"];\n}> {\n /* v8 ignore start */\n override get message() {\n return `Unsupported schema type '${this.schemaType}'`;\n }\n /* v8 ignore stop */\n}\n\nexport class IndexSignaturesAreNotSupportedError extends Data.TaggedError(\n \"IndexSignaturesAreNotSupportedError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Index signatures are not supported\";\n }\n /* v8 ignore stop */\n}\n\nexport class MixedIndexAndPropertySignaturesAreNotSupportedError extends Data.TaggedError(\n \"MixedIndexAndPropertySignaturesAreNotSupportedError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Mixed index and property signatures are not supported\";\n }\n /* v8 ignore stop */\n}\n\nexport class OptionalTupleElementsAreNotSupportedError extends Data.TaggedError(\n \"OptionalTupleElementsAreNotSupportedError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Optional tuple elements are not supported\";\n }\n /* v8 ignore stop */\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAa,qBACX,eACuB;CACvB,MAAM,MAAM,OAAO,UAAU,UAAU,CAAC,CAAC;CAEzC,OAAO,KACL,KACA,MAAM,OACN,MAAM,IAAI,YAAY,eACpB,MAAM,qBAAqB,WAAW,eAAe,IACjD,yBAAyB,UAAU,IACnC,OAAO,KAAK,IAAI,oCAAoC,CAAC,CAC3D,GACA,MAAM,aAAa,OAAO,KAAK,IAAI,0BAA0B,CAAC,CAAC,GAC/D,OAAO,OACT;AACF;AAIA,MAAa,wBACX,WAEA,OAAO,QAAQ,WAAW,OAAO,UAAU,MAAM,CAAC,CAAC,GAAG,CAAC;AAgBzD,MAAa,sBACX,WAC6C;CAC7C,MAAM,MAAM,OAAO,UAAU,MAAM,CAAC,CAAC;CAErC,OAAO,KACL,KACA,MAAM,OACN,MAAM,IAAI,YAAY,EAAE,sBACtB,MAAM,qBAAqB,eAAe,IACrC,WAAW,GAAG,IACf,OAAO,KAAK,IAAI,oCAAoC,CAAC,CAC3D,GACA,MAAM,IAAI,UAAU,aAAa,WAAW,QAAQ,CAAC,GACrD,MAAM,aAAa,OAAO,KAAK,IAAI,iCAAiC,CAAC,CAAC,GACtE,OAAO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qDACF,CAAC,CAAC;;CAEA,IAAa,UAAU;EACrB,OAAO;CACT;AAEF;AAEA,IAAa,4CAAb,cAA+D,KAAK,YAClE,2CACF,CAAC,CAAC;;CAEA,IAAa,UAAU;EACrB,OAAO;CACT;AAEF"}
|
|
1
|
+
{"version":3,"file":"SchemaToValidator.js","names":["GenericId.tableName"],"sources":["../src/SchemaToValidator.ts"],"sourcesContent":["import type {\n PropertyValidators,\n Validator,\n VAny,\n VArray,\n VBoolean,\n VBytes,\n VFloat64,\n VId,\n VInt64,\n VLiteral,\n VNull,\n VObject,\n VOptional,\n VRecord,\n VString,\n VUnion,\n} from \"convex/values\";\nimport { v } from \"convex/values\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\nimport * as Match from \"effect/Match\";\nimport * as Number from \"effect/Number\";\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaAST from \"effect/SchemaAST\";\nimport * as String from \"effect/String\";\n\nimport * as GenericId from \"./GenericId\";\nimport type {\n IsAny,\n IsOptional,\n IsRecord,\n IsRecursive,\n IsUnion,\n TypeError,\n UnionToTuple,\n} from \"./Types\";\n\n// Args\n\nexport const compileArgsSchema = <ConfectValue, ConvexValue>(\n argsSchema: Schema.Codec<ConfectValue, ConvexValue>,\n): PropertyValidators => {\n const ast = Schema.toEncoded(argsSchema).ast;\n\n return pipe(\n ast,\n Match.value,\n Match.tag(\"Objects\", (objectsAst) =>\n Array.isReadonlyArrayEmpty(objectsAst.indexSignatures)\n ? handlePropertySignatures(objectsAst)\n : Effect.fail(new IndexSignaturesAreNotSupportedError()),\n ),\n Match.orElse(() => Effect.fail(new TopLevelMustBeObjectError())),\n Effect.runSync,\n );\n};\n\n// Returns\n\nexport const compileReturnsSchema = <ConfectValue, ConvexValue>(\n schema: Schema.Codec<ConfectValue, ConvexValue>,\n): Validator<any, any, any> =>\n Effect.runSync(compileAst(Schema.toEncoded(schema).ast));\n\n// Table\n\n/**\n * Convert a table `Schema` to a table `Validator`.\n */\nexport type TableSchemaToTableValidator<\n TableSchema extends Schema.Codec<any, any>,\n> =\n ValueToValidator<TableSchema[\"Encoded\"]> extends infer Vd extends\n | VObject<any, any, any, any>\n | VUnion<any, any, any, any>\n ? Vd\n : never;\n\nexport const compileTableSchema = <TableSchema extends Schema.Codec<any, any>>(\n schema: TableSchema,\n): TableSchemaToTableValidator<TableSchema> => {\n const ast = Schema.toEncoded(schema).ast;\n\n return pipe(\n ast,\n Match.value,\n Match.tag(\"Objects\", ({ indexSignatures }) =>\n Array.isReadonlyArrayEmpty(indexSignatures)\n ? // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- The return type is derived from the input schema and cannot be recovered from the runtime AST.\n (compileAst(ast) as Effect.Effect<any>)\n : Effect.fail(new IndexSignaturesAreNotSupportedError()),\n ),\n Match.tag(\"Union\", (unionAst) => compileAst(unionAst)),\n Match.orElse(() => Effect.fail(new TopLevelMustBeObjectOrUnionError())),\n Effect.runSync,\n );\n};\n\n// Compiler\n\nexport type ReadonlyValue =\n | string\n | number\n | bigint\n | boolean\n | ArrayBuffer\n | ReadonlyArrayValue\n | ReadonlyRecordValue\n | null;\n\ntype ReadonlyArrayValue = readonly ReadonlyValue[];\n\nexport type ReadonlyRecordValue = {\n readonly [key: string]: ReadonlyValue | undefined;\n};\n\ntype MutableValue<T> =\n T extends ReadonlyArray<infer El>\n ? MutableValue<El>[]\n : T extends ReadonlyRecordValue\n ? { -readonly [K in keyof T]: MutableValue<Exclude<T[K], undefined>> }\n : T;\n\nexport type ValueToValidator<Vl> = [Vl] extends [never]\n ? never\n : IsAny<Vl> extends true\n ? VAny\n : [Vl] extends [null]\n ? VNull\n : [Vl] extends [boolean]\n ? [boolean] extends [Vl]\n ? VBoolean\n : VLiteral<Vl>\n : IsUnion<Vl> extends true\n ? IsRecursive<Vl> extends true\n ? VAny\n : [Vl] extends [ReadonlyValue]\n ? UnionValueToValidator<Vl>\n : TypeError<\"Provided value is not a valid Convex value\", Vl>\n : [Vl] extends [number]\n ? [number] extends [Vl]\n ? VFloat64\n : VLiteral<Vl>\n : [Vl] extends [bigint]\n ? [bigint] extends [Vl]\n ? VInt64\n : VLiteral<Vl>\n : [Vl] extends [string]\n ? Vl extends {\n __tableName: infer TableName extends string;\n }\n ? VId<GenericId.GenericId<TableName>>\n : [string] extends [Vl]\n ? VString\n : VLiteral<Vl>\n : [Vl] extends [ArrayBuffer]\n ? VBytes\n : IsRecursive<Vl> extends true\n ? VAny\n : [Vl] extends [ReadonlyValue]\n ? Vl extends ReadonlyArray<ReadonlyValue>\n ? ArrayValueToValidator<Vl>\n : Vl extends ReadonlyRecordValue\n ? RecordValueToValidator<Vl>\n : TypeError<\"Unexpected value\", Vl>\n : TypeError<\n \"Provided value is not a valid Convex value\",\n Vl\n >;\n\ntype ArrayValueToValidator<Vl extends ReadonlyArray<ReadonlyValue>> =\n Vl extends ReadonlyArray<infer El extends ReadonlyValue>\n ? ValueToValidator<El> extends infer Vd extends Validator<any, any, any>\n ? VArray<MutableValue<El[]>, Vd>\n : never\n : never;\n\ntype RecordValueToValidator<Vl> = Vl extends ReadonlyRecordValue\n ? {\n -readonly [K in keyof Vl]-?: IsAny<Vl[K]> extends true\n ? IsOptional<Vl, K> extends true\n ? VOptional<VAny>\n : VAny\n : UndefinedOrValueToValidator<Vl[K]>;\n } extends infer VdRecord extends Record<string, any>\n ? MutableValue<Vl> extends infer VlRecord extends Record<string, any>\n ? IsRecord<VlRecord> extends true\n ? VRecord<VlRecord, VString, VdRecord[keyof VdRecord]>\n : VObject<VlRecord, VdRecord>\n : never\n : never\n : never;\n\nexport type UndefinedOrValueToValidator<Vl extends ReadonlyValue | undefined> =\n undefined extends Vl\n ? [Vl] extends [(infer Val extends ReadonlyValue) | undefined]\n ? ValueToValidator<Val> extends infer Vd extends Validator<\n any,\n \"required\",\n any\n >\n ? VOptional<Vd>\n : never\n : never\n : [Vl] extends [ReadonlyValue]\n ? ValueToValidator<Vl>\n : never;\n\ntype UnionValueToValidator<Vl extends ReadonlyValue> = [Vl] extends [\n ReadonlyValue,\n]\n ? IsUnion<Vl> extends true\n ? UnionToTuple<Vl> extends infer VlTuple extends\n ReadonlyArray<ReadonlyValue>\n ? ValueTupleToValidatorTuple<VlTuple> extends infer VdTuple extends\n Validator<any, \"required\", any>[]\n ? VUnion<MutableValue<Vl>, VdTuple>\n : TypeError<\"Failed to convert value tuple to validator tuple\">\n : TypeError<\"Failed to convert union to tuple\">\n : TypeError<\"Expected a union of values, but got a single value instead\">\n : TypeError<\"Provided value is not a valid Convex value\">;\n\ntype ValueTupleToValidatorTuple<VlTuple extends ReadonlyArray<ReadonlyValue>> =\n VlTuple extends\n | [true, false, ...infer VlRest extends ReadonlyArray<ReadonlyValue>]\n | [false, true, ...infer VlRest extends ReadonlyArray<ReadonlyValue>]\n ? ValueTupleToValidatorTuple<VlRest> extends infer VdRest extends Validator<\n any,\n any,\n any\n >[]\n ? [VBoolean<boolean>, ...VdRest]\n : never\n : VlTuple extends [\n infer Vl extends ReadonlyValue,\n ...infer VlRest extends ReadonlyArray<ReadonlyValue>,\n ]\n ? ValueToValidator<Vl> extends infer Vd extends Validator<any, any, any>\n ? ValueTupleToValidatorTuple<VlRest> extends infer VdRest extends\n Validator<any, \"required\", any>[]\n ? [Vd, ...VdRest]\n : never\n : never\n : [];\n\nexport const compileSchema = <T, E>(\n schema: Schema.Codec<T, E>,\n): ValueToValidator<(typeof schema)[\"Encoded\"]> =>\n Effect.runSync(compileAst(schema.ast)) as any;\n\nexport const isRecursive = (ast: SchemaAST.AST): boolean =>\n pipe(\n ast,\n Match.value,\n Match.tag(\n \"Literal\",\n \"Null\",\n \"Boolean\",\n \"String\",\n \"Number\",\n \"BigInt\",\n \"Unknown\",\n \"Any\",\n \"Declaration\",\n \"UniqueSymbol\",\n \"Symbol\",\n \"Undefined\",\n \"Void\",\n \"Never\",\n \"Enum\",\n \"TemplateLiteral\",\n \"ObjectKeyword\",\n () => false,\n ),\n Match.tag(\"Union\", ({ types }) =>\n Array.some(types, (type) => isRecursive(type)),\n ),\n Match.tag(\"Objects\", ({ propertySignatures }) =>\n Array.some(propertySignatures, ({ type }) => isRecursive(type)),\n ),\n Match.tag(\n \"Arrays\",\n ({ elements, rest }) =>\n Array.some(elements, (element) => isRecursive(element)) ||\n Array.some(rest, (element) => isRecursive(element)),\n ),\n Match.tag(\"Suspend\", () => true),\n Match.exhaustive,\n );\n\nexport const compileAst = (\n ast: SchemaAST.AST,\n isOptionalPropertyOfTypeLiteral = false,\n): Effect.Effect<\n Validator<any, any, any>,\n | UnsupportedSchemaTypeError\n | UnsupportedPropertySignatureKeyTypeError\n | IndexSignaturesAreNotSupportedError\n | MixedIndexAndPropertySignaturesAreNotSupportedError\n | OptionalTupleElementsAreNotSupportedError\n | EmptyTupleIsNotSupportedError\n | EmptyUnionIsNotSupportedError\n> =>\n isRecursive(ast)\n ? Effect.succeed(v.any())\n : pipe(\n ast,\n Match.value,\n Match.tag(\"Literal\", ({ literal }) =>\n pipe(\n literal,\n Match.value,\n Match.whenOr(\n Match.string,\n Match.number,\n Match.bigint,\n Match.boolean,\n (l) => v.literal(l),\n ),\n Match.exhaustive,\n Effect.succeed,\n ),\n ),\n Match.tag(\"Null\", () => Effect.succeed(v.null())),\n Match.tag(\"Boolean\", () => Effect.succeed(v.boolean())),\n Match.tag(\"String\", (stringAst) =>\n GenericId.tableName(stringAst).pipe(\n Option.match({\n onNone: () => Effect.succeed(v.string()),\n onSome: (tableName) => Effect.succeed(v.id(tableName)),\n }),\n ),\n ),\n Match.tag(\"Number\", () => Effect.succeed(v.float64())),\n Match.tag(\"BigInt\", () => Effect.succeed(v.int64())),\n Match.tag(\"Union\", (unionAst) =>\n handleUnion(unionAst, isOptionalPropertyOfTypeLiteral),\n ),\n Match.tag(\"Objects\", (objectsAst) => handleObjects(objectsAst)),\n Match.tag(\"Arrays\", (arraysAst) => handleArrays(arraysAst)),\n Match.tag(\"Unknown\", \"Any\", () => Effect.succeed(v.any())),\n Match.tag(\"Declaration\", (declaration) =>\n Effect.mapBoth(\n // oxlint-disable-next-line effecttsgo/any-unknown-in-error-context -- Codec inputs are context-free, but Effect's SchemaAST.DeclarationRun erases their requirements to `any`.\n declaration.run(declaration.typeParameters)(\n new ArrayBuffer(0),\n declaration,\n {},\n ) as Effect.Effect<ArrayBuffer, unknown, never>,\n {\n onSuccess: () => v.bytes(),\n onFailure: () =>\n new UnsupportedSchemaTypeError({\n schemaType: declaration._tag,\n }),\n },\n ),\n ),\n Match.tag(\"Suspend\", () => Effect.succeed(v.any())),\n Match.tag(\n \"UniqueSymbol\",\n \"Symbol\",\n \"Undefined\",\n \"Void\",\n \"Never\",\n \"Enum\",\n \"TemplateLiteral\",\n \"ObjectKeyword\",\n () =>\n Effect.fail(\n new UnsupportedSchemaTypeError({\n schemaType: ast._tag,\n }),\n ),\n ),\n Match.exhaustive,\n );\n\nconst handleUnion = (\n { types }: SchemaAST.Union,\n isOptionalPropertyOfTypeLiteral: boolean,\n) => handleUnionTypes(types, isOptionalPropertyOfTypeLiteral);\n\nconst handleUnionTypes = Effect.fnUntraced(function* (\n types: SchemaAST.Union[\"types\"],\n isOptionalPropertyOfTypeLiteral: boolean,\n) {\n const members = isOptionalPropertyOfTypeLiteral\n ? Array.filter(types, Predicate.not(SchemaAST.isUndefined))\n : types;\n\n const [firstValidator, secondValidator, ...restValidators] =\n yield* Effect.all(Array.map(members, (type) => compileAst(type)));\n\n if (firstValidator === undefined) {\n return yield* new EmptyUnionIsNotSupportedError();\n } else if (secondValidator === undefined) {\n return firstValidator;\n } else {\n return v.union(firstValidator, secondValidator, ...restValidators);\n }\n});\n\nconst handleObjects = (objectsAst: SchemaAST.Objects) =>\n pipe(\n objectsAst.indexSignatures,\n Array.head,\n Option.match({\n onNone: () => Effect.map(handlePropertySignatures(objectsAst), v.object),\n onSome: ({ parameter, type }) =>\n pipe(\n objectsAst.propertySignatures,\n Array.head,\n Option.match({\n onNone: () =>\n Effect.map(\n Effect.all({\n parameter_: compileAst(parameter),\n type_: compileAst(type),\n }),\n ({ parameter_, type_ }) => v.record(parameter_, type_),\n ),\n onSome: () =>\n Effect.fail(\n new MixedIndexAndPropertySignaturesAreNotSupportedError(),\n ),\n }),\n ),\n }),\n );\n\nconst handleArrays = ({ elements, rest }: SchemaAST.Arrays) =>\n handleArrayElements(elements, rest);\n\nconst handleArrayElements = Effect.fnUntraced(function* (\n elements: SchemaAST.Arrays[\"elements\"],\n rest: SchemaAST.Arrays[\"rest\"],\n) {\n const [f, s, ...r] = elements;\n\n const elementToValidator = (element: SchemaAST.AST) =>\n SchemaAST.isOptional(element)\n ? Effect.fail(new OptionalTupleElementsAreNotSupportedError())\n : compileAst(element);\n\n const arrayItemsValidator = yield* f === undefined\n ? pipe(\n rest,\n Array.head,\n Option.match({\n onNone: () => Effect.fail(new EmptyTupleIsNotSupportedError()),\n onSome: (type) => compileAst(type),\n }),\n )\n : s === undefined\n ? elementToValidator(f)\n : Effect.gen(function* () {\n const firstValidator = yield* elementToValidator(f);\n const secondValidator = yield* elementToValidator(s);\n const restValidators = yield* Effect.forEach(r, elementToValidator);\n\n return v.union(firstValidator, secondValidator, ...restValidators);\n });\n\n return v.array(arrayItemsValidator);\n});\n\nconst handlePropertySignatures = (objectsAst: SchemaAST.Objects) =>\n pipe(\n objectsAst.propertySignatures,\n Effect.forEach(({ type, name }) => {\n const isOptional = SchemaAST.isOptional(type);\n if (String.isString(name)) {\n // Somehow, somewhere, keys of type number are being coerced to strings…\n return Option.match(Number.parse(name), {\n onNone: () =>\n Effect.gen(function* () {\n const validator = yield* compileAst(type, isOptional);\n\n return {\n propertyName: name,\n validator: isOptional ? v.optional(validator) : validator,\n };\n }),\n onSome: (number) =>\n Effect.fail(\n new UnsupportedPropertySignatureKeyTypeError({\n propertyKey: number,\n }),\n ),\n });\n } else {\n return Effect.fail(\n new UnsupportedPropertySignatureKeyTypeError({ propertyKey: name }),\n );\n }\n }),\n Effect.andThen((propertyNamesWithValidators) =>\n pipe(\n propertyNamesWithValidators,\n Array.reduce(\n {} as Record<string, Validator<any, any, any>>,\n (acc, { propertyName, validator }) => ({\n [propertyName]: validator,\n ...acc,\n }),\n ),\n Effect.succeed,\n ),\n ),\n );\n\n// Errors\n\nexport class TopLevelMustBeObjectError extends Data.TaggedError(\n \"TopLevelMustBeObjectError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Top level schema must be an object\";\n }\n /* v8 ignore stop */\n}\n\nexport class TopLevelMustBeObjectOrUnionError extends Data.TaggedError(\n \"TopLevelMustBeObjectOrUnionError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Top level schema must be an object or a union\";\n }\n /* v8 ignore stop */\n}\n\nexport class UnsupportedPropertySignatureKeyTypeError extends Data.TaggedError(\n \"UnsupportedPropertySignatureKeyTypeError\",\n)<{\n readonly propertyKey: number | symbol;\n}> {\n /* v8 ignore start */\n override get message() {\n return `Unsupported property signature '${this.propertyKey.toString()}'. Property is of type '${typeof this.propertyKey}' but only 'string' properties are supported.`;\n }\n /* v8 ignore stop */\n}\n\nexport class EmptyTupleIsNotSupportedError extends Data.TaggedError(\n \"EmptyTupleIsNotSupportedError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Tuple must have at least one element\";\n }\n /* v8 ignore stop */\n}\n\nexport class EmptyUnionIsNotSupportedError extends Data.TaggedError(\n \"EmptyUnionIsNotSupportedError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Union must have at least one member that compiles to a validator\";\n }\n /* v8 ignore stop */\n}\n\nexport class UnsupportedSchemaTypeError extends Data.TaggedError(\n \"UnsupportedSchemaTypeError\",\n)<{\n readonly schemaType: SchemaAST.AST[\"_tag\"];\n}> {\n /* v8 ignore start */\n override get message() {\n return `Unsupported schema type '${this.schemaType}'`;\n }\n /* v8 ignore stop */\n}\n\nexport class IndexSignaturesAreNotSupportedError extends Data.TaggedError(\n \"IndexSignaturesAreNotSupportedError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Index signatures are not supported\";\n }\n /* v8 ignore stop */\n}\n\nexport class MixedIndexAndPropertySignaturesAreNotSupportedError extends Data.TaggedError(\n \"MixedIndexAndPropertySignaturesAreNotSupportedError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Mixed index and property signatures are not supported\";\n }\n /* v8 ignore stop */\n}\n\nexport class OptionalTupleElementsAreNotSupportedError extends Data.TaggedError(\n \"OptionalTupleElementsAreNotSupportedError\",\n) {\n /* v8 ignore start */\n override get message() {\n return \"Optional tuple elements are not supported\";\n }\n /* v8 ignore stop */\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAa,qBACX,eACuB;CACvB,MAAM,MAAM,OAAO,UAAU,UAAU,CAAC,CAAC;CAEzC,OAAO,KACL,KACA,MAAM,OACN,MAAM,IAAI,YAAY,eACpB,MAAM,qBAAqB,WAAW,eAAe,IACjD,yBAAyB,UAAU,IACnC,OAAO,KAAK,IAAI,oCAAoC,CAAC,CAC3D,GACA,MAAM,aAAa,OAAO,KAAK,IAAI,0BAA0B,CAAC,CAAC,GAC/D,OAAO,OACT;AACF;AAIA,MAAa,wBACX,WAEA,OAAO,QAAQ,WAAW,OAAO,UAAU,MAAM,CAAC,CAAC,GAAG,CAAC;AAgBzD,MAAa,sBACX,WAC6C;CAC7C,MAAM,MAAM,OAAO,UAAU,MAAM,CAAC,CAAC;CAErC,OAAO,KACL,KACA,MAAM,OACN,MAAM,IAAI,YAAY,EAAE,sBACtB,MAAM,qBAAqB,eAAe,IAErC,WAAW,GAAG,IACf,OAAO,KAAK,IAAI,oCAAoC,CAAC,CAC3D,GACA,MAAM,IAAI,UAAU,aAAa,WAAW,QAAQ,CAAC,GACrD,MAAM,aAAa,OAAO,KAAK,IAAI,iCAAiC,CAAC,CAAC,GACtE,OAAO,OACT;AACF;AAqJA,MAAa,iBACX,WAEA,OAAO,QAAQ,W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O;CACT;AAEF;AAEA,IAAa,sDAAb,cAAyE,KAAK,YAC5E,qDACF,CAAC,CAAC;;CAEA,IAAa,UAAU;EACrB,OAAO;CACT;AAEF;AAEA,IAAa,4CAAb,cAA+D,KAAK,YAClE,2CACF,CAAC,CAAC;;CAEA,IAAa,UAAU;EACrB,OAAO;CACT;AAEF"}
|
package/dist/Spec.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export type TypeId = typeof TypeId;
|
|
|
4
4
|
export declare const isSpec: (u: unknown) => u is AnyWithProps;
|
|
5
5
|
/**
|
|
6
6
|
* A Confect spec: a flat container of function groups. Groups may be of any
|
|
7
|
-
* runtime
|
|
7
|
+
* runtime—a group built with `GroupSpec.makeNode()` (a Node action group) sits
|
|
8
8
|
* alongside `GroupSpec.make()` groups in the same namespace. The runtime of a
|
|
9
9
|
* group lives on the group itself (`GroupSpec.runtime`) and on each function's
|
|
10
10
|
* `RuntimeAndFunctionType`; the spec does not carry a runtime of its own.
|
package/dist/Spec.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Spec.js","names":["GroupSpec.withName"],"sources":["../src/Spec.ts"],"sourcesContent":["import * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\nimport * as GroupSpec from \"./GroupSpec\";\n\nexport const TypeId = \"~@confect/core/Spec\";\nexport type TypeId = typeof TypeId;\n\nexport const isSpec = (u: unknown): u is AnyWithProps =>\n Predicate.hasProperty(u, TypeId);\n\n/**\n * A Confect spec: a flat container of function groups. Groups may be of any\n * runtime
|
|
1
|
+
{"version":3,"file":"Spec.js","names":["GroupSpec.withName"],"sources":["../src/Spec.ts"],"sourcesContent":["import * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\nimport * as GroupSpec from \"./GroupSpec\";\n\nexport const TypeId = \"~@confect/core/Spec\";\nexport type TypeId = typeof TypeId;\n\nexport const isSpec = (u: unknown): u is AnyWithProps =>\n Predicate.hasProperty(u, TypeId);\n\n/**\n * A Confect spec: a flat container of function groups. Groups may be of any\n * runtime—a group built with `GroupSpec.makeNode()` (a Node action group) sits\n * alongside `GroupSpec.make()` groups in the same namespace. The runtime of a\n * group lives on the group itself (`GroupSpec.runtime`) and on each function's\n * `RuntimeAndFunctionType`; the spec does not carry a runtime of its own.\n */\nexport interface Spec<Groups_ extends GroupSpec.AnyWithProps = never> {\n readonly [TypeId]: TypeId;\n readonly groups: {\n [GroupName in GroupSpec.Name<Groups_>]: GroupSpec.WithName<\n Groups_,\n GroupName\n >;\n };\n readonly \"~Groups\": Groups_;\n\n add<Group extends GroupSpec.AnyWithProps>(\n group: Group,\n ): Spec<Groups_ | Group>;\n\n addAt<const Name extends string, Group extends GroupSpec.AnyWithProps>(\n name: Name,\n group: Group,\n ): Spec<Groups_ | GroupSpec.NamedAt<Group, Name>>;\n}\n\nexport interface Any {\n readonly [TypeId]: TypeId;\n}\n\nexport interface AnyWithProps extends Spec<GroupSpec.AnyWithProps> {}\n\nexport type Groups<Spec_ extends AnyWithProps> = Spec_[\"~Groups\"];\n\nconst Proto = {\n [TypeId]: TypeId,\n\n add<Group extends GroupSpec.AnyWithProps>(this: AnyWithProps, group: Group) {\n return makeProto({\n groups: Record.set(this.groups, group.name, group),\n });\n },\n\n addAt<Group extends GroupSpec.AnyWithProps>(\n this: AnyWithProps,\n name: string,\n group: Group,\n ) {\n return makeProto({\n groups: Record.set(this.groups, name, GroupSpec.withName(name, group)),\n });\n },\n};\n\nconst makeProto = <Groups_ extends GroupSpec.AnyWithProps>({\n groups,\n}: {\n groups: Record.ReadonlyRecord<string, Groups_>;\n}): Spec<Groups_> =>\n Object.assign(Object.create(Proto), {\n groups,\n }) as Spec<Groups_>;\n\nexport const make = (): Spec => makeProto({ groups: {} });\n"],"mappings":";;;;;;;;;;AAIA,MAAa,SAAS;AAGtB,MAAa,UAAU,MACrB,UAAU,YAAY,GAAG,MAAM;AAqCjC,MAAM,QAAQ;EACX,SAAS;CAEV,IAA8D,OAAc;EAC1E,OAAO,UAAU,EACf,QAAQ,OAAO,IAAI,KAAK,QAAQ,MAAM,MAAM,KAAK,EACnD,CAAC;CACH;CAEA,MAEE,MACA,OACA;EACA,OAAO,UAAU,EACf,QAAQ,OAAO,IAAI,KAAK,QAAQ,MAAMA,SAAmB,MAAM,KAAK,CAAC,EACvE,CAAC;CACH;AACF;AAEA,MAAM,aAAqD,EACzD,aAIA,OAAO,OAAO,OAAO,OAAO,KAAK,GAAG,EAClC,OACF,CAAC;AAEH,MAAa,aAAmB,UAAU,EAAE,QAAQ,CAAC,EAAE,CAAC"}
|
package/dist/SystemFields.d.ts
CHANGED
|
@@ -18,9 +18,8 @@ type SystemFieldsFor<TableName extends string> = ReturnType<typeof SystemFields<
|
|
|
18
18
|
*
|
|
19
19
|
* A plain `Struct` gains the fields via `Schema.fieldsAssign` and a `Union`
|
|
20
20
|
* has them distributed across its members, preserving the schema's
|
|
21
|
-
* `Struct`/`Union` structure. Any other object-shaped schema
|
|
22
|
-
* `Schema.decodeTo`/`Schema.encodeKeys`, a branded struct, a suspended schema
|
|
23
|
-
* — is extended at the AST level: every object node in its encoding chain
|
|
21
|
+
* `Struct`/`Union` structure. Any other object-shaped schema—one built with
|
|
22
|
+
* `Schema.decodeTo`/`Schema.encodeKeys`, a branded struct, a suspended schema—is extended at the AST level: every object node in its encoding chain
|
|
24
23
|
* gains the system fields, and each transformation is wrapped so the fields
|
|
25
24
|
* bypass the user-defined getters. Schemas that do not resolve to an object
|
|
26
25
|
* shape at every step (such as `Schema.Class`, whose decoded values are class
|
|
@@ -53,7 +52,7 @@ export type ExtendWithSystemFields<TableName extends string, TableSchema extends
|
|
|
53
52
|
}>>> : ApplySystemFields<TableName, TableSchema>;
|
|
54
53
|
/**
|
|
55
54
|
* The decoded/encoded document shape: a table's fields plus Convex's system
|
|
56
|
-
* fields. Deliberately a bare intersection (no `Expand`/`Simplify`)
|
|
55
|
+
* fields. Deliberately a bare intersection (no `Expand`/`Simplify`)—flattening
|
|
57
56
|
* it with a homomorphic mapped type collapses to `{ [x: string]: any }` when
|
|
58
57
|
* `Document` is still an unresolved generic, which breaks structural
|
|
59
58
|
* comparability in the database reader/writer plumbing.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SystemFields.d.ts","sourceRoot":"","sources":["../src/SystemFields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,IAAI,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAOhF,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAIxC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAGxC;;GAEG;AACH,eAAO,MAAM,YAAY,GAAI,SAAS,SAAS,MAAM,aAAa,SAAS;;;EAIvE,CAAC;AAEL;;;GAGG;AACH,KAAK,eAAe,CAAC,SAAS,SAAS,MAAM,IAAI,UAAU,CACzD,OAAO,YAAY,CAAC,SAAS,CAAC,CAC/B,CAAC,QAAQ,CAAC,CAAC;AA4HZ
|
|
1
|
+
{"version":3,"file":"SystemFields.d.ts","sourceRoot":"","sources":["../src/SystemFields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,IAAI,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAOhF,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAIxC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAGxC;;GAEG;AACH,eAAO,MAAM,YAAY,GAAI,SAAS,SAAS,MAAM,aAAa,SAAS;;;EAIvE,CAAC;AAEL;;;GAGG;AACH,KAAK,eAAe,CAAC,SAAS,SAAS,MAAM,IAAI,UAAU,CACzD,OAAO,YAAY,CAAC,SAAS,CAAC,CAC/B,CAAC,QAAQ,CAAC,CAAC;AA4HZ;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,sBAAsB,GACjC,SAAS,SAAS,MAAM,EACxB,WAAW,SAAS,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,GAAG,CAA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Fields.js
CHANGED
|
@@ -54,13 +54,13 @@ const wrapTransformation = (transformation) => {
|
|
|
54
54
|
};
|
|
55
55
|
/**
|
|
56
56
|
* Builds an AST walker that adds the given system-field property signatures to
|
|
57
|
-
* every object node of a schema's AST
|
|
58
|
-
* chain
|
|
57
|
+
* every object node of a schema's AST—including each step of its encoding
|
|
58
|
+
* chain—wrapping transformations so the fields survive them.
|
|
59
59
|
*/
|
|
60
60
|
const makeExtendAst = (systemPropertySignatures) => {
|
|
61
61
|
const extendEncoding = (encoding) => Array.map(encoding, (link) => new SchemaAST.Link(extendAst(link.to), wrapTransformation(link.transformation)));
|
|
62
62
|
const extendAst = (ast) => {
|
|
63
|
-
if (SchemaAST.isUnion(ast)) return new SchemaAST.Union(Array.map(ast.types, extendAst), ast.
|
|
63
|
+
if (SchemaAST.isUnion(ast)) return new SchemaAST.Union(Array.map(ast.types, extendAst), ast.options, ast.annotations, ast.checks, ast.encoding === void 0 ? void 0 : extendEncoding(ast.encoding), ast.context, ast.encodingChecks);
|
|
64
64
|
if (SchemaAST.isSuspend(ast)) return new SchemaAST.Suspend(() => extendAst(ast.thunk()), ast.annotations, void 0, ast.encoding === void 0 ? void 0 : extendEncoding(ast.encoding), ast.context);
|
|
65
65
|
if (SchemaAST.isObjects(ast)) return new SchemaAST.Objects(Array.appendAll(ast.propertySignatures, systemPropertySignatures), ast.indexSignatures, ast.annotations, ast.checks, ast.encoding === void 0 ? void 0 : extendEncoding(ast.encoding), ast.context, ast.encodingChecks);
|
|
66
66
|
throw new Error(ast._tag === "Declaration" ? "Cannot extend a `Declaration` schema (such as a `Schema.Class`) with system fields: its decoded values are constructed instances, which cannot gain extra fields. Use a plain `Schema.Struct`, or transform to one with `Schema.decodeTo`." : `Cannot extend a \`${ast._tag}\` schema node with system fields: a table schema must resolve to an object shape at every step of its encoding.`);
|
|
@@ -72,9 +72,8 @@ const makeExtendAst = (systemPropertySignatures) => {
|
|
|
72
72
|
*
|
|
73
73
|
* A plain `Struct` gains the fields via `Schema.fieldsAssign` and a `Union`
|
|
74
74
|
* has them distributed across its members, preserving the schema's
|
|
75
|
-
* `Struct`/`Union` structure. Any other object-shaped schema
|
|
76
|
-
* `Schema.decodeTo`/`Schema.encodeKeys`, a branded struct, a suspended schema
|
|
77
|
-
* — is extended at the AST level: every object node in its encoding chain
|
|
75
|
+
* `Struct`/`Union` structure. Any other object-shaped schema—one built with
|
|
76
|
+
* `Schema.decodeTo`/`Schema.encodeKeys`, a branded struct, a suspended schema—is extended at the AST level: every object node in its encoding chain
|
|
78
77
|
* gains the system fields, and each transformation is wrapped so the fields
|
|
79
78
|
* bypass the user-defined getters. Schemas that do not resolve to an object
|
|
80
79
|
* shape at every step (such as `Schema.Class`, whose decoded values are class
|
package/dist/SystemFields.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SystemFields.js","names":["GenericId.GenericId"],"sources":["../src/SystemFields.ts"],"sourcesContent":["import type { IdField, SystemFields as NonIdSystemFields } from \"convex/server\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaAST from \"effect/SchemaAST\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nimport * as Struct from \"effect/Struct\";\nimport * as GenericId from \"./GenericId\";\n\n/**\n * Produces a schema for Convex system fields. In Confect, system fields include `_id`.\n */\nexport const SystemFields = <TableName extends string>(tableName: TableName) =>\n Schema.Struct({\n _id: GenericId.GenericId(tableName),\n _creationTime: Schema.Finite,\n });\n\n/**\n * The field map added to a table schema, derived from {@link SystemFields} so it\n * stays in lockstep with the runtime schema.\n */\ntype SystemFieldsFor<TableName extends string> = ReturnType<\n typeof SystemFields<TableName>\n>[\"fields\"];\n\n/**\n * The system field names, derived from {@link SystemFields} so they stay in\n * lockstep with the schema.\n */\nconst systemFieldNames: ReadonlyArray<string> = Record.keys(\n SystemFields(\"\").fields,\n);\n\nconst isSystemFieldKey = (key: string | symbol): key is string =>\n Predicate.isString(key) && Array.contains(systemFieldNames, key);\n\nconst splitSystemFields = (input: { [key: PropertyKey]: unknown }) => {\n const keys = Reflect.ownKeys(input);\n const pick = (pickedKeys: ReadonlyArray<string | symbol>) =>\n Record.fromEntries(\n Array.map(pickedKeys, (key) => [key, input[key]] as const),\n );\n return {\n system: pick(Array.filter(keys, isSystemFieldKey)),\n rest: pick(Array.filter(keys, Predicate.not(isSystemFieldKey))),\n };\n};\n\n/**\n * Wraps a transformation getter so the system fields bypass it: they are split\n * off the input before the user-defined getter runs and merged back into its\n * output. Transformations construct fresh objects, so without this the system\n * fields would be dropped at every transformation step.\n */\nconst wrapGetter = (\n getter: SchemaGetter.Getter<any, any, any>,\n): SchemaGetter.Getter<any, any, any> =>\n new SchemaGetter.Getter((input, options) => {\n if (Option.isNone(input) || !Predicate.isObject(input.value)) {\n return getter.run(input, options);\n }\n const { system, rest } = splitSystemFields(input.value);\n return getter\n .run(Option.some(rest), options)\n .pipe(\n Effect.map(\n Option.map((output) =>\n Predicate.isObject(output) ? Struct.assign(output, system) : output,\n ),\n ),\n );\n });\n\nconst wrapTransformation = (\n transformation: SchemaAST.Link[\"transformation\"],\n): SchemaTransformation.Transformation<any, any, any, any> => {\n if (!SchemaTransformation.isTransformation(transformation)) {\n throw new Error(\n \"Cannot extend a table schema that uses decoding/encoding middleware with system fields\",\n );\n }\n return new SchemaTransformation.Transformation(\n wrapGetter(transformation.decode),\n wrapGetter(transformation.encode),\n );\n};\n\n/**\n * Builds an AST walker that adds the given system-field property signatures to\n * every object node of a schema's AST — including each step of its encoding\n * chain — wrapping transformations so the fields survive them.\n */\nconst makeExtendAst = (\n systemPropertySignatures: ReadonlyArray<SchemaAST.PropertySignature>,\n) => {\n const extendEncoding = (encoding: SchemaAST.Encoding): SchemaAST.Encoding =>\n Array.map(\n encoding,\n (link) =>\n new SchemaAST.Link(\n extendAst(link.to),\n wrapTransformation(link.transformation),\n ),\n );\n\n const extendAst = (ast: SchemaAST.AST): SchemaAST.AST => {\n if (SchemaAST.isUnion(ast)) {\n return new SchemaAST.Union(\n Array.map(ast.types, extendAst),\n ast.mode,\n ast.annotations,\n ast.checks,\n ast.encoding === undefined ? undefined : extendEncoding(ast.encoding),\n ast.context,\n ast.encodingChecks,\n );\n }\n if (SchemaAST.isSuspend(ast)) {\n return new SchemaAST.Suspend(\n () => extendAst(ast.thunk()),\n ast.annotations,\n undefined,\n ast.encoding === undefined ? undefined : extendEncoding(ast.encoding),\n ast.context,\n );\n }\n if (SchemaAST.isObjects(ast)) {\n return new SchemaAST.Objects(\n Array.appendAll(ast.propertySignatures, systemPropertySignatures),\n ast.indexSignatures,\n ast.annotations,\n ast.checks,\n ast.encoding === undefined ? undefined : extendEncoding(ast.encoding),\n ast.context,\n ast.encodingChecks,\n );\n }\n throw new Error(\n ast._tag === \"Declaration\"\n ? \"Cannot extend a `Declaration` schema (such as a `Schema.Class`) with system fields: its decoded values are constructed instances, which cannot gain extra fields. Use a plain `Schema.Struct`, or transform to one with `Schema.decodeTo`.\"\n : `Cannot extend a \\`${ast._tag}\\` schema node with system fields: a table schema must resolve to an object shape at every step of its encoding.`,\n );\n };\n\n return extendAst;\n};\n\n/**\n * Extend a table schema with Convex system fields.\n *\n * A plain `Struct` gains the fields via `Schema.fieldsAssign` and a `Union`\n * has them distributed across its members, preserving the schema's\n * `Struct`/`Union` structure. Any other object-shaped schema — one built with\n * `Schema.decodeTo`/`Schema.encodeKeys`, a branded struct, a suspended schema\n * — is extended at the AST level: every object node in its encoding chain\n * gains the system fields, and each transformation is wrapped so the fields\n * bypass the user-defined getters. Schemas that do not resolve to an object\n * shape at every step (such as `Schema.Class`, whose decoded values are class\n * instances) are rejected with a descriptive error.\n *\n * Note that struct-level checks on an extended schema observe the value with\n * the system fields attached, and encoding an extended schema emits the system\n * fields alongside the table fields.\n */\nexport const extendWithSystemFields = <\n TableName extends string,\n TableSchema extends Schema.Codec<any, any>,\n>(\n tableName: TableName,\n schema: TableSchema,\n): ExtendWithSystemFields<TableName, TableSchema> => {\n const system = SystemFields(tableName).fields;\n\n const extendAst = makeExtendAst(\n pipe(\n system,\n Record.toEntries,\n Array.map(\n ([name, field]) => new SchemaAST.PropertySignature(name, field.ast),\n ),\n ),\n );\n\n const extend = (s: Schema.Top): Schema.Top => {\n if (\n s.ast.encoding === undefined &&\n SchemaAST.isUnion(s.ast) &&\n Array.isArray((s as { readonly members?: unknown }).members)\n ) {\n return Schema.Union(\n Array.map(\n (s as Schema.Union<ReadonlyArray<Schema.Top>>).members,\n extend,\n ),\n );\n }\n if (\n s.ast.encoding === undefined &&\n SchemaAST.isObjects(s.ast) &&\n typeof (s as { readonly mapFields?: unknown }).mapFields === \"function\"\n ) {\n return Schema.fieldsAssign(system)(\n s as Schema.Struct<Schema.Struct.Fields>,\n );\n }\n return Schema.make(extendAst(s.ast));\n };\n\n return extend(schema) as unknown as ExtendWithSystemFields<\n TableName,\n TableSchema\n >;\n};\n\n/**\n * Applies the system fields to a single struct, mirroring `Schema.fieldsAssign`.\n * Any other (already-extended or opaque) schema falls back to a `Codec` carrying\n * the system-field document shape.\n */\ntype ApplySystemFields<TableName extends string, S> =\n S extends Schema.Struct<infer Fields extends Schema.Struct.Fields>\n ? Schema.Struct<\n Struct.Simplify<Struct.Assign<Fields, SystemFieldsFor<TableName>>>\n >\n : S extends Schema.Codec<infer Type, infer Encoded>\n ? Schema.Codec<\n WithSystemFields<TableName, Type>,\n WithSystemFields<TableName, Encoded>\n >\n : never;\n\n/**\n * Extend a table schema with Convex system fields at the type level.\n *\n * This mirrors the runtime {@link extendWithSystemFields}: a `Struct` gains the\n * system fields directly (matching `Schema.fieldsAssign`), and a `Union` has\n * them distributed across its members (matching\n * `union.mapMembers(Tuple.map(Schema.fieldsAssign(...)))`). The `Struct`/`Union`\n * structure is preserved rather than collapsed to a bare `Codec`; any other\n * schema falls back to a `Codec` carrying the system-field document shape,\n * matching the runtime's AST-level extension.\n */\nexport type ExtendWithSystemFields<\n TableName extends string,\n TableSchema extends Schema.Top,\n> =\n TableSchema extends Schema.Union<\n infer Members extends ReadonlyArray<Schema.Top>\n >\n ? Schema.Union<\n Struct.Simplify<\n Readonly<{\n [K in keyof Members]: ExtendWithSystemFields<TableName, Members[K]>;\n }>\n >\n >\n : ApplySystemFields<TableName, TableSchema>;\n\n/**\n * The decoded/encoded document shape: a table's fields plus Convex's system\n * fields. Deliberately a bare intersection (no `Expand`/`Simplify`) — flattening\n * it with a homomorphic mapped type collapses to `{ [x: string]: any }` when\n * `Document` is still an unresolved generic, which breaks structural\n * comparability in the database reader/writer plumbing.\n */\nexport type WithSystemFields<\n TableName extends string,\n Document,\n> = Document extends unknown\n ? IdField<TableName> & NonIdSystemFields & Document\n : never;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiBA,MAAa,gBAA0C,cACrD,OAAO,OAAO;CACZ,KAAKA,UAAoB,SAAS;CAClC,eAAe,OAAO;AACxB,CAAC;;;;;AAcH,MAAM,mBAA0C,OAAO,KACrD,aAAa,EAAE,CAAC,CAAC,MACnB;AAEA,MAAM,oBAAoB,QACxB,UAAU,SAAS,GAAG,KAAK,MAAM,SAAS,kBAAkB,GAAG;AAEjE,MAAM,qBAAqB,UAA2C;CACpE,MAAM,OAAO,QAAQ,QAAQ,KAAK;CAClC,MAAM,QAAQ,eACZ,OAAO,YACL,MAAM,IAAI,aAAa,QAAQ,CAAC,KAAK,MAAM,IAAI,CAAU,CAC3D;CACF,OAAO;EACL,QAAQ,KAAK,MAAM,OAAO,MAAM,gBAAgB,CAAC;EACjD,MAAM,KAAK,MAAM,OAAO,MAAM,UAAU,IAAI,gBAAgB,CAAC,CAAC;CAChE;AACF;;;;;;;AAQA,MAAM,cACJ,WAEA,IAAI,aAAa,QAAQ,OAAO,YAAY;CAC1C,IAAI,OAAO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,aAAa,KAAA,IAAY,KAAA,IAAY,eAAe,IAAI,QAAQ,GACpE,IAAI,SACJ,IAAI,cACN;EAEF,MAAM,IAAI,MACR,IAAI,SAAS,gBACT,+OACA,qBAAqB,IAAI,KAAK,iHACpC;CACF;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,MAAa,0BAIX,WACA,WACmD;CACnD,MAAM,SAAS,aAAa,SAAS,CAAC,CAAC;CAEvC,MAAM,YAAY,cAChB,KACE,QACA,OAAO,WACP,MAAM,KACH,CAAC,MAAM,WAAW,IAAI,UAAU,kBAAkB,MAAM,MAAM,GAAG,CACpE,CACF,CACF;CAEA,MAAM,UAAU,MAA8B;EAC5C,IACE,EAAE,IAAI,aAAa,KAAA,KACnB,UAAU,QAAQ,EAAE,GAAG,KACvB,MAAM,QAAS,EAAqC,OAAO,GAE3D,OAAO,OAAO,MACZ,MAAM,IACH,EAA8C,SAC/C,MACF,CACF;EAEF,IACE,EAAE,IAAI,aAAa,KAAA,KACnB,UAAU,UAAU,EAAE,GAAG,KACzB,OAAQ,EAAuC,cAAc,YAE7D,OAAO,OAAO,aAAa,MAAM,CAAC,CAChC,CACF;EAEF,OAAO,OAAO,KAAK,UAAU,EAAE,GAAG,CAAC;CACrC;CAEA,OAAO,OAAO,MAAM;AAItB"}
|
|
1
|
+
{"version":3,"file":"SystemFields.js","names":["GenericId.GenericId"],"sources":["../src/SystemFields.ts"],"sourcesContent":["import type { IdField, SystemFields as NonIdSystemFields } from \"convex/server\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaAST from \"effect/SchemaAST\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nimport * as Struct from \"effect/Struct\";\nimport * as GenericId from \"./GenericId\";\n\n/**\n * Produces a schema for Convex system fields. In Confect, system fields include `_id`.\n */\nexport const SystemFields = <TableName extends string>(tableName: TableName) =>\n Schema.Struct({\n _id: GenericId.GenericId(tableName),\n _creationTime: Schema.Finite,\n });\n\n/**\n * The field map added to a table schema, derived from {@link SystemFields} so it\n * stays in lockstep with the runtime schema.\n */\ntype SystemFieldsFor<TableName extends string> = ReturnType<\n typeof SystemFields<TableName>\n>[\"fields\"];\n\n/**\n * The system field names, derived from {@link SystemFields} so they stay in\n * lockstep with the schema.\n */\nconst systemFieldNames: ReadonlyArray<string> = Record.keys(\n SystemFields(\"\").fields,\n);\n\nconst isSystemFieldKey = (key: string | symbol): key is string =>\n Predicate.isString(key) && Array.contains(systemFieldNames, key);\n\nconst splitSystemFields = (input: { [key: PropertyKey]: unknown }) => {\n const keys = Reflect.ownKeys(input);\n const pick = (pickedKeys: ReadonlyArray<string | symbol>) =>\n Record.fromEntries(\n Array.map(pickedKeys, (key) => [key, input[key]] as const),\n );\n return {\n system: pick(Array.filter(keys, isSystemFieldKey)),\n rest: pick(Array.filter(keys, Predicate.not(isSystemFieldKey))),\n };\n};\n\n/**\n * Wraps a transformation getter so the system fields bypass it: they are split\n * off the input before the user-defined getter runs and merged back into its\n * output. Transformations construct fresh objects, so without this the system\n * fields would be dropped at every transformation step.\n */\nconst wrapGetter = <R>(\n getter: SchemaGetter.Getter<any, any, R>,\n): SchemaGetter.Getter<any, any, R> =>\n new SchemaGetter.Getter((input, options) => {\n if (Option.isNone(input) || !Predicate.isObject(input.value)) {\n return getter.run(input, options);\n }\n const { system, rest } = splitSystemFields(input.value);\n return getter\n .run(Option.some(rest), options)\n .pipe(\n Effect.map(\n Option.map((output) =>\n Predicate.isObject(output) ? Struct.assign(output, system) : output,\n ),\n ),\n );\n });\n\nconst wrapTransformation = (\n transformation: SchemaAST.Link[\"transformation\"],\n): SchemaTransformation.Transformation<any, any, any, any> => {\n if (!SchemaTransformation.isTransformation(transformation)) {\n throw new Error(\n \"Cannot extend a table schema that uses decoding/encoding middleware with system fields\",\n );\n }\n return new SchemaTransformation.Transformation(\n wrapGetter(transformation.decode),\n wrapGetter(transformation.encode),\n );\n};\n\n/**\n * Builds an AST walker that adds the given system-field property signatures to\n * every object node of a schema's AST—including each step of its encoding\n * chain—wrapping transformations so the fields survive them.\n */\nconst makeExtendAst = (\n systemPropertySignatures: ReadonlyArray<SchemaAST.PropertySignature>,\n) => {\n const extendEncoding = (encoding: SchemaAST.Encoding): SchemaAST.Encoding =>\n Array.map(\n encoding,\n (link) =>\n new SchemaAST.Link(\n extendAst(link.to),\n wrapTransformation(link.transformation),\n ),\n );\n\n const extendAst = (ast: SchemaAST.AST): SchemaAST.AST => {\n if (SchemaAST.isUnion(ast)) {\n return new SchemaAST.Union(\n Array.map(ast.types, extendAst),\n ast.options,\n ast.annotations,\n ast.checks,\n ast.encoding === undefined ? undefined : extendEncoding(ast.encoding),\n ast.context,\n ast.encodingChecks,\n );\n }\n if (SchemaAST.isSuspend(ast)) {\n return new SchemaAST.Suspend(\n () => extendAst(ast.thunk()),\n ast.annotations,\n undefined,\n ast.encoding === undefined ? undefined : extendEncoding(ast.encoding),\n ast.context,\n );\n }\n if (SchemaAST.isObjects(ast)) {\n return new SchemaAST.Objects(\n Array.appendAll(ast.propertySignatures, systemPropertySignatures),\n ast.indexSignatures,\n ast.annotations,\n ast.checks,\n ast.encoding === undefined ? undefined : extendEncoding(ast.encoding),\n ast.context,\n ast.encodingChecks,\n );\n }\n throw new Error(\n ast._tag === \"Declaration\"\n ? \"Cannot extend a `Declaration` schema (such as a `Schema.Class`) with system fields: its decoded values are constructed instances, which cannot gain extra fields. Use a plain `Schema.Struct`, or transform to one with `Schema.decodeTo`.\"\n : `Cannot extend a \\`${ast._tag}\\` schema node with system fields: a table schema must resolve to an object shape at every step of its encoding.`,\n );\n };\n\n return extendAst;\n};\n\n/**\n * Extend a table schema with Convex system fields.\n *\n * A plain `Struct` gains the fields via `Schema.fieldsAssign` and a `Union`\n * has them distributed across its members, preserving the schema's\n * `Struct`/`Union` structure. Any other object-shaped schema—one built with\n * `Schema.decodeTo`/`Schema.encodeKeys`, a branded struct, a suspended schema—is extended at the AST level: every object node in its encoding chain\n * gains the system fields, and each transformation is wrapped so the fields\n * bypass the user-defined getters. Schemas that do not resolve to an object\n * shape at every step (such as `Schema.Class`, whose decoded values are class\n * instances) are rejected with a descriptive error.\n *\n * Note that struct-level checks on an extended schema observe the value with\n * the system fields attached, and encoding an extended schema emits the system\n * fields alongside the table fields.\n */\nexport const extendWithSystemFields = <\n TableName extends string,\n TableSchema extends Schema.Codec<any, any>,\n>(\n tableName: TableName,\n schema: TableSchema,\n): ExtendWithSystemFields<TableName, TableSchema> => {\n const system = SystemFields(tableName).fields;\n\n const extendAst = makeExtendAst(\n pipe(\n system,\n Record.toEntries,\n Array.map(\n ([name, field]) => new SchemaAST.PropertySignature(name, field.ast),\n ),\n ),\n );\n\n const extend = (s: Schema.Top): Schema.Top => {\n if (\n s.ast.encoding === undefined &&\n SchemaAST.isUnion(s.ast) &&\n Array.isArray((s as { readonly members?: unknown }).members)\n ) {\n return Schema.Union(\n Array.map(\n (s as Schema.Union<ReadonlyArray<Schema.Top>>).members,\n extend,\n ),\n );\n }\n if (\n s.ast.encoding === undefined &&\n SchemaAST.isObjects(s.ast) &&\n typeof (s as { readonly mapFields?: unknown }).mapFields === \"function\"\n ) {\n return Schema.fieldsAssign(system)(\n s as Schema.Struct<Schema.Struct.Fields>,\n );\n }\n return Schema.make(extendAst(s.ast));\n };\n\n return extend(schema) as unknown as ExtendWithSystemFields<\n TableName,\n TableSchema\n >;\n};\n\n/**\n * Applies the system fields to a single struct, mirroring `Schema.fieldsAssign`.\n * Any other (already-extended or opaque) schema falls back to a `Codec` carrying\n * the system-field document shape.\n */\ntype ApplySystemFields<TableName extends string, S> =\n S extends Schema.Struct<infer Fields extends Schema.Struct.Fields>\n ? Schema.Struct<\n Struct.Simplify<Struct.Assign<Fields, SystemFieldsFor<TableName>>>\n >\n : S extends Schema.Codec<infer Type, infer Encoded>\n ? Schema.Codec<\n WithSystemFields<TableName, Type>,\n WithSystemFields<TableName, Encoded>\n >\n : never;\n\n/**\n * Extend a table schema with Convex system fields at the type level.\n *\n * This mirrors the runtime {@link extendWithSystemFields}: a `Struct` gains the\n * system fields directly (matching `Schema.fieldsAssign`), and a `Union` has\n * them distributed across its members (matching\n * `union.mapMembers(Tuple.map(Schema.fieldsAssign(...)))`). The `Struct`/`Union`\n * structure is preserved rather than collapsed to a bare `Codec`; any other\n * schema falls back to a `Codec` carrying the system-field document shape,\n * matching the runtime's AST-level extension.\n */\nexport type ExtendWithSystemFields<\n TableName extends string,\n TableSchema extends Schema.Top,\n> =\n TableSchema extends Schema.Union<\n infer Members extends ReadonlyArray<Schema.Top>\n >\n ? Schema.Union<\n Struct.Simplify<\n Readonly<{\n [K in keyof Members]: ExtendWithSystemFields<TableName, Members[K]>;\n }>\n >\n >\n : ApplySystemFields<TableName, TableSchema>;\n\n/**\n * The decoded/encoded document shape: a table's fields plus Convex's system\n * fields. Deliberately a bare intersection (no `Expand`/`Simplify`)—flattening\n * it with a homomorphic mapped type collapses to `{ [x: string]: any }` when\n * `Document` is still an unresolved generic, which breaks structural\n * comparability in the database reader/writer plumbing.\n */\nexport type WithSystemFields<\n TableName extends string,\n Document,\n> = Document extends unknown\n ? IdField<TableName> & NonIdSystemFields & Document\n : never;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiBA,MAAa,gBAA0C,cACrD,OAAO,OAAO;CACZ,KAAKA,UAAoB,SAAS;CAClC,eAAe,OAAO;AACxB,CAAC;;;;;AAcH,MAAM,mBAA0C,OAAO,KACrD,aAAa,EAAE,CAAC,CAAC,MACnB;AAEA,MAAM,oBAAoB,QACxB,UAAU,SAAS,GAAG,KAAK,MAAM,SAAS,kBAAkB,GAAG;AAEjE,MAAM,qBAAqB,UAA2C;CACpE,MAAM,OAAO,QAAQ,QAAQ,KAAK;CAClC,MAAM,QAAQ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AG,GACzB,OAAO,IAAI,UAAU,cACb,UAAU,IAAI,MAAM,CAAC,GAC3B,IAAI,aACJ,KAAA,GACA,IAAI,aAAa,KAAA,IAAY,KAAA,IAAY,eAAe,IAAI,QAAQ,GACpE,IAAI,OACN;EAEF,IAAI,UAAU,UAAU,GAAG,GACzB,OAAO,IAAI,UAAU,QACnB,MAAM,UAAU,IAAI,oBAAoB,wBAAwB,GAChE,IAAI,iBACJ,IAAI,aACJ,IAAI,QACJ,IAAI,aAAa,KAAA,IAAY,KAAA,IAAY,eAAe,IAAI,QAAQ,GACpE,IAAI,SACJ,IAAI,cACN;EAEF,MAAM,IAAI,MACR,IAAI,SAAS,gBACT,+OACA,qBAAqB,IAAI,KAAK,iHACpC;CACF;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,MAAa,0BAIX,WACA,WACmD;CACnD,MAAM,SAAS,aAAa,SAAS,CAAC,CAAC;CAEvC,MAAM,YAAY,cAChB,KACE,QACA,OAAO,WACP,MAAM,KACH,CAAC,MAAM,WAAW,IAAI,UAAU,kBAAkB,MAAM,MAAM,GAAG,CACpE,CACF,CACF;CAEA,MAAM,UAAU,MAA8B;EAC5C,IACE,EAAE,IAAI,aAAa,KAAA,KACnB,UAAU,QAAQ,EAAE,GAAG,KACvB,MAAM,QAAS,EAAqC,OAAO,GAE3D,OAAO,OAAO,MACZ,MAAM,IACH,EAA8C,SAC/C,MACF,CACF;EAEF,IACE,EAAE,IAAI,aAAa,KAAA,KACnB,UAAU,UAAU,EAAE,GAAG,KACzB,OAAQ,EAAuC,cAAc,YAE7D,OAAO,OAAO,aAAa,MAAM,CAAC,CAChC,CACF;EAEF,OAAO,OAAO,KAAK,UAAU,EAAE,GAAG,CAAC;CACrC;CAEA,OAAO,OAAO,MAAM;AAItB"}
|
package/dist/Table.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Table.js","names":["SystemFields.extendWithSystemFields"],"sources":["../src/Table.ts"],"sourcesContent":["import * as Lazy from \"./Lazy\";\nimport * as SystemFields from \"./SystemFields\";\nimport type { TableSchemaToTableValidator } from \"./SchemaToValidator\";\nimport type {\n SystemFields as ConvexSystemFields,\n Expand,\n GenericTableIndexes,\n GenericTableSearchIndexes,\n GenericTableVectorIndexes,\n IndexTiebreakerField,\n SearchIndexConfig,\n VectorIndexConfig,\n} from \"convex/server\";\nimport type { GenericValidator, Validator } from \"convex/values\";\nimport * as Predicate from \"effect/Predicate\";\nimport type * as Schema from \"effect/Schema\";\n\nexport const TypeId = \"~@confect/core/Table\";\nexport type TypeId = typeof TypeId;\n\n// -----------------------------------------------------------------------------\n// Predicates\n// -----------------------------------------------------------------------------\n//\n// Both bound `Table`s and `UnnamedTable` callables share the same `[TypeId]`\n// brand. They disambiguate by whether a `tableName` property is set: bound\n// tables have one, unnamed callables do not.\n//\n// The discriminator is `tableName` (not `name`) so it does not collide with\n// the built-in `Function.prototype.name` that every JS function carries.\n\nexport const isTable = (u: unknown): u is Any =>\n Predicate.hasProperty(u, TypeId) && Predicate.hasProperty(u, \"tableName\");\n\nexport const isUnnamedTable = (u: unknown): u is UnnamedAny =>\n Predicate.hasProperty(u, TypeId) && !Predicate.hasProperty(u, \"tableName\");\n\n// -----------------------------------------------------------------------------\n// Bound Table\n// -----------------------------------------------------------------------------\n//\n// A bound `Table` is the client-safe document schema: `Fields`, `Doc`, and\n// the index metadata records. The Convex deploy `tableDefinition` (which\n// value-imports `convex/server`) is produced separately by\n// `@confect/server/Table.tableDefinition`.\n\nexport interface Table<\n Name_ extends string,\n TableSchema_ extends Schema.Codec<any, any>,\n TableValidator_ extends GenericValidator =\n TableSchemaToTableValidator<TableSchema_>,\n Indexes_ extends GenericTableIndexes = {},\n SearchIndexes_ extends GenericTableSearchIndexes = {},\n VectorIndexes_ extends GenericTableVectorIndexes = {},\n> {\n readonly [TypeId]: TypeId;\n readonly tableName: Name_;\n readonly Fields: TableSchema_;\n readonly Doc: SystemFields.ExtendWithSystemFields<Name_, TableSchema_>;\n readonly indexes: Indexes_;\n readonly searchIndexes: SearchIndexes_;\n readonly vectorIndexes: VectorIndexes_;\n readonly \"~TableValidator\": TableValidator_;\n}\n\nexport interface Any {\n readonly [TypeId]: TypeId;\n readonly tableName: string;\n}\n\nexport type AnyWithProps = Table<\n any,\n Schema.Codec<any, any>,\n GenericValidator,\n GenericTableIndexes,\n GenericTableSearchIndexes,\n GenericTableVectorIndexes\n>;\n\n// -----------------------------------------------------------------------------\n// UnnamedTable (callable)\n// -----------------------------------------------------------------------------\n//\n// `Table.make(lazyFields)` returns an `UnnamedTable`: a callable that\n// produces a fully bound `Table` when invoked with a name. Chaining methods\n// (`.index`, `.searchIndex`, `.vectorIndex`) live here and return new\n// `UnnamedTable`s, accumulating plain index metadata records. The\n// user-supplied `lazyFields` callback is just carried through until first\n// access of `Fields` / `Doc` on a bound table. The codegen pipeline emits a\n// wrapper file per user-authored table that simply invokes the unnamed\n// callable with the filename basename.\n\nexport interface UnnamedTable<\n TableSchema_ extends Schema.Codec<any, any>,\n TableValidator_ extends GenericValidator =\n TableSchemaToTableValidator<TableSchema_>,\n Indexes_ extends GenericTableIndexes = {},\n SearchIndexes_ extends GenericTableSearchIndexes = {},\n VectorIndexes_ extends GenericTableVectorIndexes = {},\n> {\n <const Name_ extends string>(\n tableName: Name_,\n ): Table<\n Name_,\n TableSchema_,\n TableValidator_,\n Indexes_,\n SearchIndexes_,\n VectorIndexes_\n >;\n\n readonly [TypeId]: TypeId;\n readonly indexes: Indexes_;\n readonly searchIndexes: SearchIndexes_;\n readonly vectorIndexes: VectorIndexes_;\n readonly \"~TableValidator\": TableValidator_;\n\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<TableValidator_>,\n RestFieldPaths extends ExtractFieldPaths<TableValidator_>[],\n >(\n name: IndexName,\n fields: [FirstFieldPath, ...RestFieldPaths],\n ): UnnamedTable<\n TableSchema_,\n TableValidator_,\n Expand<\n Indexes_ &\n Record<\n IndexName,\n [FirstFieldPath, ...RestFieldPaths, IndexTiebreakerField]\n >\n >,\n SearchIndexes_,\n VectorIndexes_\n >;\n\n searchIndex<\n IndexName extends string,\n SearchField extends ExtractFieldPaths<TableValidator_>,\n FilterFields extends ExtractFieldPaths<TableValidator_> = never,\n >(\n name: IndexName,\n indexConfig: Expand<SearchIndexConfig<SearchField, FilterFields>>,\n ): UnnamedTable<\n TableSchema_,\n TableValidator_,\n Indexes_,\n Expand<\n SearchIndexes_ &\n Record<\n IndexName,\n {\n searchField: SearchField;\n filterFields: FilterFields;\n }\n >\n >,\n VectorIndexes_\n >;\n\n vectorIndex<\n IndexName extends string,\n VectorField extends ExtractFieldPaths<TableValidator_>,\n FilterFields extends ExtractFieldPaths<TableValidator_> = never,\n >(\n name: IndexName,\n indexConfig: Expand<VectorIndexConfig<VectorField, FilterFields>>,\n ): UnnamedTable<\n TableSchema_,\n TableValidator_,\n Indexes_,\n SearchIndexes_,\n Expand<\n VectorIndexes_ &\n Record<\n IndexName,\n {\n vectorField: VectorField;\n dimensions: number;\n filterFields: FilterFields;\n }\n >\n >\n >;\n}\n\nexport interface UnnamedAny {\n readonly [TypeId]: TypeId;\n}\n\nexport type UnnamedAnyWithProps = UnnamedTable<\n Schema.Codec<any, any>,\n GenericValidator,\n GenericTableIndexes,\n GenericTableSearchIndexes,\n GenericTableVectorIndexes\n>;\n\n// -----------------------------------------------------------------------------\n// Type extractors\n// -----------------------------------------------------------------------------\n\nexport type Name<TableDef extends AnyWithProps> = TableDef[\"tableName\"] &\n string;\n\nexport type TableSchema<TableDef extends AnyWithProps> = TableDef[\"Fields\"];\n\nexport type TableValidator<TableDef extends AnyWithProps> =\n TableDef[\"~TableValidator\"];\n\nexport type Indexes<TableDef extends AnyWithProps> = TableDef[\"indexes\"];\n\nexport type SearchIndexes<TableDef extends AnyWithProps> =\n TableDef[\"searchIndexes\"];\n\nexport type VectorIndexes<TableDef extends AnyWithProps> =\n TableDef[\"vectorIndexes\"];\n\nexport type Doc<TableDef extends AnyWithProps> = TableDef[\"Doc\"];\n\nexport type Fields<TableDef extends AnyWithProps> = TableDef[\"Fields\"];\n\nexport type WithName<\n TableDef extends AnyWithProps,\n Name_ extends string,\n> = TableDef extends { readonly tableName: Name_ } ? TableDef : never;\n\nexport type TablesRecord<Tables extends AnyWithProps> = {\n readonly [TableName_ in Name<Tables>]: WithName<Tables, TableName_>;\n};\n\n// -----------------------------------------------------------------------------\n// Construction\n// -----------------------------------------------------------------------------\n//\n// `make` only stores the user-supplied `lazyFields` callback alongside any\n// chained index metadata. Neither `Fields` nor `Doc` is constructed until\n// first access on a bound `Table`. Each chain step is O(1) (plain object\n// spread of the metadata records) and never invokes the callback. Binding\n// via `unnamed(tableName)` installs lazy memoised getters for `Fields` and\n// `Doc` via `Lazy.defineProperty`, so the first access materialises the\n// value and replaces the getter with a plain data property — second-and-\n// subsequent accesses are observably indistinguishable from a plain\n// property and avoid all function-call overhead.\n\ninterface UnnamedState<\n TableSchema_ extends Schema.Codec<any, any>,\n Indexes_ extends GenericTableIndexes,\n SearchIndexes_ extends GenericTableSearchIndexes,\n VectorIndexes_ extends GenericTableVectorIndexes,\n> {\n readonly lazyFields: () => TableSchema_;\n readonly indexes: Indexes_;\n readonly searchIndexes: SearchIndexes_;\n readonly vectorIndexes: VectorIndexes_;\n}\n\nconst makeBound = <\n Name_ extends string,\n TableSchema_ extends Schema.Codec<any, any>,\n TableValidator_ extends Validator<any, any, any>,\n Indexes_ extends GenericTableIndexes,\n SearchIndexes_ extends GenericTableSearchIndexes,\n VectorIndexes_ extends GenericTableVectorIndexes,\n>(\n tableName: Name_,\n state: UnnamedState<TableSchema_, Indexes_, SearchIndexes_, VectorIndexes_>,\n): Table<\n Name_,\n TableSchema_,\n TableValidator_,\n Indexes_,\n SearchIndexes_,\n VectorIndexes_\n> => {\n const bound = {\n [TypeId]: TypeId as TypeId,\n tableName,\n indexes: state.indexes,\n searchIndexes: state.searchIndexes,\n vectorIndexes: state.vectorIndexes,\n } as Table<\n Name_,\n TableSchema_,\n TableValidator_,\n Indexes_,\n SearchIndexes_,\n VectorIndexes_\n >;\n\n Lazy.defineProperty(bound, \"Fields\", () => state.lazyFields());\n\n Lazy.defineProperty(bound, \"Doc\", () =>\n SystemFields.extendWithSystemFields(\n tableName,\n (bound as { Fields: TableSchema_ }).Fields,\n ),\n );\n\n return bound;\n};\n\nconst makeUnnamed = <\n TableSchema_ extends Schema.Codec<any, any>,\n TableValidator_ extends Validator<any, any, any>,\n Indexes_ extends GenericTableIndexes,\n SearchIndexes_ extends GenericTableSearchIndexes,\n VectorIndexes_ extends GenericTableVectorIndexes,\n>(\n state: UnnamedState<TableSchema_, Indexes_, SearchIndexes_, VectorIndexes_>,\n): UnnamedTable<\n TableSchema_,\n TableValidator_,\n Indexes_,\n SearchIndexes_,\n VectorIndexes_\n> => {\n type UnnamedTable_ = UnnamedTable<\n TableSchema_,\n TableValidator_,\n Indexes_,\n SearchIndexes_,\n VectorIndexes_\n >;\n\n type UnnamedTableFunction<FunctionName extends keyof UnnamedTable_> =\n UnnamedTable_[FunctionName];\n\n const bind = <const Name_ extends string>(\n tableName: Name_,\n ): Table<\n Name_,\n TableSchema_,\n TableValidator_,\n Indexes_,\n SearchIndexes_,\n VectorIndexes_\n > =>\n makeBound<\n Name_,\n TableSchema_,\n TableValidator_,\n Indexes_,\n SearchIndexes_,\n VectorIndexes_\n >(tableName, state);\n\n const index: UnnamedTableFunction<\"index\"> = (name, fields) =>\n makeUnnamed({\n lazyFields: state.lazyFields,\n indexes: {\n ...state.indexes,\n [name]: fields,\n } as any,\n searchIndexes: state.searchIndexes,\n vectorIndexes: state.vectorIndexes,\n });\n\n const searchIndex: UnnamedTableFunction<\"searchIndex\"> = (\n name,\n indexConfig,\n ) =>\n makeUnnamed({\n lazyFields: state.lazyFields,\n indexes: state.indexes,\n searchIndexes: {\n ...state.searchIndexes,\n [name]: indexConfig,\n } as any,\n vectorIndexes: state.vectorIndexes,\n });\n\n const vectorIndex: UnnamedTableFunction<\"vectorIndex\"> = (\n name,\n indexConfig,\n ) =>\n makeUnnamed({\n lazyFields: state.lazyFields,\n indexes: state.indexes,\n searchIndexes: state.searchIndexes,\n vectorIndexes: {\n ...state.vectorIndexes,\n [name]: indexConfig,\n } as any,\n });\n\n return Object.assign(bind, {\n [TypeId]: TypeId as TypeId,\n indexes: state.indexes,\n searchIndexes: state.searchIndexes,\n vectorIndexes: state.vectorIndexes,\n index,\n searchIndex,\n vectorIndex,\n }) as UnnamedTable_;\n};\n\nexport const make = <const TableSchema_ extends Schema.Codec<any, any>>(\n lazyFields: () => TableSchema_,\n): UnnamedTable<TableSchema_, TableSchemaToTableValidator<TableSchema_>> => {\n type TableValidator_ = TableSchemaToTableValidator<TableSchema_>;\n type UnnamedTable_ = UnnamedTable<TableSchema_, TableValidator_>;\n\n return makeUnnamed<TableSchema_, TableValidator_, {}, {}, {}>({\n lazyFields,\n indexes: {},\n searchIndexes: {},\n vectorIndexes: {},\n }) as UnnamedTable_;\n};\n\n// Vendored types from convex-js, partially modified. Ideally we could use these directly. See https://github.com/get-convex/convex-js/pull/14\n\n/**\n * Extract all of the index field paths within a Convex `Validator`.\n *\n * This is used when declaring table indexes.\n * @public\n */\ntype ExtractFieldPaths<T extends Validator<any, any, any>> =\n // Add in the system fields available in index definitions.\n // This should be everything except for `_id` because thats added to indexes\n // automatically.\n T[\"fieldPaths\"] | keyof ConvexSystemFields;\n"],"mappings":";;;;;;;;;;;AAiBA,MAAa,SAAS;AActB,MAAa,WAAW,MACtB,UAAU,YAAY,GAAA,sBAAS,KAAK,UAAU,YAAY,GAAG,WAAW;AAE1E,MAAa,kBAAkB,MAC7B,UAAU,YAAY,GAAA,sBAAS,KAAK,CAAC,UAAU,YAAY,GAAG,WAAW;AAgO3E,MAAM,aAQJ,WACA,UAQG;CACH,MAAM,QAAQ;GACX,SAAS;EACV;EACA,SAAS,MAAM;EACf,eAAe,MAAM;EACrB,eAAe,MAAM;CACvB;CASA,eAAoB,OAAO,gBAAgB,MAAM,WAAW,CAAC;CAE7D,eAAoB,OAAO,aACzBA,uBACE,WACC,MAAmC,MACtC,CACF;CAEA,OAAO;AACT;AAEA,MAAM,eAOJ,UAOG;CAYH,MAAM,QACJ,cASA,UAOE,WAAW,KAAK;CAEpB,MAAM,SAAwC,MAAM,WAClD,YAAY;EACV,YAAY,MAAM;EAClB,SAAS;GACP,GAAG,MAAM;IACR,OAAO;EACV;EACA,eAAe,MAAM;EACrB,eAAe,MAAM;CACvB,CAAC;CAEH,MAAM,eACJ,MACA,gBAEA,YAAY;EACV,YAAY,MAAM;EAClB,SAAS,MAAM;EACf,eAAe;GACb,GAAG,MAAM;IACR,OAAO;EACV;EACA,eAAe,MAAM;CACvB,CAAC;CAEH,MAAM,eACJ,MACA,gBAEA,YAAY;EACV,YAAY,MAAM;EAClB,SAAS,MAAM;EACf,eAAe,MAAM;EACrB,eAAe;GACb,GAAG,MAAM;IACR,OAAO;EACV;CACF,CAAC;CAEH,OAAO,OAAO,OAAO,MAAM;GACxB,SAAS;EACV,SAAS,MAAM;EACf,eAAe,MAAM;EACrB,eAAe,MAAM;EACrB;EACA;EACA;CACF,CAAC;AACH;AAEA,MAAa,QACX,eAC0E;CAI1E,OAAO,YAAuD;EAC5D;EACA,SAAS,CAAC;EACV,eAAe,CAAC;EAChB,eAAe,CAAC;CAClB,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"Table.js","names":["SystemFields.extendWithSystemFields"],"sources":["../src/Table.ts"],"sourcesContent":["import * as Lazy from \"./Lazy\";\nimport * as SystemFields from \"./SystemFields\";\nimport type { TableSchemaToTableValidator } from \"./SchemaToValidator\";\nimport type {\n SystemFields as ConvexSystemFields,\n Expand,\n GenericTableIndexes,\n GenericTableSearchIndexes,\n GenericTableVectorIndexes,\n IndexTiebreakerField,\n SearchIndexConfig,\n VectorIndexConfig,\n} from \"convex/server\";\nimport type { GenericValidator, Validator } from \"convex/values\";\nimport * as Predicate from \"effect/Predicate\";\nimport type * as Schema from \"effect/Schema\";\n\nexport const TypeId = \"~@confect/core/Table\";\nexport type TypeId = typeof TypeId;\n\n// -----------------------------------------------------------------------------\n// Predicates\n// -----------------------------------------------------------------------------\n//\n// Both bound `Table`s and `UnnamedTable` callables share the same `[TypeId]`\n// brand. They disambiguate by whether a `tableName` property is set: bound\n// tables have one, unnamed callables do not.\n//\n// The discriminator is `tableName` (not `name`) so it does not collide with\n// the built-in `Function.prototype.name` that every JS function carries.\n\nexport const isTable = (u: unknown): u is Any =>\n Predicate.hasProperty(u, TypeId) && Predicate.hasProperty(u, \"tableName\");\n\nexport const isUnnamedTable = (u: unknown): u is UnnamedAny =>\n Predicate.hasProperty(u, TypeId) && !Predicate.hasProperty(u, \"tableName\");\n\n// -----------------------------------------------------------------------------\n// Bound Table\n// -----------------------------------------------------------------------------\n//\n// A bound `Table` is the client-safe document schema: `Fields`, `Doc`, and\n// the index metadata records. The Convex deploy `tableDefinition` (which\n// value-imports `convex/server`) is produced separately by\n// `@confect/server/Table.tableDefinition`.\n\nexport interface Table<\n Name_ extends string,\n TableSchema_ extends Schema.Codec<any, any>,\n TableValidator_ extends GenericValidator =\n TableSchemaToTableValidator<TableSchema_>,\n Indexes_ extends GenericTableIndexes = {},\n SearchIndexes_ extends GenericTableSearchIndexes = {},\n VectorIndexes_ extends GenericTableVectorIndexes = {},\n> {\n readonly [TypeId]: TypeId;\n readonly tableName: Name_;\n readonly Fields: TableSchema_;\n readonly Doc: SystemFields.ExtendWithSystemFields<Name_, TableSchema_>;\n readonly indexes: Indexes_;\n readonly searchIndexes: SearchIndexes_;\n readonly vectorIndexes: VectorIndexes_;\n readonly \"~TableValidator\": TableValidator_;\n}\n\nexport interface Any {\n readonly [TypeId]: TypeId;\n readonly tableName: string;\n}\n\nexport type AnyWithProps = Table<\n any,\n Schema.Codec<any, any>,\n GenericValidator,\n GenericTableIndexes,\n GenericTableSearchIndexes,\n GenericTableVectorIndexes\n>;\n\n// -----------------------------------------------------------------------------\n// UnnamedTable (callable)\n// -----------------------------------------------------------------------------\n//\n// `Table.make(lazyFields)` returns an `UnnamedTable`: a callable that\n// produces a fully bound `Table` when invoked with a name. Chaining methods\n// (`.index`, `.searchIndex`, `.vectorIndex`) live here and return new\n// `UnnamedTable`s, accumulating plain index metadata records. The\n// user-supplied `lazyFields` callback is just carried through until first\n// access of `Fields`/`Doc` on a bound table. The codegen pipeline emits a\n// wrapper file per user-authored table that simply invokes the unnamed\n// callable with the filename basename.\n\nexport interface UnnamedTable<\n TableSchema_ extends Schema.Codec<any, any>,\n TableValidator_ extends GenericValidator =\n TableSchemaToTableValidator<TableSchema_>,\n Indexes_ extends GenericTableIndexes = {},\n SearchIndexes_ extends GenericTableSearchIndexes = {},\n VectorIndexes_ extends GenericTableVectorIndexes = {},\n> {\n <const Name_ extends string>(\n tableName: Name_,\n ): Table<\n Name_,\n TableSchema_,\n TableValidator_,\n Indexes_,\n SearchIndexes_,\n VectorIndexes_\n >;\n\n readonly [TypeId]: TypeId;\n readonly indexes: Indexes_;\n readonly searchIndexes: SearchIndexes_;\n readonly vectorIndexes: VectorIndexes_;\n readonly \"~TableValidator\": TableValidator_;\n\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<TableValidator_>,\n RestFieldPaths extends ExtractFieldPaths<TableValidator_>[],\n >(\n name: IndexName,\n fields: [FirstFieldPath, ...RestFieldPaths],\n ): UnnamedTable<\n TableSchema_,\n TableValidator_,\n Expand<\n Indexes_ &\n Record<\n IndexName,\n [FirstFieldPath, ...RestFieldPaths, IndexTiebreakerField]\n >\n >,\n SearchIndexes_,\n VectorIndexes_\n >;\n\n searchIndex<\n IndexName extends string,\n SearchField extends ExtractFieldPaths<TableValidator_>,\n FilterFields extends ExtractFieldPaths<TableValidator_> = never,\n >(\n name: IndexName,\n indexConfig: Expand<SearchIndexConfig<SearchField, FilterFields>>,\n ): UnnamedTable<\n TableSchema_,\n TableValidator_,\n Indexes_,\n Expand<\n SearchIndexes_ &\n Record<\n IndexName,\n {\n searchField: SearchField;\n filterFields: FilterFields;\n }\n >\n >,\n VectorIndexes_\n >;\n\n vectorIndex<\n IndexName extends string,\n VectorField extends ExtractFieldPaths<TableValidator_>,\n FilterFields extends ExtractFieldPaths<TableValidator_> = never,\n >(\n name: IndexName,\n indexConfig: Expand<VectorIndexConfig<VectorField, FilterFields>>,\n ): UnnamedTable<\n TableSchema_,\n TableValidator_,\n Indexes_,\n SearchIndexes_,\n Expand<\n VectorIndexes_ &\n Record<\n IndexName,\n {\n vectorField: VectorField;\n dimensions: number;\n filterFields: FilterFields;\n }\n >\n >\n >;\n}\n\nexport interface UnnamedAny {\n readonly [TypeId]: TypeId;\n}\n\nexport type UnnamedAnyWithProps = UnnamedTable<\n Schema.Codec<any, any>,\n GenericValidator,\n GenericTableIndexes,\n GenericTableSearchIndexes,\n GenericTableVectorIndexes\n>;\n\n// -----------------------------------------------------------------------------\n// Type extractors\n// -----------------------------------------------------------------------------\n\nexport type Name<TableDef extends AnyWithProps> = TableDef[\"tableName\"] &\n string;\n\nexport type TableSchema<TableDef extends AnyWithProps> = TableDef[\"Fields\"];\n\nexport type TableValidator<TableDef extends AnyWithProps> =\n TableDef[\"~TableValidator\"];\n\nexport type Indexes<TableDef extends AnyWithProps> = TableDef[\"indexes\"];\n\nexport type SearchIndexes<TableDef extends AnyWithProps> =\n TableDef[\"searchIndexes\"];\n\nexport type VectorIndexes<TableDef extends AnyWithProps> =\n TableDef[\"vectorIndexes\"];\n\nexport type Doc<TableDef extends AnyWithProps> = TableDef[\"Doc\"];\n\nexport type Fields<TableDef extends AnyWithProps> = TableDef[\"Fields\"];\n\nexport type WithName<\n TableDef extends AnyWithProps,\n Name_ extends string,\n> = TableDef extends { readonly tableName: Name_ } ? TableDef : never;\n\nexport type TablesRecord<Tables extends AnyWithProps> = {\n readonly [TableName_ in Name<Tables>]: WithName<Tables, TableName_>;\n};\n\n// -----------------------------------------------------------------------------\n// Construction\n// -----------------------------------------------------------------------------\n//\n// `make` only stores the user-supplied `lazyFields` callback alongside any\n// chained index metadata. Neither `Fields` nor `Doc` is constructed until\n// first access on a bound `Table`. Each chain step is O(1) (plain object\n// spread of the metadata records) and never invokes the callback. Binding\n// via `unnamed(tableName)` installs lazy memoised getters for `Fields` and\n// `Doc` via `Lazy.defineProperty`, so the first access materialises the\n// value and replaces the getter with a plain data property—second-and-\n// subsequent accesses are observably indistinguishable from a plain\n// property and avoid all function-call overhead.\n\ninterface UnnamedState<\n TableSchema_ extends Schema.Codec<any, any>,\n Indexes_ extends GenericTableIndexes,\n SearchIndexes_ extends GenericTableSearchIndexes,\n VectorIndexes_ extends GenericTableVectorIndexes,\n> {\n readonly lazyFields: () => TableSchema_;\n readonly indexes: Indexes_;\n readonly searchIndexes: SearchIndexes_;\n readonly vectorIndexes: VectorIndexes_;\n}\n\nconst makeBound = <\n Name_ extends string,\n TableSchema_ extends Schema.Codec<any, any>,\n TableValidator_ extends Validator<any, any, any>,\n Indexes_ extends GenericTableIndexes,\n SearchIndexes_ extends GenericTableSearchIndexes,\n VectorIndexes_ extends GenericTableVectorIndexes,\n>(\n tableName: Name_,\n state: UnnamedState<TableSchema_, Indexes_, SearchIndexes_, VectorIndexes_>,\n): Table<\n Name_,\n TableSchema_,\n TableValidator_,\n Indexes_,\n SearchIndexes_,\n VectorIndexes_\n> => {\n const bound = {\n [TypeId]: TypeId as TypeId,\n tableName,\n indexes: state.indexes,\n searchIndexes: state.searchIndexes,\n vectorIndexes: state.vectorIndexes,\n } as Table<\n Name_,\n TableSchema_,\n TableValidator_,\n Indexes_,\n SearchIndexes_,\n VectorIndexes_\n >;\n\n Lazy.defineProperty(bound, \"Fields\", () => state.lazyFields());\n\n Lazy.defineProperty(bound, \"Doc\", () =>\n SystemFields.extendWithSystemFields(\n tableName,\n (bound as { Fields: TableSchema_ }).Fields,\n ),\n );\n\n return bound;\n};\n\nconst makeUnnamed = <\n TableSchema_ extends Schema.Codec<any, any>,\n TableValidator_ extends Validator<any, any, any>,\n Indexes_ extends GenericTableIndexes,\n SearchIndexes_ extends GenericTableSearchIndexes,\n VectorIndexes_ extends GenericTableVectorIndexes,\n>(\n state: UnnamedState<TableSchema_, Indexes_, SearchIndexes_, VectorIndexes_>,\n): UnnamedTable<\n TableSchema_,\n TableValidator_,\n Indexes_,\n SearchIndexes_,\n VectorIndexes_\n> => {\n type UnnamedTable_ = UnnamedTable<\n TableSchema_,\n TableValidator_,\n Indexes_,\n SearchIndexes_,\n VectorIndexes_\n >;\n\n type UnnamedTableFunction<FunctionName extends keyof UnnamedTable_> =\n UnnamedTable_[FunctionName];\n\n const bind = <const Name_ extends string>(\n tableName: Name_,\n ): Table<\n Name_,\n TableSchema_,\n TableValidator_,\n Indexes_,\n SearchIndexes_,\n VectorIndexes_\n > =>\n makeBound<\n Name_,\n TableSchema_,\n TableValidator_,\n Indexes_,\n SearchIndexes_,\n VectorIndexes_\n >(tableName, state);\n\n const index: UnnamedTableFunction<\"index\"> = (name, fields) =>\n makeUnnamed({\n lazyFields: state.lazyFields,\n indexes: {\n ...state.indexes,\n [name]: fields,\n } as any,\n searchIndexes: state.searchIndexes,\n vectorIndexes: state.vectorIndexes,\n });\n\n const searchIndex: UnnamedTableFunction<\"searchIndex\"> = (\n name,\n indexConfig,\n ) =>\n makeUnnamed({\n lazyFields: state.lazyFields,\n indexes: state.indexes,\n searchIndexes: {\n ...state.searchIndexes,\n [name]: indexConfig,\n } as any,\n vectorIndexes: state.vectorIndexes,\n });\n\n const vectorIndex: UnnamedTableFunction<\"vectorIndex\"> = (\n name,\n indexConfig,\n ) =>\n makeUnnamed({\n lazyFields: state.lazyFields,\n indexes: state.indexes,\n searchIndexes: state.searchIndexes,\n vectorIndexes: {\n ...state.vectorIndexes,\n [name]: indexConfig,\n } as any,\n });\n\n return Object.assign(bind, {\n [TypeId]: TypeId as TypeId,\n indexes: state.indexes,\n searchIndexes: state.searchIndexes,\n vectorIndexes: state.vectorIndexes,\n index,\n searchIndex,\n vectorIndex,\n }) as UnnamedTable_;\n};\n\nexport const make = <const TableSchema_ extends Schema.Codec<any, any>>(\n lazyFields: () => TableSchema_,\n): UnnamedTable<TableSchema_, TableSchemaToTableValidator<TableSchema_>> => {\n type TableValidator_ = TableSchemaToTableValidator<TableSchema_>;\n type UnnamedTable_ = UnnamedTable<TableSchema_, TableValidator_>;\n\n return makeUnnamed<TableSchema_, TableValidator_, {}, {}, {}>({\n lazyFields,\n indexes: {},\n searchIndexes: {},\n vectorIndexes: {},\n }) as UnnamedTable_;\n};\n\n// Vendored types from convex-js, partially modified. Ideally we could use these directly. See https://github.com/get-convex/convex-js/pull/14\n\n/**\n * Extract all of the index field paths within a Convex `Validator`.\n *\n * This is used when declaring table indexes.\n * @public\n */\ntype ExtractFieldPaths<T extends Validator<any, any, any>> =\n // Add in the system fields available in index definitions.\n // This should be everything except for `_id` because thats added to indexes\n // automatically.\n T[\"fieldPaths\"] | keyof ConvexSystemFields;\n"],"mappings":";;;;;;;;;;;AAiBA,MAAa,SAAS;AActB,MAAa,WAAW,MACtB,UAAU,YAAY,GAAA,sBAAS,KAAK,UAAU,YAAY,GAAG,WAAW;AAE1E,MAAa,kBAAkB,MAC7B,UAAU,YAAY,GAAA,sBAAS,KAAK,CAAC,UAAU,YAAY,GAAG,WAAW;AAgO3E,MAAM,aAQJ,WACA,UAQG;CACH,MAAM,QAAQ;GACX,SAAS;EACV;EACA,SAAS,MAAM;EACf,eAAe,MAAM;EACrB,eAAe,MAAM;CACvB;CASA,eAAoB,OAAO,gBAAgB,MAAM,WAAW,CAAC;CAE7D,eAAoB,OAAO,aACzBA,uBACE,WACC,MAAmC,MACtC,CACF;CAEA,OAAO;AACT;AAEA,MAAM,eAOJ,UAOG;CAYH,MAAM,QACJ,cASA,UAOE,WAAW,KAAK;CAEpB,MAAM,SAAwC,MAAM,WAClD,YAAY;EACV,YAAY,MAAM;EAClB,SAAS;GACP,GAAG,MAAM;IACR,OAAO;EACV;EACA,eAAe,MAAM;EACrB,eAAe,MAAM;CACvB,CAAC;CAEH,MAAM,eACJ,MACA,gBAEA,YAAY;EACV,YAAY,MAAM;EAClB,SAAS,MAAM;EACf,eAAe;GACb,GAAG,MAAM;IACR,OAAO;EACV;EACA,eAAe,MAAM;CACvB,CAAC;CAEH,MAAM,eACJ,MACA,gBAEA,YAAY;EACV,YAAY,MAAM;EAClB,SAAS,MAAM;EACf,eAAe,MAAM;EACrB,eAAe;GACb,GAAG,MAAM;IACR,OAAO;EACV;CACF,CAAC;CAEH,OAAO,OAAO,OAAO,MAAM;GACxB,SAAS;EACV,SAAS,MAAM;EACf,eAAe,MAAM;EACrB,eAAe,MAAM;EACrB;EACA;EACA;CACF,CAAC;AACH;AAEA,MAAa,QACX,eAC0E;CAI1E,OAAO,YAAuD;EAC5D;EACA,SAAS,CAAC;EACV,eAAe,CAAC;EAChB,eAAe,CAAC;CAClB,CAAC;AACH"}
|
package/dist/index.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ export * as GroupPath from "./GroupPath";
|
|
|
5
5
|
export * as GroupSpec from "./GroupSpec";
|
|
6
6
|
export * as Identifier from "./Identifier";
|
|
7
7
|
export * as Lazy from "./Lazy";
|
|
8
|
+
export * as MiddlewareAttachment from "./MiddlewareAttachment";
|
|
8
9
|
export * as MiddlewareSpec from "./MiddlewareSpec";
|
|
9
10
|
export * as PaginationError from "./PaginationError";
|
|
10
11
|
export * as PaginationOptions from "./PaginationOptions";
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,kBAAkB,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,YAAY,MAAM,gBAAgB,CAAC;AAC/C,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,UAAU,MAAM,cAAc,CAAC;AAC3C,OAAO,K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D,OAAO,KAAK,GAAG,MAAM,OAAO,CAAC;AAC7B,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAC;AAC/B,OAAO,KAAK,sBAAsB,MAAM,0BAA0B,CAAC;AACnE,OAAO,KAAK,iBAAiB,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAC;AAC/B,OAAO,KAAK,YAAY,MAAM,gBAAgB,CAAC;AAC/C,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC;AACjC,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC;AACjC,OAAO,KAAK,YAAY,MAAM,gBAAgB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -7,6 +7,7 @@ import { RuntimeAndFunctionType_exports } from "./RuntimeAndFunctionType.js";
|
|
|
7
7
|
import { FunctionSpec_exports } from "./FunctionSpec.js";
|
|
8
8
|
import { GenericId_exports } from "./GenericId.js";
|
|
9
9
|
import { GroupPath_exports } from "./GroupPath.js";
|
|
10
|
+
import { MiddlewareAttachment_exports } from "./MiddlewareAttachment.js";
|
|
10
11
|
import { GroupSpec_exports } from "./GroupSpec.js";
|
|
11
12
|
import { MiddlewareSpec_exports } from "./MiddlewareSpec.js";
|
|
12
13
|
import { PaginationError_exports } from "./PaginationError.js";
|
|
@@ -18,4 +19,4 @@ import { SystemFields_exports } from "./SystemFields.js";
|
|
|
18
19
|
import { Table_exports } from "./Table.js";
|
|
19
20
|
import { Types_exports } from "./Types.js";
|
|
20
21
|
import { UserIdentity_exports } from "./UserIdentity.js";
|
|
21
|
-
export { FunctionProvenance_exports as FunctionProvenance, FunctionSpec_exports as FunctionSpec, GenericId_exports as GenericId, GroupPath_exports as GroupPath, GroupSpec_exports as GroupSpec, Identifier_exports as Identifier, Lazy_exports as Lazy, MiddlewareSpec_exports as MiddlewareSpec, PaginationError_exports as PaginationError, PaginationOptions_exports as PaginationOptions, PaginationResult_exports as PaginationResult, Ref_exports as Ref, Refs_exports as Refs, RuntimeAndFunctionType_exports as RuntimeAndFunctionType, SchemaToValidator_exports as SchemaToValidator, Spec_exports as Spec, SystemFields_exports as SystemFields, Table_exports as Table, Types_exports as Types, UserIdentity_exports as UserIdentity };
|
|
22
|
+
export { FunctionProvenance_exports as FunctionProvenance, FunctionSpec_exports as FunctionSpec, GenericId_exports as GenericId, GroupPath_exports as GroupPath, GroupSpec_exports as GroupSpec, Identifier_exports as Identifier, Lazy_exports as Lazy, MiddlewareAttachment_exports as MiddlewareAttachment, MiddlewareSpec_exports as MiddlewareSpec, PaginationError_exports as PaginationError, PaginationOptions_exports as PaginationOptions, PaginationResult_exports as PaginationResult, Ref_exports as Ref, Refs_exports as Refs, RuntimeAndFunctionType_exports as RuntimeAndFunctionType, SchemaToValidator_exports as SchemaToValidator, Spec_exports as Spec, SystemFields_exports as SystemFields, Table_exports as Table, Types_exports as Types, UserIdentity_exports as UserIdentity };
|
package/package.json
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@confect/core",
|
|
3
3
|
"description": "Shared specs and schemas used by all Confect packages",
|
|
4
|
-
"version": "10.0.0-next.
|
|
4
|
+
"version": "10.0.0-next.22",
|
|
5
5
|
"author": "RJ Dellecese",
|
|
6
6
|
"bugs": {
|
|
7
7
|
"url": "https://github.com/rjdellecese/confect/issues"
|
|
8
8
|
},
|
|
9
9
|
"devDependencies": {
|
|
10
|
-
"@effect/vitest": "4.0.0-rc.
|
|
11
|
-
"@types/node": "
|
|
12
|
-
"
|
|
13
|
-
"
|
|
14
|
-
"
|
|
10
|
+
"@effect/vitest": "4.0.0-rc.115",
|
|
11
|
+
"@types/node": "24.13.3",
|
|
12
|
+
"confect-bench-harness": "0.0.0",
|
|
13
|
+
"effect": "4.0.0-rc.115",
|
|
14
|
+
"tsdown": "0.23.0",
|
|
15
|
+
"tsx": "4.23.13",
|
|
15
16
|
"typescript": "7.0.2",
|
|
16
17
|
"unrun": "0.3.1",
|
|
17
|
-
"vitest": "
|
|
18
|
-
"confect-bench-harness": "0.0.0"
|
|
18
|
+
"vitest": "5.0.0"
|
|
19
19
|
},
|
|
20
20
|
"engines": {
|
|
21
|
-
"node": ">=
|
|
21
|
+
"node": ">=24"
|
|
22
22
|
},
|
|
23
23
|
"exports": {
|
|
24
24
|
".": {
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
"module": "./dist/index.js",
|
|
52
52
|
"peerDependencies": {
|
|
53
53
|
"convex": "^1.32.0",
|
|
54
|
-
"effect": "^4.0.0-rc.
|
|
54
|
+
"effect": "^4.0.0-rc.115"
|
|
55
55
|
},
|
|
56
56
|
"repository": {
|
|
57
57
|
"type": "git",
|
|
@@ -10,7 +10,6 @@ import * as PaginationResult from "./PaginationResult";
|
|
|
10
10
|
* context-free codec means the struct assembled from the fields can always be
|
|
11
11
|
* encoded and decoded synchronously at a Convex boundary.
|
|
12
12
|
*/
|
|
13
|
-
// eslint-disable-next-line import/namespace -- oxlint's namespace resolution misses type-only exports, and `Schema` is an interface/namespace
|
|
14
13
|
export type ArgsFields = {
|
|
15
14
|
readonly [key: PropertyKey]: Schema.ConstraintCodec<any, any>;
|
|
16
15
|
};
|
|
@@ -45,7 +44,7 @@ export type FunctionProvenance = Data.TaggedEnum<{
|
|
|
45
44
|
}>;
|
|
46
45
|
|
|
47
46
|
/**
|
|
48
|
-
* The declaration shape of a Confect function
|
|
47
|
+
* The declaration shape of a Confect function—orthogonal to both the
|
|
49
48
|
* provenance origin (Confect vs Convex) and the function type
|
|
50
49
|
* (query/mutation/action). A `Standard` function declares its args fields and
|
|
51
50
|
* returns schema directly; a `Paginated` function declares user-args fields
|
|
@@ -63,11 +62,11 @@ export interface Paginated<
|
|
|
63
62
|
Item extends Schema.Codec<any, any> = Schema.Codec<any, any>,
|
|
64
63
|
> {
|
|
65
64
|
readonly _tag: "Paginated";
|
|
66
|
-
/** User-declared args
|
|
65
|
+
/** User-declared args—no `paginationOpts`. */
|
|
67
66
|
readonly userArgs: ArgsSchema<UserArgsFields_>;
|
|
68
67
|
/** Page element schema. */
|
|
69
68
|
readonly item: Item;
|
|
70
|
-
/** Mutable array of items
|
|
69
|
+
/** Mutable array of items—the page decode target. */
|
|
71
70
|
readonly page: Schema.Codec<any, any>;
|
|
72
71
|
}
|
|
73
72
|
|
|
@@ -110,8 +109,7 @@ const Standard: Standard = { _tag: "Standard" };
|
|
|
110
109
|
* `args`, `returns`, and `error` are exposed as sync lazy memoised getters
|
|
111
110
|
* (via {@link Lazy.defineProperty}) that only evaluate their thunk on first
|
|
112
111
|
* access, mirroring how `Table` defers `Fields`/`Doc`. This keeps importing the
|
|
113
|
-
* assembled `_generated/spec.ts` cheap
|
|
114
|
-
* `Schema.Array(...)` work runs at module load; it is deferred to the first
|
|
112
|
+
* assembled `_generated/spec.ts` cheap—no `Schema.Struct(...)`/`Schema.Array(...)` work runs at module load; it is deferred to the first
|
|
115
113
|
* invocation that actually compiles validators or runs a codec.
|
|
116
114
|
*
|
|
117
115
|
* The object is built by hand rather than through `FunctionProvenance.Confect`
|
|
@@ -185,7 +183,7 @@ export interface AnyConfectPaginated extends AnyConfect {
|
|
|
185
183
|
/**
|
|
186
184
|
* Build the provenance of a paginated query from lazy schema thunks, with the
|
|
187
185
|
* same laziness contract as {@link Confect}. The user-facing schemas live on
|
|
188
|
-
* the `Paginated` kind (`kind.userArgs`, `kind.item`, `kind.page`)
|
|
186
|
+
* the `Paginated` kind (`kind.userArgs`, `kind.item`, `kind.page`)—the kind
|
|
189
187
|
* container is built eagerly (it is cheap) while the schemas inside it stay
|
|
190
188
|
* lazy. The composed Convex-facing `args`/`returns` are derived lazily from
|
|
191
189
|
* them: `args` spreads the user fields plus `paginationOpts`, and `returns`
|
|
@@ -217,7 +215,7 @@ export const ConfectPaginated = <
|
|
|
217
215
|
const fields = paginatedKind.userArgs.fields;
|
|
218
216
|
if ("paginationOpts" in fields) {
|
|
219
217
|
throw new globalThis.Error(
|
|
220
|
-
"A paginated query's args schema must not declare `paginationOpts
|
|
218
|
+
"A paginated query's args schema must not declare `paginationOpts`—" +
|
|
221
219
|
"it is added automatically from the `PaginationOptions` schema",
|
|
222
220
|
);
|
|
223
221
|
}
|
package/src/FunctionSpec.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type * as MiddlewareAttachment from "./MiddlewareAttachment";
|
|
1
2
|
import type {
|
|
2
3
|
DefaultFunctionArgs,
|
|
3
4
|
FunctionType,
|
|
@@ -32,6 +33,9 @@ export interface FunctionSpec<
|
|
|
32
33
|
readonly name: Name_;
|
|
33
34
|
readonly functionProvenance: FunctionProvenance_;
|
|
34
35
|
readonly middlewareSpecs: ReadonlyArray<MiddlewareSpecs_>;
|
|
36
|
+
readonly middlewareAttachments: ReadonlyArray<
|
|
37
|
+
MiddlewareAttachment.MiddlewareAttachment<MiddlewareSpecs_>
|
|
38
|
+
>;
|
|
35
39
|
}
|
|
36
40
|
|
|
37
41
|
export interface Builder<
|
|
@@ -55,6 +59,7 @@ export interface Builder<
|
|
|
55
59
|
FunctionProvenance_,
|
|
56
60
|
MiddlewareSpecs_
|
|
57
61
|
>,
|
|
62
|
+
...options: MiddlewareAttachment.Args<NoInfer<MiddlewareSpec_>>
|
|
58
63
|
): Builder<
|
|
59
64
|
RuntimeAndFunctionType_,
|
|
60
65
|
FunctionVisibility_,
|
|
@@ -282,9 +287,14 @@ export type WithoutName<
|
|
|
282
287
|
const Proto = {
|
|
283
288
|
[TypeId]: TypeId,
|
|
284
289
|
|
|
290
|
+
get middlewareSpecs() {
|
|
291
|
+
return this.middlewareAttachments.map(({ spec }) => spec);
|
|
292
|
+
},
|
|
293
|
+
|
|
285
294
|
middleware(
|
|
286
295
|
this: AnyWithProps,
|
|
287
296
|
middlewareSpec: MiddlewareSpec.AnyMiddlewareSpec,
|
|
297
|
+
...options: ReadonlyArray<unknown>
|
|
288
298
|
) {
|
|
289
299
|
if (this.functionProvenance._tag === "Convex") {
|
|
290
300
|
throw new Error(
|
|
@@ -298,8 +308,9 @@ const Proto = {
|
|
|
298
308
|
);
|
|
299
309
|
}
|
|
300
310
|
if (
|
|
301
|
-
|
|
302
|
-
|
|
311
|
+
!("options" in middlewareSpec) &&
|
|
312
|
+
this.middlewareAttachments.some(
|
|
313
|
+
({ spec }) => spec.key === middlewareSpec.key,
|
|
303
314
|
)
|
|
304
315
|
) {
|
|
305
316
|
throw new Error(
|
|
@@ -312,10 +323,13 @@ const Proto = {
|
|
|
312
323
|
functionVisibility: this.functionVisibility,
|
|
313
324
|
name: this.name,
|
|
314
325
|
functionProvenance: this.functionProvenance,
|
|
315
|
-
|
|
326
|
+
middlewareAttachments: [
|
|
327
|
+
...this.middlewareAttachments,
|
|
328
|
+
{ spec: middlewareSpec, options: options[0] },
|
|
329
|
+
],
|
|
316
330
|
});
|
|
317
331
|
},
|
|
318
|
-
}
|
|
332
|
+
} satisfies ThisType<AnyWithProps>;
|
|
319
333
|
|
|
320
334
|
interface Options {
|
|
321
335
|
readonly name: string;
|
|
@@ -373,7 +387,7 @@ const make = <
|
|
|
373
387
|
args === undefined
|
|
374
388
|
? FunctionProvenance.Confect(() => ({}), returns, error)
|
|
375
389
|
: FunctionProvenance.Confect(args, returns, error),
|
|
376
|
-
|
|
390
|
+
middlewareAttachments: [],
|
|
377
391
|
});
|
|
378
392
|
}
|
|
379
393
|
|
|
@@ -448,7 +462,7 @@ const makePaginated = <
|
|
|
448
462
|
args === undefined
|
|
449
463
|
? FunctionProvenance.ConfectPaginated(() => ({}), item, error)
|
|
450
464
|
: FunctionProvenance.ConfectPaginated(args, item, error),
|
|
451
|
-
|
|
465
|
+
middlewareAttachments: [],
|
|
452
466
|
});
|
|
453
467
|
}
|
|
454
468
|
|
|
@@ -562,7 +576,7 @@ const makeConvex =
|
|
|
562
576
|
ExtractArgs<F>,
|
|
563
577
|
ExtractReturns<F>
|
|
564
578
|
>(),
|
|
565
|
-
|
|
579
|
+
middlewareAttachments: [],
|
|
566
580
|
}) as any;
|
|
567
581
|
};
|
|
568
582
|
|