diff --git a/crates/bindings-typescript/examples/quickstart-chat/src/App.tsx b/crates/bindings-typescript/examples/quickstart-chat/src/App.tsx index 78ae2da57a0..a6cf1f2751c 100644 --- a/crates/bindings-typescript/examples/quickstart-chat/src/App.tsx +++ b/crates/bindings-typescript/examples/quickstart-chat/src/App.tsx @@ -16,8 +16,9 @@ function App() { const [settingName, setSettingName] = useState(false); const [systemMessages, setSystemMessages] = useState([] as Message[]); const [newMessage, setNewMessage] = useState(''); - const conn = useSpacetimeDB(); + + conn.setReducerFlags(); const { identity, isActive: connected } = conn; // Subscribe to all messages in the chat diff --git a/crates/bindings-typescript/examples/quickstart-chat/src/module_bindings/index.ts b/crates/bindings-typescript/examples/quickstart-chat/src/module_bindings/index.ts index 89a6af89230..f74aad067dc 100644 --- a/crates/bindings-typescript/examples/quickstart-chat/src/module_bindings/index.ts +++ b/crates/bindings-typescript/examples/quickstart-chat/src/module_bindings/index.ts @@ -61,9 +61,9 @@ const REMOTE_MODULE = { user: { tableName: 'user' as const, rowType: User.getTypeScriptAlgebraicType(), - primaryKey: 'identity', + primaryKey: 'identity' as const, primaryKeyInfo: { - colName: 'identity', + colName: 'identity' as const, colType: ( User.getTypeScriptAlgebraicType() as __AlgebraicTypeVariants.Product ).value.elements[0].algebraicType, @@ -119,7 +119,7 @@ const REMOTE_MODULE = { setReducerFlagsConstructor: () => { return new SetReducerFlags(); }, -}; +} satisfies RemoteModule; // A type representing all the possible variants of a reducer. export type Reducer = diff --git a/crates/bindings-typescript/examples/quickstart-chat/src/module_bindings/user_table.ts b/crates/bindings-typescript/examples/quickstart-chat/src/module_bindings/user_table.ts index 85687a99eff..61c82b8de12 100644 --- a/crates/bindings-typescript/examples/quickstart-chat/src/module_bindings/user_table.ts +++ b/crates/bindings-typescript/examples/quickstart-chat/src/module_bindings/user_table.ts @@ -46,9 +46,9 @@ declare type __keep = [EventContext, Reducer, RemoteReducers, RemoteTables]; * but to directly chain method calls, * like `ctx.db.user.on_insert(...)`. */ -export class UserTableHandle - implements __TableHandle -{ +export class UserTableHandle< + TableName extends string, +> extends ClientTable { // phantom type to track the table name readonly tableName!: TableName; tableCache: __TableCache; @@ -76,11 +76,11 @@ export class UserTableHandle * Get a handle on the `identity` unique index on the table `user`. */ identity = { - // Find the subscribed row whose `identity` column value is equal to `col_val`, + // Find the subscribed row whose `identity` column value is equal to `colVal`, // if such a row is present in the client cache. - find: (col_val: __Identity): User | undefined => { + find: (colVal: __Identity): User | undefined => { for (let row of this.tableCache.iter()) { - if (__deepEqual(row.identity, col_val)) { + if (__deepEqual(row.identity, colVal)) { return row; } } diff --git a/crates/bindings-typescript/src/index.ts b/crates/bindings-typescript/src/index.ts index 5204fe0b972..6e8c97d64e7 100644 --- a/crates/bindings-typescript/src/index.ts +++ b/crates/bindings-typescript/src/index.ts @@ -6,7 +6,7 @@ export { default as BinaryWriter } from './lib/binary_writer'; export * from './lib/schedule_at'; export * from './lib/time_duration'; export * from './lib/timestamp'; -export * from './lib/utils'; +export * from './lib/util'; export * from './lib/identity'; export * from './lib/option'; export * from './sdk'; diff --git a/crates/bindings-typescript/src/lib/algebraic_type.ts b/crates/bindings-typescript/src/lib/algebraic_type.ts index d7af713abac..2f8b4bdbba3 100644 --- a/crates/bindings-typescript/src/lib/algebraic_type.ts +++ b/crates/bindings-typescript/src/lib/algebraic_type.ts @@ -4,21 +4,15 @@ import { ConnectionId } from './connection_id'; import type BinaryReader from './binary_reader'; import BinaryWriter from './binary_writer'; import { Identity } from './identity'; -import { Option } from './option'; -import { - AlgebraicType as AlgebraicTypeType, - AlgebraicType as AlgebraicTypeValue, -} from './autogen/algebraic_type_type'; -import { - type ProductType as ProductTypeType, - ProductType as ProductTypeValue, -} from './autogen/product_type_type'; -import { - type SumType as SumTypeType, - SumType as SumTypeValue, -} from './autogen/sum_type_type'; -import ScheduleAt from './schedule_at'; -import type Typespace from './autogen/typespace_type'; +import * as AlgebraicTypeVariants from './algebraic_type_variants'; + +type TypespaceType = { + types: AlgebraicTypeType[]; +}; + +export type ProductTypeType = { + elements: ProductTypeElement[]; +}; /** * A factor / element of a product type. @@ -28,7 +22,14 @@ import type Typespace from './autogen/typespace_type'; * NOTE: Each element has an implicit element tag based on its order. * Uniquely identifies an element similarly to protobuf tags. */ -export * from './autogen/product_type_element_type'; +export type ProductTypeElement = { + name: string | undefined; + algebraicType: AlgebraicTypeType; +}; + +export type SumTypeType = { + variants: SumTypeVariant[]; +}; /** * A variant of a sum type. @@ -36,93 +37,81 @@ export * from './autogen/product_type_element_type'; * NOTE: Each element has an implicit element tag based on its order. * Uniquely identifies an element similarly to protobuf tags. */ -export * from './autogen/sum_type_variant_type'; +export type SumTypeVariant = { + name: string | undefined; + algebraicType: AlgebraicTypeType; +}; -/** - * The variant types of the Algebraic Type tagged union. - */ -export type * as AlgebraicTypeVariants from './autogen/algebraic_type_variants'; +export type AlgebraicTypeType = + | AlgebraicTypeVariants.Ref + | AlgebraicTypeVariants.Sum + | AlgebraicTypeVariants.Product + | AlgebraicTypeVariants.Array + | AlgebraicTypeVariants.String + | AlgebraicTypeVariants.Bool + | AlgebraicTypeVariants.I8 + | AlgebraicTypeVariants.U8 + | AlgebraicTypeVariants.I16 + | AlgebraicTypeVariants.U16 + | AlgebraicTypeVariants.I32 + | AlgebraicTypeVariants.U32 + | AlgebraicTypeVariants.I64 + | AlgebraicTypeVariants.U64 + | AlgebraicTypeVariants.I128 + | AlgebraicTypeVariants.U128 + | AlgebraicTypeVariants.I256 + | AlgebraicTypeVariants.U256 + | AlgebraicTypeVariants.F32 + | AlgebraicTypeVariants.F64; -/** - * The SpacetimeDB Algebraic Type System (SATS) is a structural type system in - * which a nominal type system can be constructed. - * - * The type system unifies the concepts sum types, product types, and built-in - * primitive types into a single type system. - */ export type AlgebraicType = AlgebraicTypeType; /** - * Algebraic Type utilities. + * The variant types of the Algebraic Type tagged union. */ -export const AlgebraicType: { - Sum(value: T): { tag: 'Sum'; value: T }; - Product(value: T): { tag: 'Product'; value: T }; - Array(value: T): { tag: 'Array'; value: T }; +export { AlgebraicTypeVariants }; - createOptionType(innerType: AlgebraicTypeType): AlgebraicTypeType; - createIdentityType(): AlgebraicTypeType; - createConnectionIdType(): AlgebraicTypeType; - createScheduleAtType(): AlgebraicTypeType; - createTimestampType(): AlgebraicTypeType; - createTimeDurationType(): AlgebraicTypeType; - serializeValue( - writer: BinaryWriter, - ty: AlgebraicTypeType, - value: any, - typespace?: Typespace - ): void; - deserializeValue( - reader: BinaryReader, - ty: AlgebraicTypeType, - typespace?: Typespace - ): any; - /** - * Convert a value of the algebraic type into something that can be used as a key in a map. - * There are no guarantees about being able to order it. - * This is only guaranteed to be comparable to other values of the same type. - * @param value A value of the algebraic type - * @returns Something that can be used as a key in a map. - */ - intoMapKey(ty: AlgebraicTypeType, value: any): ComparablePrimitive; -} & typeof AlgebraicTypeValue = { - ...AlgebraicTypeValue, - Sum: (value: T): { tag: 'Sum'; value: T } => ({ +// A value with helper functions to construct the type. +export const AlgebraicType = { + Ref: (value: number): AlgebraicTypeVariants.Ref => ({ tag: 'Ref', value }), + Sum: (value: T): { tag: 'Sum'; value: T } => ({ tag: 'Sum', value, }), - Product: (value: T): { tag: 'Product'; value: T } => ({ + Product: ( + value: T + ): { tag: 'Product'; value: T } => ({ tag: 'Product', value, }), - Array: (value: T): { tag: 'Array'; value: T } => ({ + Array: ( + value: T + ): { tag: 'Array'; value: T } => ({ tag: 'Array', value, }), - createOptionType: function (innerType: AlgebraicTypeType): AlgebraicTypeType { - return Option.getAlgebraicType(innerType); - }, - createIdentityType: function (): AlgebraicTypeType { - return Identity.getAlgebraicType(); - }, - createConnectionIdType: function (): AlgebraicTypeType { - return ConnectionId.getAlgebraicType(); - }, - createScheduleAtType: function (): AlgebraicTypeType { - return ScheduleAt.getAlgebraicType(); - }, - createTimestampType: function (): AlgebraicTypeType { - return Timestamp.getAlgebraicType(); - }, - createTimeDurationType: function (): AlgebraicTypeType { - return TimeDuration.getAlgebraicType(); - }, - serializeValue: function ( + String: { tag: 'String' } as const, + Bool: { tag: 'Bool' } as const, + I8: { tag: 'I8' } as const, + U8: { tag: 'U8' } as const, + I16: { tag: 'I16' } as const, + U16: { tag: 'U16' } as const, + I32: { tag: 'I32' } as const, + U32: { tag: 'U32' } as const, + I64: { tag: 'I64' } as const, + U64: { tag: 'U64' } as const, + I128: { tag: 'I128' } as const, + U128: { tag: 'U128' } as const, + I256: { tag: 'I256' } as const, + U256: { tag: 'U256' } as const, + F32: { tag: 'F32' } as const, + F64: { tag: 'F64' } as const, + serializeValue( writer: BinaryWriter, ty: AlgebraicTypeType, value: any, - typespace?: Typespace - ): void { + typespace?: TypespaceType + ) { if (ty.tag === 'Ref') { if (!typespace) throw new Error('cannot serialize refs without a typespace'); @@ -199,7 +188,7 @@ export const AlgebraicType: { deserializeValue: function ( reader: BinaryReader, ty: AlgebraicTypeType, - typespace?: Typespace + typespace?: TypespaceType ): any { if (ty.tag === 'Ref') { if (!typespace) @@ -327,26 +316,12 @@ export const AlgebraicType: { */ export type ProductType = ProductTypeType; -export const ProductType: { - serializeValue( - writer: BinaryWriter, - ty: ProductTypeType, - value: any, - typespace?: Typespace - ): void; - deserializeValue( - reader: BinaryReader, - ty: ProductTypeType, - typespace?: Typespace - ): any; - intoMapKey(ty: ProductTypeType, value: any): ComparablePrimitive; -} = { - ...ProductTypeValue, +export const ProductType = { serializeValue( writer: BinaryWriter, ty: ProductTypeType, value: any, - typespace?: Typespace + typespace?: TypespaceType ): void { for (const element of ty.elements) { AlgebraicType.serializeValue( @@ -360,7 +335,7 @@ export const ProductType: { deserializeValue( reader: BinaryReader, ty: ProductTypeType, - typespace?: Typespace + typespace?: TypespaceType ): any { const result: { [key: string]: any } = {}; if (ty.elements.length === 1) { @@ -441,25 +416,12 @@ export type SumType = SumTypeType; * * [structural]: https://en.wikipedia.org/wiki/Structural_type_system */ -export const SumType: { - serializeValue( - writer: BinaryWriter, - ty: SumTypeType, - value: any, - typespace?: Typespace - ): void; - deserializeValue( - reader: BinaryReader, - ty: SumTypeType, - typespace?: Typespace - ): any; -} = { - ...SumTypeValue, +export const SumType = { serializeValue: function ( writer: BinaryWriter, ty: SumTypeType, value: any, - typespace?: Typespace + typespace?: TypespaceType ): void { if ( ty.variants.length == 2 && @@ -495,7 +457,7 @@ export const SumType: { deserializeValue: function ( reader: BinaryReader, ty: SumTypeType, - typespace?: Typespace + typespace?: TypespaceType ): any { const tag = reader.readU8(); // In TypeScript we handle Option values as a special case diff --git a/crates/bindings-typescript/src/lib/algebraic_type_variants.ts b/crates/bindings-typescript/src/lib/algebraic_type_variants.ts new file mode 100644 index 00000000000..5890d53c148 --- /dev/null +++ b/crates/bindings-typescript/src/lib/algebraic_type_variants.ts @@ -0,0 +1,26 @@ +import type { + AlgebraicTypeType, + ProductTypeType, + SumTypeType, +} from './algebraic_type'; + +export type Ref = { tag: 'Ref'; value: number }; +export type Sum = { tag: 'Sum'; value: SumTypeType }; +export type Product = { tag: 'Product'; value: ProductTypeType }; +export type Array = { tag: 'Array'; value: AlgebraicTypeType }; +export type String = { tag: 'String' }; +export type Bool = { tag: 'Bool' }; +export type I8 = { tag: 'I8' }; +export type U8 = { tag: 'U8' }; +export type I16 = { tag: 'I16' }; +export type U16 = { tag: 'U16' }; +export type I32 = { tag: 'I32' }; +export type U32 = { tag: 'U32' }; +export type I64 = { tag: 'I64' }; +export type U64 = { tag: 'U64' }; +export type I128 = { tag: 'I128' }; +export type U128 = { tag: 'U128' }; +export type I256 = { tag: 'I256' }; +export type U256 = { tag: 'U256' }; +export type F32 = { tag: 'F32' }; +export type F64 = { tag: 'F64' }; diff --git a/crates/bindings-typescript/src/lib/autogen/algebraic_type_type.ts b/crates/bindings-typescript/src/lib/autogen/algebraic_type_type.ts index fcbc92cd34c..3fe9bb3bbe1 100644 --- a/crates/bindings-typescript/src/lib/autogen/algebraic_type_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/algebraic_type_type.ts @@ -4,186 +4,43 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { SumType } from './sum_type_type'; -// Mark import as potentially unused -declare type __keep_SumType = SumType; -import { ProductType } from './product_type_type'; -// Mark import as potentially unused -declare type __keep_ProductType = ProductType; - -import * as AlgebraicTypeVariants from './algebraic_type_variants'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import SumType from './sum_type_type'; +import ProductType from './product_type_type'; // The tagged union or sum type for the algebraic type `AlgebraicType`. -export type AlgebraicType = - | AlgebraicTypeVariants.Ref - | AlgebraicTypeVariants.Sum - | AlgebraicTypeVariants.Product - | AlgebraicTypeVariants.Array - | AlgebraicTypeVariants.String - | AlgebraicTypeVariants.Bool - | AlgebraicTypeVariants.I8 - | AlgebraicTypeVariants.U8 - | AlgebraicTypeVariants.I16 - | AlgebraicTypeVariants.U16 - | AlgebraicTypeVariants.I32 - | AlgebraicTypeVariants.U32 - | AlgebraicTypeVariants.I64 - | AlgebraicTypeVariants.U64 - | AlgebraicTypeVariants.I128 - | AlgebraicTypeVariants.U128 - | AlgebraicTypeVariants.I256 - | AlgebraicTypeVariants.U256 - | AlgebraicTypeVariants.F32 - | AlgebraicTypeVariants.F64; - -let _cached_AlgebraicType_type_value: __AlgebraicTypeType | null = null; - -// A value with helper functions to construct the type. -export const AlgebraicType = { - // Helper functions for constructing each variant of the tagged union. - // ``` - // const foo = Foo.A(42); - // assert!(foo.tag === "A"); - // assert!(foo.value === 42); - // ``` - Ref: (value: number): AlgebraicTypeVariants.Ref => ({ tag: 'Ref', value }), - Sum: (value: SumType): AlgebraicTypeVariants.Sum => ({ tag: 'Sum', value }), - Product: (value: ProductType): AlgebraicTypeVariants.Product => ({ - tag: 'Product', - value, - }), - Array: (value: AlgebraicType): AlgebraicTypeVariants.Array => ({ - tag: 'Array', - value, - }), - String: { tag: 'String' } as const, - Bool: { tag: 'Bool' } as const, - I8: { tag: 'I8' } as const, - U8: { tag: 'U8' } as const, - I16: { tag: 'I16' } as const, - U16: { tag: 'U16' } as const, - I32: { tag: 'I32' } as const, - U32: { tag: 'U32' } as const, - I64: { tag: 'I64' } as const, - U64: { tag: 'U64' } as const, - I128: { tag: 'I128' } as const, - U128: { tag: 'U128' } as const, - I256: { tag: 'I256' } as const, - U256: { tag: 'U256' } as const, - F32: { tag: 'F32' } as const, - F64: { tag: 'F64' } as const, - - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_AlgebraicType_type_value) - return _cached_AlgebraicType_type_value; - _cached_AlgebraicType_type_value = __AlgebraicTypeValue.Sum({ - variants: [], - }); - _cached_AlgebraicType_type_value.value.variants.push( - { name: 'Ref', algebraicType: __AlgebraicTypeValue.U32 }, - { name: 'Sum', algebraicType: SumType.getTypeScriptAlgebraicType() }, - { - name: 'Product', - algebraicType: ProductType.getTypeScriptAlgebraicType(), - }, - { - name: 'Array', - algebraicType: AlgebraicType.getTypeScriptAlgebraicType(), - }, - { - name: 'String', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'Bool', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'I8', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'U8', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'I16', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'U16', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'I32', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'U32', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'I64', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'U64', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'I128', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'U128', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'I256', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'U256', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'F32', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'F64', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - } - ); - return _cached_AlgebraicType_type_value; - }, - - serialize(writer: __BinaryWriter, value: AlgebraicType): void { - __AlgebraicTypeValue.serializeValue( - writer, - AlgebraicType.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): AlgebraicType { - return __AlgebraicTypeValue.deserializeValue( - reader, - AlgebraicType.getTypeScriptAlgebraicType() - ); - }, -}; +const AlgebraicType: __TypeBuilder<__AlgebraicTypeType, __AlgebraicTypeType> = + __t.enum('AlgebraicType', { + Ref: __t.u32(), + get Sum() { + return SumType; + }, + get Product() { + return ProductType; + }, + get Array() { + return AlgebraicType; + }, + String: __t.unit(), + Bool: __t.unit(), + I8: __t.unit(), + U8: __t.unit(), + I16: __t.unit(), + U16: __t.unit(), + I32: __t.unit(), + U32: __t.unit(), + I64: __t.unit(), + U64: __t.unit(), + I128: __t.unit(), + U128: __t.unit(), + I256: __t.unit(), + U256: __t.unit(), + F32: __t.unit(), + F64: __t.unit(), + }); export default AlgebraicType; diff --git a/crates/bindings-typescript/src/lib/autogen/algebraic_type_variants.ts b/crates/bindings-typescript/src/lib/autogen/algebraic_type_variants.ts deleted file mode 100644 index e92c84b2140..00000000000 --- a/crates/bindings-typescript/src/lib/autogen/algebraic_type_variants.ts +++ /dev/null @@ -1,48 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -/* eslint-disable */ -/* tslint:disable */ -import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { AlgebraicType as AlgebraicTypeType } from './algebraic_type_type'; -// Mark import as potentially unused -declare type __keep_AlgebraicTypeType = AlgebraicTypeType; -import { SumType as SumTypeType } from './sum_type_type'; -// Mark import as potentially unused -declare type __keep_SumTypeType = SumTypeType; -import { ProductType as ProductTypeType } from './product_type_type'; -// Mark import as potentially unused -declare type __keep_ProductTypeType = ProductTypeType; - -export type Ref = { tag: 'Ref'; value: number }; -export type Sum = { tag: 'Sum'; value: SumTypeType }; -export type Product = { tag: 'Product'; value: ProductTypeType }; -export type Array = { tag: 'Array'; value: AlgebraicTypeType }; -export type String = { tag: 'String' }; -export type Bool = { tag: 'Bool' }; -export type I8 = { tag: 'I8' }; -export type U8 = { tag: 'U8' }; -export type I16 = { tag: 'I16' }; -export type U16 = { tag: 'U16' }; -export type I32 = { tag: 'I32' }; -export type U32 = { tag: 'U32' }; -export type I64 = { tag: 'I64' }; -export type U64 = { tag: 'U64' }; -export type I128 = { tag: 'I128' }; -export type U128 = { tag: 'U128' }; -export type I256 = { tag: 'I256' }; -export type U256 = { tag: 'U256' }; -export type F32 = { tag: 'F32' }; -export type F64 = { tag: 'F64' }; diff --git a/crates/bindings-typescript/src/lib/autogen/index_type_type.ts b/crates/bindings-typescript/src/lib/autogen/index_type_type.ts index 691424a1d7b..4bcfdb5933a 100644 --- a/crates/bindings-typescript/src/lib/autogen/index_type_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/index_type_type.ts @@ -4,66 +4,16 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import * as IndexTypeVariants from './index_type_variants'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; // The tagged union or sum type for the algebraic type `IndexType`. -export type IndexType = IndexTypeVariants.BTree | IndexTypeVariants.Hash; - -let _cached_IndexType_type_value: __AlgebraicTypeType | null = null; - -// A value with helper functions to construct the type. -export const IndexType = { - // Helper functions for constructing each variant of the tagged union. - // ``` - // const foo = Foo.A(42); - // assert!(foo.tag === "A"); - // assert!(foo.value === 42); - // ``` - BTree: { tag: 'BTree' } as const, - Hash: { tag: 'Hash' } as const, - - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_IndexType_type_value) return _cached_IndexType_type_value; - _cached_IndexType_type_value = __AlgebraicTypeValue.Sum({ variants: [] }); - _cached_IndexType_type_value.value.variants.push( - { - name: 'BTree', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'Hash', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - } - ); - return _cached_IndexType_type_value; - }, - - serialize(writer: __BinaryWriter, value: IndexType): void { - __AlgebraicTypeValue.serializeValue( - writer, - IndexType.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): IndexType { - return __AlgebraicTypeValue.deserializeValue( - reader, - IndexType.getTypeScriptAlgebraicType() - ); - }, -}; +const IndexType = __t.enum('IndexType', { + BTree: __t.unit(), + Hash: __t.unit(), +}); export default IndexType; diff --git a/crates/bindings-typescript/src/lib/autogen/index_type_variants.ts b/crates/bindings-typescript/src/lib/autogen/index_type_variants.ts deleted file mode 100644 index e6ad5bc4a79..00000000000 --- a/crates/bindings-typescript/src/lib/autogen/index_type_variants.ts +++ /dev/null @@ -1,21 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -/* eslint-disable */ -/* tslint:disable */ -import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; - -export type BTree = { tag: 'BTree' }; -export type Hash = { tag: 'Hash' }; diff --git a/crates/bindings-typescript/src/lib/autogen/lifecycle_type.ts b/crates/bindings-typescript/src/lib/autogen/lifecycle_type.ts index 1ac1f627392..f1aa730d73c 100644 --- a/crates/bindings-typescript/src/lib/autogen/lifecycle_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/lifecycle_type.ts @@ -4,74 +4,17 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import * as LifecycleVariants from './lifecycle_variants'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; // The tagged union or sum type for the algebraic type `Lifecycle`. -export type Lifecycle = - | LifecycleVariants.Init - | LifecycleVariants.OnConnect - | LifecycleVariants.OnDisconnect; - -let _cached_Lifecycle_type_value: __AlgebraicTypeType | null = null; - -// A value with helper functions to construct the type. -export const Lifecycle = { - // Helper functions for constructing each variant of the tagged union. - // ``` - // const foo = Foo.A(42); - // assert!(foo.tag === "A"); - // assert!(foo.value === 42); - // ``` - Init: { tag: 'Init' } as const, - OnConnect: { tag: 'OnConnect' } as const, - OnDisconnect: { tag: 'OnDisconnect' } as const, - - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_Lifecycle_type_value) return _cached_Lifecycle_type_value; - _cached_Lifecycle_type_value = __AlgebraicTypeValue.Sum({ variants: [] }); - _cached_Lifecycle_type_value.value.variants.push( - { - name: 'Init', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'OnConnect', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'OnDisconnect', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - } - ); - return _cached_Lifecycle_type_value; - }, - - serialize(writer: __BinaryWriter, value: Lifecycle): void { - __AlgebraicTypeValue.serializeValue( - writer, - Lifecycle.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): Lifecycle { - return __AlgebraicTypeValue.deserializeValue( - reader, - Lifecycle.getTypeScriptAlgebraicType() - ); - }, -}; +const Lifecycle = __t.enum('Lifecycle', { + Init: __t.unit(), + OnConnect: __t.unit(), + OnDisconnect: __t.unit(), +}); export default Lifecycle; diff --git a/crates/bindings-typescript/src/lib/autogen/lifecycle_variants.ts b/crates/bindings-typescript/src/lib/autogen/lifecycle_variants.ts deleted file mode 100644 index 0816ce1d64e..00000000000 --- a/crates/bindings-typescript/src/lib/autogen/lifecycle_variants.ts +++ /dev/null @@ -1,22 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -/* eslint-disable */ -/* tslint:disable */ -import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; - -export type Init = { tag: 'Init' }; -export type OnConnect = { tag: 'OnConnect' }; -export type OnDisconnect = { tag: 'OnDisconnect' }; diff --git a/crates/bindings-typescript/src/lib/autogen/misc_module_export_type.ts b/crates/bindings-typescript/src/lib/autogen/misc_module_export_type.ts index 427e9f437f0..9c0589c2c5e 100644 --- a/crates/bindings-typescript/src/lib/autogen/misc_module_export_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/misc_module_export_type.ts @@ -4,69 +4,18 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { TypeAlias } from './type_alias_type'; -// Mark import as potentially unused -declare type __keep_TypeAlias = TypeAlias; - -import * as MiscModuleExportVariants from './misc_module_export_variants'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import TypeAlias from './type_alias_type'; // The tagged union or sum type for the algebraic type `MiscModuleExport`. -export type MiscModuleExport = MiscModuleExportVariants.TypeAlias; - -let _cached_MiscModuleExport_type_value: __AlgebraicTypeType | null = null; - -// A value with helper functions to construct the type. -export const MiscModuleExport = { - // Helper functions for constructing each variant of the tagged union. - // ``` - // const foo = Foo.A(42); - // assert!(foo.tag === "A"); - // assert!(foo.value === 42); - // ``` - TypeAlias: (value: TypeAlias): MiscModuleExportVariants.TypeAlias => ({ - tag: 'TypeAlias', - value, - }), - - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_MiscModuleExport_type_value) - return _cached_MiscModuleExport_type_value; - _cached_MiscModuleExport_type_value = __AlgebraicTypeValue.Sum({ - variants: [], - }); - _cached_MiscModuleExport_type_value.value.variants.push({ - name: 'TypeAlias', - algebraicType: TypeAlias.getTypeScriptAlgebraicType(), - }); - return _cached_MiscModuleExport_type_value; - }, - - serialize(writer: __BinaryWriter, value: MiscModuleExport): void { - __AlgebraicTypeValue.serializeValue( - writer, - MiscModuleExport.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): MiscModuleExport { - return __AlgebraicTypeValue.deserializeValue( - reader, - MiscModuleExport.getTypeScriptAlgebraicType() - ); +const MiscModuleExport = __t.enum('MiscModuleExport', { + get TypeAlias() { + return TypeAlias; }, -}; +}); export default MiscModuleExport; diff --git a/crates/bindings-typescript/src/lib/autogen/misc_module_export_variants.ts b/crates/bindings-typescript/src/lib/autogen/misc_module_export_variants.ts deleted file mode 100644 index d416d705c2f..00000000000 --- a/crates/bindings-typescript/src/lib/autogen/misc_module_export_variants.ts +++ /dev/null @@ -1,23 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -/* eslint-disable */ -/* tslint:disable */ -import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { TypeAlias as TypeAliasType } from './type_alias_type'; -// Mark import as potentially unused -declare type __keep_TypeAliasType = TypeAliasType; - -export type TypeAlias = { tag: 'TypeAlias'; value: TypeAliasType }; diff --git a/crates/bindings-typescript/src/lib/autogen/product_type_element_type.ts b/crates/bindings-typescript/src/lib/autogen/product_type_element_type.ts index 18e793c3857..fec88e755fe 100644 --- a/crates/bindings-typescript/src/lib/autogen/product_type_element_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/product_type_element_type.ts @@ -4,71 +4,16 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { AlgebraicType } from './algebraic_type_type'; -// Mark import as potentially unused -declare type __keep_AlgebraicType = AlgebraicType; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import AlgebraicType from './algebraic_type_type'; -export type ProductTypeElement = { - name: string | undefined; - algebraicType: AlgebraicType; -}; -let _cached_ProductTypeElement_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const ProductTypeElement = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_ProductTypeElement_type_value) - return _cached_ProductTypeElement_type_value; - _cached_ProductTypeElement_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_ProductTypeElement_type_value.value.elements.push( - { - name: 'name', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.String - ), - }, - { - name: 'algebraicType', - algebraicType: AlgebraicType.getTypeScriptAlgebraicType(), - } - ); - return _cached_ProductTypeElement_type_value; - }, - - serialize(writer: __BinaryWriter, value: ProductTypeElement): void { - __AlgebraicTypeValue.serializeValue( - writer, - ProductTypeElement.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('ProductTypeElement', { + name: __t.option(__t.string()), + get algebraicType() { + return AlgebraicType; }, - - deserialize(reader: __BinaryReader): ProductTypeElement { - return __AlgebraicTypeValue.deserializeValue( - reader, - ProductTypeElement.getTypeScriptAlgebraicType() - ); - }, -}; - -export default ProductTypeElement; +}); diff --git a/crates/bindings-typescript/src/lib/autogen/product_type_type.ts b/crates/bindings-typescript/src/lib/autogen/product_type_type.ts index aa72f5a57af..64416a77874 100644 --- a/crates/bindings-typescript/src/lib/autogen/product_type_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/product_type_type.ts @@ -4,63 +4,15 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { ProductTypeElement } from './product_type_element_type'; -// Mark import as potentially unused -declare type __keep_ProductTypeElement = ProductTypeElement; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import ProductTypeElement from './product_type_element_type'; -export type ProductType = { - elements: ProductTypeElement[]; -}; -let _cached_ProductType_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const ProductType = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_ProductType_type_value) return _cached_ProductType_type_value; - _cached_ProductType_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_ProductType_type_value.value.elements.push({ - name: 'elements', - algebraicType: __AlgebraicTypeValue.Array( - ProductTypeElement.getTypeScriptAlgebraicType() - ), - }); - return _cached_ProductType_type_value; - }, - - serialize(writer: __BinaryWriter, value: ProductType): void { - __AlgebraicTypeValue.serializeValue( - writer, - ProductType.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('ProductType', { + get elements() { + return __t.array(ProductTypeElement); }, - - deserialize(reader: __BinaryReader): ProductType { - return __AlgebraicTypeValue.deserializeValue( - reader, - ProductType.getTypeScriptAlgebraicType() - ); - }, -}; - -export default ProductType; +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_column_def_v_8_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_column_def_v_8_type.ts index c7ceea12688..b8606b3a96d 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_column_def_v_8_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_column_def_v_8_type.ts @@ -4,66 +4,16 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { AlgebraicType } from './algebraic_type_type'; -// Mark import as potentially unused -declare type __keep_AlgebraicType = AlgebraicType; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import AlgebraicType from './algebraic_type_type'; -export type RawColumnDefV8 = { - colName: string; - colType: AlgebraicType; -}; -let _cached_RawColumnDefV8_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawColumnDefV8 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawColumnDefV8_type_value) - return _cached_RawColumnDefV8_type_value; - _cached_RawColumnDefV8_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawColumnDefV8_type_value.value.elements.push( - { name: 'colName', algebraicType: __AlgebraicTypeValue.String }, - { - name: 'colType', - algebraicType: AlgebraicType.getTypeScriptAlgebraicType(), - } - ); - return _cached_RawColumnDefV8_type_value; - }, - - serialize(writer: __BinaryWriter, value: RawColumnDefV8): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawColumnDefV8.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('RawColumnDefV8', { + colName: __t.string(), + get colType() { + return AlgebraicType; }, - - deserialize(reader: __BinaryReader): RawColumnDefV8 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawColumnDefV8.getTypeScriptAlgebraicType() - ); - }, -}; - -export default RawColumnDefV8; +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_column_default_value_v_9_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_column_default_value_v_9_type.ts index f3b486cf3c6..3915ca92c5a 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_column_default_value_v_9_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_column_default_value_v_9_type.ts @@ -4,66 +4,14 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; -export type RawColumnDefaultValueV9 = { - table: string; - colId: number; - value: Uint8Array; -}; -let _cached_RawColumnDefaultValueV9_type_value: __AlgebraicTypeType | null = - null; - -/** - * An object for generated helper functions. - */ -export const RawColumnDefaultValueV9 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawColumnDefaultValueV9_type_value) - return _cached_RawColumnDefaultValueV9_type_value; - _cached_RawColumnDefaultValueV9_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawColumnDefaultValueV9_type_value.value.elements.push( - { name: 'table', algebraicType: __AlgebraicTypeValue.String }, - { name: 'colId', algebraicType: __AlgebraicTypeValue.U16 }, - { - name: 'value', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.U8), - } - ); - return _cached_RawColumnDefaultValueV9_type_value; - }, - - serialize(writer: __BinaryWriter, value: RawColumnDefaultValueV9): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawColumnDefaultValueV9.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): RawColumnDefaultValueV9 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawColumnDefaultValueV9.getTypeScriptAlgebraicType() - ); - }, -}; - -export default RawColumnDefaultValueV9; +export default __t.object('RawColumnDefaultValueV9', { + table: __t.string(), + colId: __t.u16(), + value: __t.byteArray(), +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_constraint_data_v_9_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_constraint_data_v_9_type.ts index 453163184fa..39812e52b83 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_constraint_data_v_9_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_constraint_data_v_9_type.ts @@ -4,68 +4,18 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { RawUniqueConstraintDataV9 } from './raw_unique_constraint_data_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawUniqueConstraintDataV9 = RawUniqueConstraintDataV9; - -import * as RawConstraintDataV9Variants from './raw_constraint_data_v_9_variants'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import RawUniqueConstraintDataV9 from './raw_unique_constraint_data_v_9_type'; // The tagged union or sum type for the algebraic type `RawConstraintDataV9`. -export type RawConstraintDataV9 = RawConstraintDataV9Variants.Unique; - -let _cached_RawConstraintDataV9_type_value: __AlgebraicTypeType | null = null; - -// A value with helper functions to construct the type. -export const RawConstraintDataV9 = { - // Helper functions for constructing each variant of the tagged union. - // ``` - // const foo = Foo.A(42); - // assert!(foo.tag === "A"); - // assert!(foo.value === 42); - // ``` - Unique: ( - value: RawUniqueConstraintDataV9 - ): RawConstraintDataV9Variants.Unique => ({ tag: 'Unique', value }), - - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawConstraintDataV9_type_value) - return _cached_RawConstraintDataV9_type_value; - _cached_RawConstraintDataV9_type_value = __AlgebraicTypeValue.Sum({ - variants: [], - }); - _cached_RawConstraintDataV9_type_value.value.variants.push({ - name: 'Unique', - algebraicType: RawUniqueConstraintDataV9.getTypeScriptAlgebraicType(), - }); - return _cached_RawConstraintDataV9_type_value; - }, - - serialize(writer: __BinaryWriter, value: RawConstraintDataV9): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawConstraintDataV9.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): RawConstraintDataV9 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawConstraintDataV9.getTypeScriptAlgebraicType() - ); +const RawConstraintDataV9 = __t.enum('RawConstraintDataV9', { + get Unique() { + return RawUniqueConstraintDataV9; }, -}; +}); export default RawConstraintDataV9; diff --git a/crates/bindings-typescript/src/lib/autogen/raw_constraint_data_v_9_variants.ts b/crates/bindings-typescript/src/lib/autogen/raw_constraint_data_v_9_variants.ts deleted file mode 100644 index 81d12153b5d..00000000000 --- a/crates/bindings-typescript/src/lib/autogen/raw_constraint_data_v_9_variants.ts +++ /dev/null @@ -1,24 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -/* eslint-disable */ -/* tslint:disable */ -import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { RawUniqueConstraintDataV9 as RawUniqueConstraintDataV9Type } from './raw_unique_constraint_data_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawUniqueConstraintDataV9Type = - RawUniqueConstraintDataV9Type; - -export type Unique = { tag: 'Unique'; value: RawUniqueConstraintDataV9Type }; diff --git a/crates/bindings-typescript/src/lib/autogen/raw_constraint_def_v_8_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_constraint_def_v_8_type.ts index 53a1d66fafa..93c76509ed2 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_constraint_def_v_8_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_constraint_def_v_8_type.ts @@ -4,65 +4,14 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; -export type RawConstraintDefV8 = { - constraintName: string; - constraints: number; - columns: number[]; -}; -let _cached_RawConstraintDefV8_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawConstraintDefV8 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawConstraintDefV8_type_value) - return _cached_RawConstraintDefV8_type_value; - _cached_RawConstraintDefV8_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawConstraintDefV8_type_value.value.elements.push( - { name: 'constraintName', algebraicType: __AlgebraicTypeValue.String }, - { name: 'constraints', algebraicType: __AlgebraicTypeValue.U8 }, - { - name: 'columns', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.U16), - } - ); - return _cached_RawConstraintDefV8_type_value; - }, - - serialize(writer: __BinaryWriter, value: RawConstraintDefV8): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawConstraintDefV8.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): RawConstraintDefV8 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawConstraintDefV8.getTypeScriptAlgebraicType() - ); - }, -}; - -export default RawConstraintDefV8; +export default __t.object('RawConstraintDefV8', { + constraintName: __t.string(), + constraints: __t.u8(), + columns: __t.array(__t.u16()), +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_constraint_def_v_9_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_constraint_def_v_9_type.ts index eb21bf196eb..ac0144c50d5 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_constraint_def_v_9_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_constraint_def_v_9_type.ts @@ -4,71 +4,16 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { RawConstraintDataV9 } from './raw_constraint_data_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawConstraintDataV9 = RawConstraintDataV9; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import RawConstraintDataV9 from './raw_constraint_data_v_9_type'; -export type RawConstraintDefV9 = { - name: string | undefined; - data: RawConstraintDataV9; -}; -let _cached_RawConstraintDefV9_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawConstraintDefV9 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawConstraintDefV9_type_value) - return _cached_RawConstraintDefV9_type_value; - _cached_RawConstraintDefV9_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawConstraintDefV9_type_value.value.elements.push( - { - name: 'name', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.String - ), - }, - { - name: 'data', - algebraicType: RawConstraintDataV9.getTypeScriptAlgebraicType(), - } - ); - return _cached_RawConstraintDefV9_type_value; - }, - - serialize(writer: __BinaryWriter, value: RawConstraintDefV9): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawConstraintDefV9.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('RawConstraintDefV9', { + name: __t.option(__t.string()), + get data() { + return RawConstraintDataV9; }, - - deserialize(reader: __BinaryReader): RawConstraintDefV9 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawConstraintDefV9.getTypeScriptAlgebraicType() - ); - }, -}; - -export default RawConstraintDefV9; +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_index_algorithm_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_index_algorithm_type.ts index c9d9b9111cc..a1c1cda01a5 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_index_algorithm_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_index_algorithm_type.ts @@ -4,83 +4,17 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import * as RawIndexAlgorithmVariants from './raw_index_algorithm_variants'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; // The tagged union or sum type for the algebraic type `RawIndexAlgorithm`. -export type RawIndexAlgorithm = - | RawIndexAlgorithmVariants.BTree - | RawIndexAlgorithmVariants.Hash - | RawIndexAlgorithmVariants.Direct; - -let _cached_RawIndexAlgorithm_type_value: __AlgebraicTypeType | null = null; - -// A value with helper functions to construct the type. -export const RawIndexAlgorithm = { - // Helper functions for constructing each variant of the tagged union. - // ``` - // const foo = Foo.A(42); - // assert!(foo.tag === "A"); - // assert!(foo.value === 42); - // ``` - BTree: (value: number[]): RawIndexAlgorithmVariants.BTree => ({ - tag: 'BTree', - value, - }), - Hash: (value: number[]): RawIndexAlgorithmVariants.Hash => ({ - tag: 'Hash', - value, - }), - Direct: (value: number): RawIndexAlgorithmVariants.Direct => ({ - tag: 'Direct', - value, - }), - - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawIndexAlgorithm_type_value) - return _cached_RawIndexAlgorithm_type_value; - _cached_RawIndexAlgorithm_type_value = __AlgebraicTypeValue.Sum({ - variants: [], - }); - _cached_RawIndexAlgorithm_type_value.value.variants.push( - { - name: 'BTree', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.U16), - }, - { - name: 'Hash', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.U16), - }, - { name: 'Direct', algebraicType: __AlgebraicTypeValue.U16 } - ); - return _cached_RawIndexAlgorithm_type_value; - }, - - serialize(writer: __BinaryWriter, value: RawIndexAlgorithm): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawIndexAlgorithm.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): RawIndexAlgorithm { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawIndexAlgorithm.getTypeScriptAlgebraicType() - ); - }, -}; +const RawIndexAlgorithm = __t.enum('RawIndexAlgorithm', { + BTree: __t.array(__t.u16()), + Hash: __t.array(__t.u16()), + Direct: __t.u16(), +}); export default RawIndexAlgorithm; diff --git a/crates/bindings-typescript/src/lib/autogen/raw_index_algorithm_variants.ts b/crates/bindings-typescript/src/lib/autogen/raw_index_algorithm_variants.ts deleted file mode 100644 index cee2772163f..00000000000 --- a/crates/bindings-typescript/src/lib/autogen/raw_index_algorithm_variants.ts +++ /dev/null @@ -1,22 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -/* eslint-disable */ -/* tslint:disable */ -import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; - -export type BTree = { tag: 'BTree'; value: number[] }; -export type Hash = { tag: 'Hash'; value: number[] }; -export type Direct = { tag: 'Direct'; value: number }; diff --git a/crates/bindings-typescript/src/lib/autogen/raw_index_def_v_8_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_index_def_v_8_type.ts index 4760d1cd435..52fff2ef4ac 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_index_def_v_8_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_index_def_v_8_type.ts @@ -4,73 +4,18 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { IndexType } from './index_type_type'; -// Mark import as potentially unused -declare type __keep_IndexType = IndexType; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import IndexType from './index_type_type'; -export type RawIndexDefV8 = { - indexName: string; - isUnique: boolean; - indexType: IndexType; - columns: number[]; -}; -let _cached_RawIndexDefV8_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawIndexDefV8 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawIndexDefV8_type_value) - return _cached_RawIndexDefV8_type_value; - _cached_RawIndexDefV8_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawIndexDefV8_type_value.value.elements.push( - { name: 'indexName', algebraicType: __AlgebraicTypeValue.String }, - { name: 'isUnique', algebraicType: __AlgebraicTypeValue.Bool }, - { - name: 'indexType', - algebraicType: IndexType.getTypeScriptAlgebraicType(), - }, - { - name: 'columns', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.U16), - } - ); - return _cached_RawIndexDefV8_type_value; - }, - - serialize(writer: __BinaryWriter, value: RawIndexDefV8): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawIndexDefV8.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('RawIndexDefV8', { + indexName: __t.string(), + isUnique: __t.bool(), + get indexType() { + return IndexType; }, - - deserialize(reader: __BinaryReader): RawIndexDefV8 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawIndexDefV8.getTypeScriptAlgebraicType() - ); - }, -}; - -export default RawIndexDefV8; + columns: __t.array(__t.u16()), +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_index_def_v_9_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_index_def_v_9_type.ts index d3df3940259..d29a62e93dc 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_index_def_v_9_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_index_def_v_9_type.ts @@ -4,78 +4,17 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { RawIndexAlgorithm } from './raw_index_algorithm_type'; -// Mark import as potentially unused -declare type __keep_RawIndexAlgorithm = RawIndexAlgorithm; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import RawIndexAlgorithm from './raw_index_algorithm_type'; -export type RawIndexDefV9 = { - name: string | undefined; - accessorName: string | undefined; - algorithm: RawIndexAlgorithm; -}; -let _cached_RawIndexDefV9_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawIndexDefV9 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawIndexDefV9_type_value) - return _cached_RawIndexDefV9_type_value; - _cached_RawIndexDefV9_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawIndexDefV9_type_value.value.elements.push( - { - name: 'name', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.String - ), - }, - { - name: 'accessorName', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.String - ), - }, - { - name: 'algorithm', - algebraicType: RawIndexAlgorithm.getTypeScriptAlgebraicType(), - } - ); - return _cached_RawIndexDefV9_type_value; - }, - - serialize(writer: __BinaryWriter, value: RawIndexDefV9): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawIndexDefV9.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('RawIndexDefV9', { + name: __t.option(__t.string()), + accessorName: __t.option(__t.string()), + get algorithm() { + return RawIndexAlgorithm; }, - - deserialize(reader: __BinaryReader): RawIndexDefV9 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawIndexDefV9.getTypeScriptAlgebraicType() - ); - }, -}; - -export default RawIndexDefV9; +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_misc_module_export_v_9_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_misc_module_export_v_9_type.ts index e10a92d8844..60ca04525da 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_misc_module_export_v_9_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_misc_module_export_v_9_type.ts @@ -4,94 +4,26 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { RawColumnDefaultValueV9 } from './raw_column_default_value_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawColumnDefaultValueV9 = RawColumnDefaultValueV9; -import { RawProcedureDefV9 } from './raw_procedure_def_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawProcedureDefV9 = RawProcedureDefV9; -import { RawViewDefV9 } from './raw_view_def_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawViewDefV9 = RawViewDefV9; - -import * as RawMiscModuleExportV9Variants from './raw_misc_module_export_v_9_variants'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import RawColumnDefaultValueV9 from './raw_column_default_value_v_9_type'; +import RawProcedureDefV9 from './raw_procedure_def_v_9_type'; +import RawViewDefV9 from './raw_view_def_v_9_type'; // The tagged union or sum type for the algebraic type `RawMiscModuleExportV9`. -export type RawMiscModuleExportV9 = - | RawMiscModuleExportV9Variants.ColumnDefaultValue - | RawMiscModuleExportV9Variants.Procedure - | RawMiscModuleExportV9Variants.View; - -let _cached_RawMiscModuleExportV9_type_value: __AlgebraicTypeType | null = null; - -// A value with helper functions to construct the type. -export const RawMiscModuleExportV9 = { - // Helper functions for constructing each variant of the tagged union. - // ``` - // const foo = Foo.A(42); - // assert!(foo.tag === "A"); - // assert!(foo.value === 42); - // ``` - ColumnDefaultValue: ( - value: RawColumnDefaultValueV9 - ): RawMiscModuleExportV9Variants.ColumnDefaultValue => ({ - tag: 'ColumnDefaultValue', - value, - }), - Procedure: ( - value: RawProcedureDefV9 - ): RawMiscModuleExportV9Variants.Procedure => ({ tag: 'Procedure', value }), - View: (value: RawViewDefV9): RawMiscModuleExportV9Variants.View => ({ - tag: 'View', - value, - }), - - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawMiscModuleExportV9_type_value) - return _cached_RawMiscModuleExportV9_type_value; - _cached_RawMiscModuleExportV9_type_value = __AlgebraicTypeValue.Sum({ - variants: [], - }); - _cached_RawMiscModuleExportV9_type_value.value.variants.push( - { - name: 'ColumnDefaultValue', - algebraicType: RawColumnDefaultValueV9.getTypeScriptAlgebraicType(), - }, - { - name: 'Procedure', - algebraicType: RawProcedureDefV9.getTypeScriptAlgebraicType(), - }, - { name: 'View', algebraicType: RawViewDefV9.getTypeScriptAlgebraicType() } - ); - return _cached_RawMiscModuleExportV9_type_value; +const RawMiscModuleExportV9 = __t.enum('RawMiscModuleExportV9', { + get ColumnDefaultValue() { + return RawColumnDefaultValueV9; }, - - serialize(writer: __BinaryWriter, value: RawMiscModuleExportV9): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawMiscModuleExportV9.getTypeScriptAlgebraicType(), - value - ); + get Procedure() { + return RawProcedureDefV9; }, - - deserialize(reader: __BinaryReader): RawMiscModuleExportV9 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawMiscModuleExportV9.getTypeScriptAlgebraicType() - ); + get View() { + return RawViewDefV9; }, -}; +}); export default RawMiscModuleExportV9; diff --git a/crates/bindings-typescript/src/lib/autogen/raw_misc_module_export_v_9_variants.ts b/crates/bindings-typescript/src/lib/autogen/raw_misc_module_export_v_9_variants.ts deleted file mode 100644 index a100dd6dc1c..00000000000 --- a/crates/bindings-typescript/src/lib/autogen/raw_misc_module_export_v_9_variants.ts +++ /dev/null @@ -1,34 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -/* eslint-disable */ -/* tslint:disable */ -import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { RawColumnDefaultValueV9 as RawColumnDefaultValueV9Type } from './raw_column_default_value_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawColumnDefaultValueV9Type = RawColumnDefaultValueV9Type; -import { RawProcedureDefV9 as RawProcedureDefV9Type } from './raw_procedure_def_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawProcedureDefV9Type = RawProcedureDefV9Type; -import { RawViewDefV9 as RawViewDefV9Type } from './raw_view_def_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawViewDefV9Type = RawViewDefV9Type; - -export type ColumnDefaultValue = { - tag: 'ColumnDefaultValue'; - value: RawColumnDefaultValueV9Type; -}; -export type Procedure = { tag: 'Procedure'; value: RawProcedureDefV9Type }; -export type View = { tag: 'View'; value: RawViewDefV9Type }; diff --git a/crates/bindings-typescript/src/lib/autogen/raw_module_def_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_module_def_type.ts index 6df7f5869b6..e0f91b646ff 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_module_def_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_module_def_type.ts @@ -4,80 +4,22 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { RawModuleDefV8 } from './raw_module_def_v_8_type'; -// Mark import as potentially unused -declare type __keep_RawModuleDefV8 = RawModuleDefV8; -import { RawModuleDefV9 } from './raw_module_def_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawModuleDefV9 = RawModuleDefV9; - -import * as RawModuleDefVariants from './raw_module_def_variants'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import RawModuleDefV8 from './raw_module_def_v_8_type'; +import RawModuleDefV9 from './raw_module_def_v_9_type'; // The tagged union or sum type for the algebraic type `RawModuleDef`. -export type RawModuleDef = - | RawModuleDefVariants.V8BackCompat - | RawModuleDefVariants.V9; - -let _cached_RawModuleDef_type_value: __AlgebraicTypeType | null = null; - -// A value with helper functions to construct the type. -export const RawModuleDef = { - // Helper functions for constructing each variant of the tagged union. - // ``` - // const foo = Foo.A(42); - // assert!(foo.tag === "A"); - // assert!(foo.value === 42); - // ``` - V8BackCompat: (value: RawModuleDefV8): RawModuleDefVariants.V8BackCompat => ({ - tag: 'V8BackCompat', - value, - }), - V9: (value: RawModuleDefV9): RawModuleDefVariants.V9 => ({ - tag: 'V9', - value, - }), - - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawModuleDef_type_value) return _cached_RawModuleDef_type_value; - _cached_RawModuleDef_type_value = __AlgebraicTypeValue.Sum({ - variants: [], - }); - _cached_RawModuleDef_type_value.value.variants.push( - { - name: 'V8BackCompat', - algebraicType: RawModuleDefV8.getTypeScriptAlgebraicType(), - }, - { name: 'V9', algebraicType: RawModuleDefV9.getTypeScriptAlgebraicType() } - ); - return _cached_RawModuleDef_type_value; +const RawModuleDef = __t.enum('RawModuleDef', { + get V8BackCompat() { + return RawModuleDefV8; }, - - serialize(writer: __BinaryWriter, value: RawModuleDef): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawModuleDef.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): RawModuleDef { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawModuleDef.getTypeScriptAlgebraicType() - ); + get V9() { + return RawModuleDefV9; }, -}; +}); export default RawModuleDef; diff --git a/crates/bindings-typescript/src/lib/autogen/raw_module_def_v_8_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_module_def_v_8_type.ts index 1ea5fdf6afa..cdfee338f0b 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_module_def_v_8_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_module_def_v_8_type.ts @@ -4,94 +4,27 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { Typespace } from './typespace_type'; -// Mark import as potentially unused -declare type __keep_Typespace = Typespace; -import { TableDesc } from './table_desc_type'; -// Mark import as potentially unused -declare type __keep_TableDesc = TableDesc; -import { ReducerDef } from './reducer_def_type'; -// Mark import as potentially unused -declare type __keep_ReducerDef = ReducerDef; -import { MiscModuleExport } from './misc_module_export_type'; -// Mark import as potentially unused -declare type __keep_MiscModuleExport = MiscModuleExport; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import Typespace from './typespace_type'; +import TableDesc from './table_desc_type'; +import ReducerDef from './reducer_def_type'; +import MiscModuleExport from './misc_module_export_type'; -export type RawModuleDefV8 = { - typespace: Typespace; - tables: TableDesc[]; - reducers: ReducerDef[]; - miscExports: MiscModuleExport[]; -}; -let _cached_RawModuleDefV8_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawModuleDefV8 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawModuleDefV8_type_value) - return _cached_RawModuleDefV8_type_value; - _cached_RawModuleDefV8_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawModuleDefV8_type_value.value.elements.push( - { - name: 'typespace', - algebraicType: Typespace.getTypeScriptAlgebraicType(), - }, - { - name: 'tables', - algebraicType: __AlgebraicTypeValue.Array( - TableDesc.getTypeScriptAlgebraicType() - ), - }, - { - name: 'reducers', - algebraicType: __AlgebraicTypeValue.Array( - ReducerDef.getTypeScriptAlgebraicType() - ), - }, - { - name: 'miscExports', - algebraicType: __AlgebraicTypeValue.Array( - MiscModuleExport.getTypeScriptAlgebraicType() - ), - } - ); - return _cached_RawModuleDefV8_type_value; +export default __t.object('RawModuleDefV8', { + get typespace() { + return Typespace; }, - - serialize(writer: __BinaryWriter, value: RawModuleDefV8): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawModuleDefV8.getTypeScriptAlgebraicType(), - value - ); + get tables() { + return __t.array(TableDesc); }, - - deserialize(reader: __BinaryReader): RawModuleDefV8 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawModuleDefV8.getTypeScriptAlgebraicType() - ); + get reducers() { + return __t.array(ReducerDef); }, -}; - -export default RawModuleDefV8; + get miscExports() { + return __t.array(MiscModuleExport); + }, +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_module_def_v_9_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_module_def_v_9_type.ts index f73d0060b67..42c05970fdb 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_module_def_v_9_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_module_def_v_9_type.ts @@ -4,114 +4,35 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { Typespace } from './typespace_type'; -// Mark import as potentially unused -declare type __keep_Typespace = Typespace; -import { RawTableDefV9 } from './raw_table_def_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawTableDefV9 = RawTableDefV9; -import { RawReducerDefV9 } from './raw_reducer_def_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawReducerDefV9 = RawReducerDefV9; -import { RawTypeDefV9 } from './raw_type_def_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawTypeDefV9 = RawTypeDefV9; -import { RawMiscModuleExportV9 } from './raw_misc_module_export_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawMiscModuleExportV9 = RawMiscModuleExportV9; -import { RawRowLevelSecurityDefV9 } from './raw_row_level_security_def_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawRowLevelSecurityDefV9 = RawRowLevelSecurityDefV9; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import Typespace from './typespace_type'; +import RawTableDefV9 from './raw_table_def_v_9_type'; +import RawReducerDefV9 from './raw_reducer_def_v_9_type'; +import RawTypeDefV9 from './raw_type_def_v_9_type'; +import RawMiscModuleExportV9 from './raw_misc_module_export_v_9_type'; +import RawRowLevelSecurityDefV9 from './raw_row_level_security_def_v_9_type'; -export type RawModuleDefV9 = { - typespace: Typespace; - tables: RawTableDefV9[]; - reducers: RawReducerDefV9[]; - types: RawTypeDefV9[]; - miscExports: RawMiscModuleExportV9[]; - rowLevelSecurity: RawRowLevelSecurityDefV9[]; -}; -let _cached_RawModuleDefV9_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawModuleDefV9 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawModuleDefV9_type_value) - return _cached_RawModuleDefV9_type_value; - _cached_RawModuleDefV9_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawModuleDefV9_type_value.value.elements.push( - { - name: 'typespace', - algebraicType: Typespace.getTypeScriptAlgebraicType(), - }, - { - name: 'tables', - algebraicType: __AlgebraicTypeValue.Array( - RawTableDefV9.getTypeScriptAlgebraicType() - ), - }, - { - name: 'reducers', - algebraicType: __AlgebraicTypeValue.Array( - RawReducerDefV9.getTypeScriptAlgebraicType() - ), - }, - { - name: 'types', - algebraicType: __AlgebraicTypeValue.Array( - RawTypeDefV9.getTypeScriptAlgebraicType() - ), - }, - { - name: 'miscExports', - algebraicType: __AlgebraicTypeValue.Array( - RawMiscModuleExportV9.getTypeScriptAlgebraicType() - ), - }, - { - name: 'rowLevelSecurity', - algebraicType: __AlgebraicTypeValue.Array( - RawRowLevelSecurityDefV9.getTypeScriptAlgebraicType() - ), - } - ); - return _cached_RawModuleDefV9_type_value; +export default __t.object('RawModuleDefV9', { + get typespace() { + return Typespace; }, - - serialize(writer: __BinaryWriter, value: RawModuleDefV9): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawModuleDefV9.getTypeScriptAlgebraicType(), - value - ); + get tables() { + return __t.array(RawTableDefV9); }, - - deserialize(reader: __BinaryReader): RawModuleDefV9 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawModuleDefV9.getTypeScriptAlgebraicType() - ); + get reducers() { + return __t.array(RawReducerDefV9); }, -}; - -export default RawModuleDefV9; + get types() { + return __t.array(RawTypeDefV9); + }, + get miscExports() { + return __t.array(RawMiscModuleExportV9); + }, + get rowLevelSecurity() { + return __t.array(RawRowLevelSecurityDefV9); + }, +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_module_def_variants.ts b/crates/bindings-typescript/src/lib/autogen/raw_module_def_variants.ts deleted file mode 100644 index f64bc93e672..00000000000 --- a/crates/bindings-typescript/src/lib/autogen/raw_module_def_variants.ts +++ /dev/null @@ -1,27 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -/* eslint-disable */ -/* tslint:disable */ -import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { RawModuleDefV8 as RawModuleDefV8Type } from './raw_module_def_v_8_type'; -// Mark import as potentially unused -declare type __keep_RawModuleDefV8Type = RawModuleDefV8Type; -import { RawModuleDefV9 as RawModuleDefV9Type } from './raw_module_def_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawModuleDefV9Type = RawModuleDefV9Type; - -export type V8BackCompat = { tag: 'V8BackCompat'; value: RawModuleDefV8Type }; -export type V9 = { tag: 'V9'; value: RawModuleDefV9Type }; diff --git a/crates/bindings-typescript/src/lib/autogen/raw_procedure_def_v_9_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_procedure_def_v_9_type.ts index 8c422c869be..37b9c4b2c42 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_procedure_def_v_9_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_procedure_def_v_9_type.ts @@ -4,74 +4,20 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { AlgebraicType } from './algebraic_type_type'; -// Mark import as potentially unused -declare type __keep_AlgebraicType = AlgebraicType; -import { ProductType } from './product_type_type'; -// Mark import as potentially unused -declare type __keep_ProductType = ProductType; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import AlgebraicType from './algebraic_type_type'; +import ProductType from './product_type_type'; -export type RawProcedureDefV9 = { - name: string; - params: ProductType; - returnType: AlgebraicType; -}; -let _cached_RawProcedureDefV9_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawProcedureDefV9 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawProcedureDefV9_type_value) - return _cached_RawProcedureDefV9_type_value; - _cached_RawProcedureDefV9_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawProcedureDefV9_type_value.value.elements.push( - { name: 'name', algebraicType: __AlgebraicTypeValue.String }, - { - name: 'params', - algebraicType: ProductType.getTypeScriptAlgebraicType(), - }, - { - name: 'returnType', - algebraicType: AlgebraicType.getTypeScriptAlgebraicType(), - } - ); - return _cached_RawProcedureDefV9_type_value; +export default __t.object('RawProcedureDefV9', { + name: __t.string(), + get params() { + return ProductType; }, - - serialize(writer: __BinaryWriter, value: RawProcedureDefV9): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawProcedureDefV9.getTypeScriptAlgebraicType(), - value - ); + get returnType() { + return AlgebraicType; }, - - deserialize(reader: __BinaryReader): RawProcedureDefV9 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawProcedureDefV9.getTypeScriptAlgebraicType() - ); - }, -}; - -export default RawProcedureDefV9; +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_reducer_def_v_9_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_reducer_def_v_9_type.ts index 85872e7391d..abfa8cf3e68 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_reducer_def_v_9_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_reducer_def_v_9_type.ts @@ -4,76 +4,20 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { ProductType } from './product_type_type'; -// Mark import as potentially unused -declare type __keep_ProductType = ProductType; -import { Lifecycle } from './lifecycle_type'; -// Mark import as potentially unused -declare type __keep_Lifecycle = Lifecycle; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import ProductType from './product_type_type'; +import Lifecycle from './lifecycle_type'; -export type RawReducerDefV9 = { - name: string; - params: ProductType; - lifecycle: Lifecycle | undefined; -}; -let _cached_RawReducerDefV9_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawReducerDefV9 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawReducerDefV9_type_value) - return _cached_RawReducerDefV9_type_value; - _cached_RawReducerDefV9_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawReducerDefV9_type_value.value.elements.push( - { name: 'name', algebraicType: __AlgebraicTypeValue.String }, - { - name: 'params', - algebraicType: ProductType.getTypeScriptAlgebraicType(), - }, - { - name: 'lifecycle', - algebraicType: __AlgebraicTypeValue.createOptionType( - Lifecycle.getTypeScriptAlgebraicType() - ), - } - ); - return _cached_RawReducerDefV9_type_value; +export default __t.object('RawReducerDefV9', { + name: __t.string(), + get params() { + return ProductType; }, - - serialize(writer: __BinaryWriter, value: RawReducerDefV9): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawReducerDefV9.getTypeScriptAlgebraicType(), - value - ); + get lifecycle() { + return __t.option(Lifecycle); }, - - deserialize(reader: __BinaryReader): RawReducerDefV9 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawReducerDefV9.getTypeScriptAlgebraicType() - ); - }, -}; - -export default RawReducerDefV9; +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_row_level_security_def_v_9_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_row_level_security_def_v_9_type.ts index b611871d29b..919a32affe9 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_row_level_security_def_v_9_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_row_level_security_def_v_9_type.ts @@ -4,60 +4,12 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; - -export type RawRowLevelSecurityDefV9 = { - sql: string; -}; -let _cached_RawRowLevelSecurityDefV9_type_value: __AlgebraicTypeType | null = - null; - -/** - * An object for generated helper functions. - */ -export const RawRowLevelSecurityDefV9 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawRowLevelSecurityDefV9_type_value) - return _cached_RawRowLevelSecurityDefV9_type_value; - _cached_RawRowLevelSecurityDefV9_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawRowLevelSecurityDefV9_type_value.value.elements.push({ - name: 'sql', - algebraicType: __AlgebraicTypeValue.String, - }); - return _cached_RawRowLevelSecurityDefV9_type_value; - }, - - serialize(writer: __BinaryWriter, value: RawRowLevelSecurityDefV9): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawRowLevelSecurityDefV9.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): RawRowLevelSecurityDefV9 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawRowLevelSecurityDefV9.getTypeScriptAlgebraicType() - ); - }, -}; - -export default RawRowLevelSecurityDefV9; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; + +export default __t.object('RawRowLevelSecurityDefV9', { + sql: __t.string(), +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_schedule_def_v_9_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_schedule_def_v_9_type.ts index 1ea84503d48..cc48e22fc21 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_schedule_def_v_9_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_schedule_def_v_9_type.ts @@ -4,67 +4,14 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; -export type RawScheduleDefV9 = { - name: string | undefined; - reducerName: string; - scheduledAtColumn: number; -}; -let _cached_RawScheduleDefV9_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawScheduleDefV9 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawScheduleDefV9_type_value) - return _cached_RawScheduleDefV9_type_value; - _cached_RawScheduleDefV9_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawScheduleDefV9_type_value.value.elements.push( - { - name: 'name', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.String - ), - }, - { name: 'reducerName', algebraicType: __AlgebraicTypeValue.String }, - { name: 'scheduledAtColumn', algebraicType: __AlgebraicTypeValue.U16 } - ); - return _cached_RawScheduleDefV9_type_value; - }, - - serialize(writer: __BinaryWriter, value: RawScheduleDefV9): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawScheduleDefV9.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): RawScheduleDefV9 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawScheduleDefV9.getTypeScriptAlgebraicType() - ); - }, -}; - -export default RawScheduleDefV9; +export default __t.object('RawScheduleDefV9', { + name: __t.option(__t.string()), + reducerName: __t.string(), + scheduledAtColumn: __t.u16(), +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_scoped_type_name_v_9_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_scoped_type_name_v_9_type.ts index 70cf0cd455b..8a524df9ea4 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_scoped_type_name_v_9_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_scoped_type_name_v_9_type.ts @@ -4,63 +4,13 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; -export type RawScopedTypeNameV9 = { - scope: string[]; - name: string; -}; -let _cached_RawScopedTypeNameV9_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawScopedTypeNameV9 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawScopedTypeNameV9_type_value) - return _cached_RawScopedTypeNameV9_type_value; - _cached_RawScopedTypeNameV9_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawScopedTypeNameV9_type_value.value.elements.push( - { - name: 'scope', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.String), - }, - { name: 'name', algebraicType: __AlgebraicTypeValue.String } - ); - return _cached_RawScopedTypeNameV9_type_value; - }, - - serialize(writer: __BinaryWriter, value: RawScopedTypeNameV9): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawScopedTypeNameV9.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): RawScopedTypeNameV9 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawScopedTypeNameV9.getTypeScriptAlgebraicType() - ); - }, -}; - -export default RawScopedTypeNameV9; +export default __t.object('RawScopedTypeNameV9', { + scope: __t.array(__t.string()), + name: __t.string(), +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_sequence_def_v_8_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_sequence_def_v_8_type.ts index 75c1799359f..eb0a866fa76 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_sequence_def_v_8_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_sequence_def_v_8_type.ts @@ -4,85 +4,18 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; -export type RawSequenceDefV8 = { - sequenceName: string; - colPos: number; - increment: bigint; - start: bigint | undefined; - minValue: bigint | undefined; - maxValue: bigint | undefined; - allocated: bigint; -}; -let _cached_RawSequenceDefV8_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawSequenceDefV8 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawSequenceDefV8_type_value) - return _cached_RawSequenceDefV8_type_value; - _cached_RawSequenceDefV8_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawSequenceDefV8_type_value.value.elements.push( - { name: 'sequenceName', algebraicType: __AlgebraicTypeValue.String }, - { name: 'colPos', algebraicType: __AlgebraicTypeValue.U16 }, - { name: 'increment', algebraicType: __AlgebraicTypeValue.I128 }, - { - name: 'start', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.I128 - ), - }, - { - name: 'minValue', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.I128 - ), - }, - { - name: 'maxValue', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.I128 - ), - }, - { name: 'allocated', algebraicType: __AlgebraicTypeValue.I128 } - ); - return _cached_RawSequenceDefV8_type_value; - }, - - serialize(writer: __BinaryWriter, value: RawSequenceDefV8): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawSequenceDefV8.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): RawSequenceDefV8 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawSequenceDefV8.getTypeScriptAlgebraicType() - ); - }, -}; - -export default RawSequenceDefV8; +export default __t.object('RawSequenceDefV8', { + sequenceName: __t.string(), + colPos: __t.u16(), + increment: __t.i128(), + start: __t.option(__t.i128()), + minValue: __t.option(__t.i128()), + maxValue: __t.option(__t.i128()), + allocated: __t.i128(), +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_sequence_def_v_9_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_sequence_def_v_9_type.ts index 4043c78a806..5095291e292 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_sequence_def_v_9_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_sequence_def_v_9_type.ts @@ -4,88 +4,17 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; -export type RawSequenceDefV9 = { - name: string | undefined; - column: number; - start: bigint | undefined; - minValue: bigint | undefined; - maxValue: bigint | undefined; - increment: bigint; -}; -let _cached_RawSequenceDefV9_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawSequenceDefV9 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawSequenceDefV9_type_value) - return _cached_RawSequenceDefV9_type_value; - _cached_RawSequenceDefV9_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawSequenceDefV9_type_value.value.elements.push( - { - name: 'name', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.String - ), - }, - { name: 'column', algebraicType: __AlgebraicTypeValue.U16 }, - { - name: 'start', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.I128 - ), - }, - { - name: 'minValue', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.I128 - ), - }, - { - name: 'maxValue', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.I128 - ), - }, - { name: 'increment', algebraicType: __AlgebraicTypeValue.I128 } - ); - return _cached_RawSequenceDefV9_type_value; - }, - - serialize(writer: __BinaryWriter, value: RawSequenceDefV9): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawSequenceDefV9.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): RawSequenceDefV9 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawSequenceDefV9.getTypeScriptAlgebraicType() - ); - }, -}; - -export default RawSequenceDefV9; +export default __t.object('RawSequenceDefV9', { + name: __t.option(__t.string()), + column: __t.u16(), + start: __t.option(__t.i128()), + minValue: __t.option(__t.i128()), + maxValue: __t.option(__t.i128()), + increment: __t.i128(), +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_table_def_v_8_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_table_def_v_8_type.ts index 56775011d3e..c504720d916 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_table_def_v_8_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_table_def_v_8_type.ts @@ -4,109 +4,31 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { RawColumnDefV8 } from './raw_column_def_v_8_type'; -// Mark import as potentially unused -declare type __keep_RawColumnDefV8 = RawColumnDefV8; -import { RawIndexDefV8 } from './raw_index_def_v_8_type'; -// Mark import as potentially unused -declare type __keep_RawIndexDefV8 = RawIndexDefV8; -import { RawConstraintDefV8 } from './raw_constraint_def_v_8_type'; -// Mark import as potentially unused -declare type __keep_RawConstraintDefV8 = RawConstraintDefV8; -import { RawSequenceDefV8 } from './raw_sequence_def_v_8_type'; -// Mark import as potentially unused -declare type __keep_RawSequenceDefV8 = RawSequenceDefV8; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import RawColumnDefV8 from './raw_column_def_v_8_type'; +import RawIndexDefV8 from './raw_index_def_v_8_type'; +import RawConstraintDefV8 from './raw_constraint_def_v_8_type'; +import RawSequenceDefV8 from './raw_sequence_def_v_8_type'; -export type RawTableDefV8 = { - tableName: string; - columns: RawColumnDefV8[]; - indexes: RawIndexDefV8[]; - constraints: RawConstraintDefV8[]; - sequences: RawSequenceDefV8[]; - tableType: string; - tableAccess: string; - scheduled: string | undefined; -}; -let _cached_RawTableDefV8_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawTableDefV8 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawTableDefV8_type_value) - return _cached_RawTableDefV8_type_value; - _cached_RawTableDefV8_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawTableDefV8_type_value.value.elements.push( - { name: 'tableName', algebraicType: __AlgebraicTypeValue.String }, - { - name: 'columns', - algebraicType: __AlgebraicTypeValue.Array( - RawColumnDefV8.getTypeScriptAlgebraicType() - ), - }, - { - name: 'indexes', - algebraicType: __AlgebraicTypeValue.Array( - RawIndexDefV8.getTypeScriptAlgebraicType() - ), - }, - { - name: 'constraints', - algebraicType: __AlgebraicTypeValue.Array( - RawConstraintDefV8.getTypeScriptAlgebraicType() - ), - }, - { - name: 'sequences', - algebraicType: __AlgebraicTypeValue.Array( - RawSequenceDefV8.getTypeScriptAlgebraicType() - ), - }, - { name: 'tableType', algebraicType: __AlgebraicTypeValue.String }, - { name: 'tableAccess', algebraicType: __AlgebraicTypeValue.String }, - { - name: 'scheduled', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.String - ), - } - ); - return _cached_RawTableDefV8_type_value; +export default __t.object('RawTableDefV8', { + tableName: __t.string(), + get columns() { + return __t.array(RawColumnDefV8); }, - - serialize(writer: __BinaryWriter, value: RawTableDefV8): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawTableDefV8.getTypeScriptAlgebraicType(), - value - ); + get indexes() { + return __t.array(RawIndexDefV8); }, - - deserialize(reader: __BinaryReader): RawTableDefV8 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawTableDefV8.getTypeScriptAlgebraicType() - ); + get constraints() { + return __t.array(RawConstraintDefV8); }, -}; - -export default RawTableDefV8; + get sequences() { + return __t.array(RawSequenceDefV8); + }, + tableType: __t.string(), + tableAccess: __t.string(), + scheduled: __t.option(__t.string()), +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_table_def_v_9_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_table_def_v_9_type.ts index 88d6045c24a..8d6df28be85 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_table_def_v_9_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_table_def_v_9_type.ts @@ -4,121 +4,38 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { RawIndexDefV9 } from './raw_index_def_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawIndexDefV9 = RawIndexDefV9; -import { RawConstraintDefV9 } from './raw_constraint_def_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawConstraintDefV9 = RawConstraintDefV9; -import { RawSequenceDefV9 } from './raw_sequence_def_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawSequenceDefV9 = RawSequenceDefV9; -import { RawScheduleDefV9 } from './raw_schedule_def_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawScheduleDefV9 = RawScheduleDefV9; -import { TableType } from './table_type_type'; -// Mark import as potentially unused -declare type __keep_TableType = TableType; -import { TableAccess } from './table_access_type'; -// Mark import as potentially unused -declare type __keep_TableAccess = TableAccess; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import RawIndexDefV9 from './raw_index_def_v_9_type'; +import RawConstraintDefV9 from './raw_constraint_def_v_9_type'; +import RawSequenceDefV9 from './raw_sequence_def_v_9_type'; +import RawScheduleDefV9 from './raw_schedule_def_v_9_type'; +import TableType from './table_type_type'; +import TableAccess from './table_access_type'; -export type RawTableDefV9 = { - name: string; - productTypeRef: number; - primaryKey: number[]; - indexes: RawIndexDefV9[]; - constraints: RawConstraintDefV9[]; - sequences: RawSequenceDefV9[]; - schedule: RawScheduleDefV9 | undefined; - tableType: TableType; - tableAccess: TableAccess; -}; -let _cached_RawTableDefV9_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawTableDefV9 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawTableDefV9_type_value) - return _cached_RawTableDefV9_type_value; - _cached_RawTableDefV9_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawTableDefV9_type_value.value.elements.push( - { name: 'name', algebraicType: __AlgebraicTypeValue.String }, - { name: 'productTypeRef', algebraicType: __AlgebraicTypeValue.U32 }, - { - name: 'primaryKey', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.U16), - }, - { - name: 'indexes', - algebraicType: __AlgebraicTypeValue.Array( - RawIndexDefV9.getTypeScriptAlgebraicType() - ), - }, - { - name: 'constraints', - algebraicType: __AlgebraicTypeValue.Array( - RawConstraintDefV9.getTypeScriptAlgebraicType() - ), - }, - { - name: 'sequences', - algebraicType: __AlgebraicTypeValue.Array( - RawSequenceDefV9.getTypeScriptAlgebraicType() - ), - }, - { - name: 'schedule', - algebraicType: __AlgebraicTypeValue.createOptionType( - RawScheduleDefV9.getTypeScriptAlgebraicType() - ), - }, - { - name: 'tableType', - algebraicType: TableType.getTypeScriptAlgebraicType(), - }, - { - name: 'tableAccess', - algebraicType: TableAccess.getTypeScriptAlgebraicType(), - } - ); - return _cached_RawTableDefV9_type_value; +export default __t.object('RawTableDefV9', { + name: __t.string(), + productTypeRef: __t.u32(), + primaryKey: __t.array(__t.u16()), + get indexes() { + return __t.array(RawIndexDefV9); }, - - serialize(writer: __BinaryWriter, value: RawTableDefV9): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawTableDefV9.getTypeScriptAlgebraicType(), - value - ); + get constraints() { + return __t.array(RawConstraintDefV9); }, - - deserialize(reader: __BinaryReader): RawTableDefV9 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawTableDefV9.getTypeScriptAlgebraicType() - ); + get sequences() { + return __t.array(RawSequenceDefV9); }, -}; - -export default RawTableDefV9; + get schedule() { + return __t.option(RawScheduleDefV9); + }, + get tableType() { + return TableType; + }, + get tableAccess() { + return TableAccess; + }, +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_type_def_v_9_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_type_def_v_9_type.ts index 5a589342fe4..5a8b4c54725 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_type_def_v_9_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_type_def_v_9_type.ts @@ -4,67 +4,17 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { RawScopedTypeNameV9 } from './raw_scoped_type_name_v_9_type'; -// Mark import as potentially unused -declare type __keep_RawScopedTypeNameV9 = RawScopedTypeNameV9; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import RawScopedTypeNameV9 from './raw_scoped_type_name_v_9_type'; -export type RawTypeDefV9 = { - name: RawScopedTypeNameV9; - ty: number; - customOrdering: boolean; -}; -let _cached_RawTypeDefV9_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawTypeDefV9 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawTypeDefV9_type_value) return _cached_RawTypeDefV9_type_value; - _cached_RawTypeDefV9_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawTypeDefV9_type_value.value.elements.push( - { - name: 'name', - algebraicType: RawScopedTypeNameV9.getTypeScriptAlgebraicType(), - }, - { name: 'ty', algebraicType: __AlgebraicTypeValue.U32 }, - { name: 'customOrdering', algebraicType: __AlgebraicTypeValue.Bool } - ); - return _cached_RawTypeDefV9_type_value; - }, - - serialize(writer: __BinaryWriter, value: RawTypeDefV9): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawTypeDefV9.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('RawTypeDefV9', { + get name() { + return RawScopedTypeNameV9; }, - - deserialize(reader: __BinaryReader): RawTypeDefV9 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawTypeDefV9.getTypeScriptAlgebraicType() - ); - }, -}; - -export default RawTypeDefV9; + ty: __t.u32(), + customOrdering: __t.bool(), +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_unique_constraint_data_v_9_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_unique_constraint_data_v_9_type.ts index 5d0ff3e4cef..38ebe81001b 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_unique_constraint_data_v_9_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_unique_constraint_data_v_9_type.ts @@ -4,60 +4,12 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; - -export type RawUniqueConstraintDataV9 = { - columns: number[]; -}; -let _cached_RawUniqueConstraintDataV9_type_value: __AlgebraicTypeType | null = - null; - -/** - * An object for generated helper functions. - */ -export const RawUniqueConstraintDataV9 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawUniqueConstraintDataV9_type_value) - return _cached_RawUniqueConstraintDataV9_type_value; - _cached_RawUniqueConstraintDataV9_type_value = __AlgebraicTypeValue.Product( - { elements: [] } - ); - _cached_RawUniqueConstraintDataV9_type_value.value.elements.push({ - name: 'columns', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.U16), - }); - return _cached_RawUniqueConstraintDataV9_type_value; - }, - - serialize(writer: __BinaryWriter, value: RawUniqueConstraintDataV9): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawUniqueConstraintDataV9.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): RawUniqueConstraintDataV9 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawUniqueConstraintDataV9.getTypeScriptAlgebraicType() - ); - }, -}; - -export default RawUniqueConstraintDataV9; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; + +export default __t.object('RawUniqueConstraintDataV9', { + columns: __t.array(__t.u16()), +}); diff --git a/crates/bindings-typescript/src/lib/autogen/raw_view_def_v_9_type.ts b/crates/bindings-typescript/src/lib/autogen/raw_view_def_v_9_type.ts index 48818599501..d58d89a1a03 100644 --- a/crates/bindings-typescript/src/lib/autogen/raw_view_def_v_9_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/raw_view_def_v_9_type.ts @@ -4,79 +4,23 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { AlgebraicType } from './algebraic_type_type'; -// Mark import as potentially unused -declare type __keep_AlgebraicType = AlgebraicType; -import { ProductType } from './product_type_type'; -// Mark import as potentially unused -declare type __keep_ProductType = ProductType; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import AlgebraicType from './algebraic_type_type'; +import ProductType from './product_type_type'; -export type RawViewDefV9 = { - name: string; - index: number; - isPublic: boolean; - isAnonymous: boolean; - params: ProductType; - returnType: AlgebraicType; -}; -let _cached_RawViewDefV9_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const RawViewDefV9 = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RawViewDefV9_type_value) return _cached_RawViewDefV9_type_value; - _cached_RawViewDefV9_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_RawViewDefV9_type_value.value.elements.push( - { name: 'name', algebraicType: __AlgebraicTypeValue.String }, - { name: 'index', algebraicType: __AlgebraicTypeValue.U32 }, - { name: 'isPublic', algebraicType: __AlgebraicTypeValue.Bool }, - { name: 'isAnonymous', algebraicType: __AlgebraicTypeValue.Bool }, - { - name: 'params', - algebraicType: ProductType.getTypeScriptAlgebraicType(), - }, - { - name: 'returnType', - algebraicType: AlgebraicType.getTypeScriptAlgebraicType(), - } - ); - return _cached_RawViewDefV9_type_value; +export default __t.object('RawViewDefV9', { + name: __t.string(), + index: __t.u32(), + isPublic: __t.bool(), + isAnonymous: __t.bool(), + get params() { + return ProductType; }, - - serialize(writer: __BinaryWriter, value: RawViewDefV9): void { - __AlgebraicTypeValue.serializeValue( - writer, - RawViewDefV9.getTypeScriptAlgebraicType(), - value - ); + get returnType() { + return AlgebraicType; }, - - deserialize(reader: __BinaryReader): RawViewDefV9 { - return __AlgebraicTypeValue.deserializeValue( - reader, - RawViewDefV9.getTypeScriptAlgebraicType() - ); - }, -}; - -export default RawViewDefV9; +}); diff --git a/crates/bindings-typescript/src/lib/autogen/reducer_def_type.ts b/crates/bindings-typescript/src/lib/autogen/reducer_def_type.ts index 55f9af77507..7086f7848a1 100644 --- a/crates/bindings-typescript/src/lib/autogen/reducer_def_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/reducer_def_type.ts @@ -4,67 +4,16 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { ProductTypeElement } from './product_type_element_type'; -// Mark import as potentially unused -declare type __keep_ProductTypeElement = ProductTypeElement; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import ProductTypeElement from './product_type_element_type'; -export type ReducerDef = { - name: string; - args: ProductTypeElement[]; -}; -let _cached_ReducerDef_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const ReducerDef = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_ReducerDef_type_value) return _cached_ReducerDef_type_value; - _cached_ReducerDef_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_ReducerDef_type_value.value.elements.push( - { name: 'name', algebraicType: __AlgebraicTypeValue.String }, - { - name: 'args', - algebraicType: __AlgebraicTypeValue.Array( - ProductTypeElement.getTypeScriptAlgebraicType() - ), - } - ); - return _cached_ReducerDef_type_value; - }, - - serialize(writer: __BinaryWriter, value: ReducerDef): void { - __AlgebraicTypeValue.serializeValue( - writer, - ReducerDef.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('ReducerDef', { + name: __t.string(), + get args() { + return __t.array(ProductTypeElement); }, - - deserialize(reader: __BinaryReader): ReducerDef { - return __AlgebraicTypeValue.deserializeValue( - reader, - ReducerDef.getTypeScriptAlgebraicType() - ); - }, -}; - -export default ReducerDef; +}); diff --git a/crates/bindings-typescript/src/lib/autogen/sum_type_type.ts b/crates/bindings-typescript/src/lib/autogen/sum_type_type.ts index c8e1bd6313c..8ce504461db 100644 --- a/crates/bindings-typescript/src/lib/autogen/sum_type_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/sum_type_type.ts @@ -4,61 +4,15 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { SumTypeVariant } from './sum_type_variant_type'; -// Mark import as potentially unused -declare type __keep_SumTypeVariant = SumTypeVariant; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import SumTypeVariant from './sum_type_variant_type'; -export type SumType = { - variants: SumTypeVariant[]; -}; -let _cached_SumType_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const SumType = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_SumType_type_value) return _cached_SumType_type_value; - _cached_SumType_type_value = __AlgebraicTypeValue.Product({ elements: [] }); - _cached_SumType_type_value.value.elements.push({ - name: 'variants', - algebraicType: __AlgebraicTypeValue.Array( - SumTypeVariant.getTypeScriptAlgebraicType() - ), - }); - return _cached_SumType_type_value; - }, - - serialize(writer: __BinaryWriter, value: SumType): void { - __AlgebraicTypeValue.serializeValue( - writer, - SumType.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('SumType', { + get variants() { + return __t.array(SumTypeVariant); }, - - deserialize(reader: __BinaryReader): SumType { - return __AlgebraicTypeValue.deserializeValue( - reader, - SumType.getTypeScriptAlgebraicType() - ); - }, -}; - -export default SumType; +}); diff --git a/crates/bindings-typescript/src/lib/autogen/sum_type_variant_type.ts b/crates/bindings-typescript/src/lib/autogen/sum_type_variant_type.ts index 9f784c25997..72fac38f3d6 100644 --- a/crates/bindings-typescript/src/lib/autogen/sum_type_variant_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/sum_type_variant_type.ts @@ -4,71 +4,16 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { AlgebraicType } from './algebraic_type_type'; -// Mark import as potentially unused -declare type __keep_AlgebraicType = AlgebraicType; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import AlgebraicType from './algebraic_type_type'; -export type SumTypeVariant = { - name: string | undefined; - algebraicType: AlgebraicType; -}; -let _cached_SumTypeVariant_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const SumTypeVariant = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_SumTypeVariant_type_value) - return _cached_SumTypeVariant_type_value; - _cached_SumTypeVariant_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_SumTypeVariant_type_value.value.elements.push( - { - name: 'name', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.String - ), - }, - { - name: 'algebraicType', - algebraicType: AlgebraicType.getTypeScriptAlgebraicType(), - } - ); - return _cached_SumTypeVariant_type_value; - }, - - serialize(writer: __BinaryWriter, value: SumTypeVariant): void { - __AlgebraicTypeValue.serializeValue( - writer, - SumTypeVariant.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('SumTypeVariant', { + name: __t.option(__t.string()), + get algebraicType() { + return AlgebraicType; }, - - deserialize(reader: __BinaryReader): SumTypeVariant { - return __AlgebraicTypeValue.deserializeValue( - reader, - SumTypeVariant.getTypeScriptAlgebraicType() - ); - }, -}; - -export default SumTypeVariant; +}); diff --git a/crates/bindings-typescript/src/lib/autogen/table_access_type.ts b/crates/bindings-typescript/src/lib/autogen/table_access_type.ts index 884835677b3..fe49768d987 100644 --- a/crates/bindings-typescript/src/lib/autogen/table_access_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/table_access_type.ts @@ -4,68 +4,16 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import * as TableAccessVariants from './table_access_variants'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; // The tagged union or sum type for the algebraic type `TableAccess`. -export type TableAccess = - | TableAccessVariants.Public - | TableAccessVariants.Private; - -let _cached_TableAccess_type_value: __AlgebraicTypeType | null = null; - -// A value with helper functions to construct the type. -export const TableAccess = { - // Helper functions for constructing each variant of the tagged union. - // ``` - // const foo = Foo.A(42); - // assert!(foo.tag === "A"); - // assert!(foo.value === 42); - // ``` - Public: { tag: 'Public' } as const, - Private: { tag: 'Private' } as const, - - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_TableAccess_type_value) return _cached_TableAccess_type_value; - _cached_TableAccess_type_value = __AlgebraicTypeValue.Sum({ variants: [] }); - _cached_TableAccess_type_value.value.variants.push( - { - name: 'Public', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'Private', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - } - ); - return _cached_TableAccess_type_value; - }, - - serialize(writer: __BinaryWriter, value: TableAccess): void { - __AlgebraicTypeValue.serializeValue( - writer, - TableAccess.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): TableAccess { - return __AlgebraicTypeValue.deserializeValue( - reader, - TableAccess.getTypeScriptAlgebraicType() - ); - }, -}; +const TableAccess = __t.enum('TableAccess', { + Public: __t.unit(), + Private: __t.unit(), +}); export default TableAccess; diff --git a/crates/bindings-typescript/src/lib/autogen/table_access_variants.ts b/crates/bindings-typescript/src/lib/autogen/table_access_variants.ts deleted file mode 100644 index aee95dd15f1..00000000000 --- a/crates/bindings-typescript/src/lib/autogen/table_access_variants.ts +++ /dev/null @@ -1,21 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -/* eslint-disable */ -/* tslint:disable */ -import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; - -export type Public = { tag: 'Public' }; -export type Private = { tag: 'Private' }; diff --git a/crates/bindings-typescript/src/lib/autogen/table_desc_type.ts b/crates/bindings-typescript/src/lib/autogen/table_desc_type.ts index 78d3f6f7bb3..963baf7f87b 100644 --- a/crates/bindings-typescript/src/lib/autogen/table_desc_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/table_desc_type.ts @@ -4,65 +4,16 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { RawTableDefV8 } from './raw_table_def_v_8_type'; -// Mark import as potentially unused -declare type __keep_RawTableDefV8 = RawTableDefV8; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import RawTableDefV8 from './raw_table_def_v_8_type'; -export type TableDesc = { - schema: RawTableDefV8; - data: number; -}; -let _cached_TableDesc_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const TableDesc = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_TableDesc_type_value) return _cached_TableDesc_type_value; - _cached_TableDesc_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_TableDesc_type_value.value.elements.push( - { - name: 'schema', - algebraicType: RawTableDefV8.getTypeScriptAlgebraicType(), - }, - { name: 'data', algebraicType: __AlgebraicTypeValue.U32 } - ); - return _cached_TableDesc_type_value; - }, - - serialize(writer: __BinaryWriter, value: TableDesc): void { - __AlgebraicTypeValue.serializeValue( - writer, - TableDesc.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('TableDesc', { + get schema() { + return RawTableDefV8; }, - - deserialize(reader: __BinaryReader): TableDesc { - return __AlgebraicTypeValue.deserializeValue( - reader, - TableDesc.getTypeScriptAlgebraicType() - ); - }, -}; - -export default TableDesc; + data: __t.u32(), +}); diff --git a/crates/bindings-typescript/src/lib/autogen/table_type_type.ts b/crates/bindings-typescript/src/lib/autogen/table_type_type.ts index d2237db481b..5f03aa6f678 100644 --- a/crates/bindings-typescript/src/lib/autogen/table_type_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/table_type_type.ts @@ -4,66 +4,16 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import * as TableTypeVariants from './table_type_variants'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; // The tagged union or sum type for the algebraic type `TableType`. -export type TableType = TableTypeVariants.System | TableTypeVariants.User; - -let _cached_TableType_type_value: __AlgebraicTypeType | null = null; - -// A value with helper functions to construct the type. -export const TableType = { - // Helper functions for constructing each variant of the tagged union. - // ``` - // const foo = Foo.A(42); - // assert!(foo.tag === "A"); - // assert!(foo.value === 42); - // ``` - System: { tag: 'System' } as const, - User: { tag: 'User' } as const, - - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_TableType_type_value) return _cached_TableType_type_value; - _cached_TableType_type_value = __AlgebraicTypeValue.Sum({ variants: [] }); - _cached_TableType_type_value.value.variants.push( - { - name: 'System', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - }, - { - name: 'User', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - } - ); - return _cached_TableType_type_value; - }, - - serialize(writer: __BinaryWriter, value: TableType): void { - __AlgebraicTypeValue.serializeValue( - writer, - TableType.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): TableType { - return __AlgebraicTypeValue.deserializeValue( - reader, - TableType.getTypeScriptAlgebraicType() - ); - }, -}; +const TableType = __t.enum('TableType', { + System: __t.unit(), + User: __t.unit(), +}); export default TableType; diff --git a/crates/bindings-typescript/src/lib/autogen/table_type_variants.ts b/crates/bindings-typescript/src/lib/autogen/table_type_variants.ts deleted file mode 100644 index 8c80797c561..00000000000 --- a/crates/bindings-typescript/src/lib/autogen/table_type_variants.ts +++ /dev/null @@ -1,21 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -/* eslint-disable */ -/* tslint:disable */ -import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; - -export type System = { tag: 'System' }; -export type User = { tag: 'User' }; diff --git a/crates/bindings-typescript/src/lib/autogen/type_alias_type.ts b/crates/bindings-typescript/src/lib/autogen/type_alias_type.ts index 6bb6000a51b..b0b4b2bd900 100644 --- a/crates/bindings-typescript/src/lib/autogen/type_alias_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/type_alias_type.ts @@ -4,59 +4,13 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; -export type TypeAlias = { - name: string; - ty: number; -}; -let _cached_TypeAlias_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const TypeAlias = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_TypeAlias_type_value) return _cached_TypeAlias_type_value; - _cached_TypeAlias_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_TypeAlias_type_value.value.elements.push( - { name: 'name', algebraicType: __AlgebraicTypeValue.String }, - { name: 'ty', algebraicType: __AlgebraicTypeValue.U32 } - ); - return _cached_TypeAlias_type_value; - }, - - serialize(writer: __BinaryWriter, value: TypeAlias): void { - __AlgebraicTypeValue.serializeValue( - writer, - TypeAlias.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): TypeAlias { - return __AlgebraicTypeValue.deserializeValue( - reader, - TypeAlias.getTypeScriptAlgebraicType() - ); - }, -}; - -export default TypeAlias; +export default __t.object('TypeAlias', { + name: __t.string(), + ty: __t.u32(), +}); diff --git a/crates/bindings-typescript/src/lib/autogen/typespace_type.ts b/crates/bindings-typescript/src/lib/autogen/typespace_type.ts index 7eb7d338238..b2215b5af73 100644 --- a/crates/bindings-typescript/src/lib/autogen/typespace_type.ts +++ b/crates/bindings-typescript/src/lib/autogen/typespace_type.ts @@ -4,63 +4,15 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ConnectionId as __ConnectionId, - Identity as __Identity, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type TableHandle as __TableHandle, -} from '../../index'; -import { AlgebraicType } from './algebraic_type_type'; -// Mark import as potentially unused -declare type __keep_AlgebraicType = AlgebraicType; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import AlgebraicType from './algebraic_type_type'; -export type Typespace = { - types: AlgebraicType[]; -}; -let _cached_Typespace_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const Typespace = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_Typespace_type_value) return _cached_Typespace_type_value; - _cached_Typespace_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_Typespace_type_value.value.elements.push({ - name: 'types', - algebraicType: __AlgebraicTypeValue.Array( - AlgebraicType.getTypeScriptAlgebraicType() - ), - }); - return _cached_Typespace_type_value; - }, - - serialize(writer: __BinaryWriter, value: Typespace): void { - __AlgebraicTypeValue.serializeValue( - writer, - Typespace.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('Typespace', { + get types() { + return __t.array(AlgebraicType); }, - - deserialize(reader: __BinaryReader): Typespace { - return __AlgebraicTypeValue.deserializeValue( - reader, - Typespace.getTypeScriptAlgebraicType() - ); - }, -}; - -export default Typespace; +}); diff --git a/crates/bindings-typescript/src/lib/connection_id.ts b/crates/bindings-typescript/src/lib/connection_id.ts index 64da6361395..a32bbdf4f14 100644 --- a/crates/bindings-typescript/src/lib/connection_id.ts +++ b/crates/bindings-typescript/src/lib/connection_id.ts @@ -1,5 +1,5 @@ import { AlgebraicType } from './algebraic_type'; -import { hexStringToU128, u128ToHexString, u128ToUint8Array } from './utils'; +import { hexStringToU128, u128ToHexString, u128ToUint8Array } from './util'; export type ConnectionIdAlgebraicType = { tag: 'Product'; @@ -63,6 +63,13 @@ export class ConnectionId { return this.__connection_id__ == other.__connection_id__; } + /** + * Check if two connection IDs are equal. + */ + equals(other: ConnectionId): boolean { + return this.isEqual(other); + } + /** * Print the connection ID as a hexadecimal string. */ diff --git a/crates/bindings-typescript/src/server/constraints.ts b/crates/bindings-typescript/src/lib/constraints.ts similarity index 81% rename from crates/bindings-typescript/src/server/constraints.ts rename to crates/bindings-typescript/src/lib/constraints.ts index 51d80f76bc9..5bd2936ad62 100644 --- a/crates/bindings-typescript/src/server/constraints.ts +++ b/crates/bindings-typescript/src/lib/constraints.ts @@ -38,3 +38,14 @@ export type ColumnIsUnique> = M extends | { isPrimaryKey: true } ? true : false; + +/** + * Constraint helper type used *inside* {@link table} to enforce the type + * of constraint definitions. + */ +export type ConstraintOpts = { + name?: string; +} & ( + | { constraint: 'unique'; columns: [AllowedCol] } + | { constraint: 'primaryKey'; columns: [AllowedCol] } +); diff --git a/crates/bindings-typescript/src/lib/identity.ts b/crates/bindings-typescript/src/lib/identity.ts index 3b2b0e60ed8..6cad2761b5e 100644 --- a/crates/bindings-typescript/src/lib/identity.ts +++ b/crates/bindings-typescript/src/lib/identity.ts @@ -1,5 +1,5 @@ import { AlgebraicType } from './algebraic_type'; -import { hexStringToU256, u256ToHexString, u256ToUint8Array } from './utils'; +import { hexStringToU256, u256ToHexString, u256ToUint8Array } from './util'; export type IdentityAlgebraicType = { tag: 'Product'; @@ -36,12 +36,19 @@ export class Identity { } /** - * Compare two identities for equality. + * Check if two identities are equal. */ isEqual(other: Identity): boolean { return this.toHexString() === other.toHexString(); } + /** + * Check if two identities are equal. + */ + equals(other: Identity): boolean { + return this.isEqual(other); + } + /** * Print the identity as a hexadecimal string. */ diff --git a/crates/bindings-typescript/src/server/indexes.ts b/crates/bindings-typescript/src/lib/indexes.ts similarity index 89% rename from crates/bindings-typescript/src/server/indexes.ts rename to crates/bindings-typescript/src/lib/indexes.ts index be3185d207f..75e0b0a0b8d 100644 --- a/crates/bindings-typescript/src/server/indexes.ts +++ b/crates/bindings-typescript/src/lib/indexes.ts @@ -1,7 +1,7 @@ import type { RowType, UntypedTableDef } from './table'; import type { ColumnMetadata, IndexTypes } from './type_builders'; import type { CollapseTuple, Prettify } from './type_util'; -import { Range } from './range'; +import { Range } from '../server/range'; import type { ColumnIsUnique } from './constraints'; /** @@ -46,13 +46,6 @@ export type Indexes< [k in keyof I]: Index; }; -export type ReadonlyIndexes< - TableDef extends UntypedTableDef, - I extends Record>, -> = { - [k in keyof I]: ReadonlyIndex; -}; - /** * A type representing a database index, which can be either unique or ranged. */ @@ -63,6 +56,20 @@ export type Index< ? UniqueIndex : RangedIndex; +/** + * A type representing a collection of read-only indexes defined on a table. + */ +export type ReadonlyIndexes< + TableDef extends UntypedTableDef, + I extends Record>, +> = { + [k in keyof I]: ReadonlyIndex; +}; + +/** + * A type representing a read-only database index, which can be either unique or ranged. + * This type only exposes read-only operations. + */ export type ReadonlyIndex< TableDef extends UntypedTableDef, I extends UntypedIndex, @@ -70,12 +77,15 @@ export type ReadonlyIndex< ? ReadonlyUniqueIndex : ReadonlyRangedIndex; -export interface ReadonlyUniqueIndex< +/** + * A type representing a read-only unique index on a database table. + */ +export type ReadonlyUniqueIndex< TableDef extends UntypedTableDef, I extends UntypedIndex, -> { - find(col_val: IndexVal): RowType | null; -} +> = { + find(colVal: IndexVal): RowType | null; +}; /** * A type representing a unique index on a database table. @@ -85,10 +95,13 @@ export interface UniqueIndex< TableDef extends UntypedTableDef, I extends UntypedIndex, > extends ReadonlyUniqueIndex { - delete(col_val: IndexVal): boolean; - update(col_val: RowType): RowType; + delete(colVal: IndexVal): boolean; + update(colVal: RowType): RowType; } +/** + * A type representing a read-only ranged index on a database table. + */ export interface ReadonlyRangedIndex< TableDef extends UntypedTableDef, I extends UntypedIndex, diff --git a/crates/bindings-typescript/src/lib/reducer_schema.ts b/crates/bindings-typescript/src/lib/reducer_schema.ts new file mode 100644 index 00000000000..c68a350f2d8 --- /dev/null +++ b/crates/bindings-typescript/src/lib/reducer_schema.ts @@ -0,0 +1,38 @@ +import type { ProductType } from './algebraic_type'; +import type RawReducerDefV9 from './autogen/raw_reducer_def_v_9_type'; +import type { ParamsObj } from './reducers'; +import type { Infer, RowBuilder, RowObj } from './type_builders'; +import type { CamelCase } from './type_util'; + +/** + * Represents a handle to a database reducer, including its name and argument type. + */ +export type ReducerSchema< + ReducerName extends string, + Params extends ParamsObj | RowObj, +> = { + /** + * The name of the reducer. + */ + readonly reducerName: ReducerName; + + /** + * The accessor name for the reducer. + */ + readonly accessorName: CamelCase; + + /** + * The TypeBuilder representation of the reducer's parameter type. + */ + readonly params: RowBuilder; + + /** + * The {@link ProductType} representing the structure of the reducer's parameters. + */ + readonly paramsSpacetimeType: ProductType; + + /** + * The {@link RawReducerDefV9} of the configured reducer. + */ + readonly reducerDef: Infer; +}; diff --git a/crates/bindings-typescript/src/server/reducers.ts b/crates/bindings-typescript/src/lib/reducers.ts similarity index 69% rename from crates/bindings-typescript/src/server/reducers.ts rename to crates/bindings-typescript/src/lib/reducers.ts index 0735cc004c1..f8b32bd1313 100644 --- a/crates/bindings-typescript/src/server/reducers.ts +++ b/crates/bindings-typescript/src/lib/reducers.ts @@ -1,17 +1,22 @@ -import type { ProductType } from '../lib/algebraic_type'; -import Lifecycle from '../lib/autogen/lifecycle_type'; -import type RawReducerDefV9 from '../lib/autogen/raw_reducer_def_v_9_type'; -import type { ConnectionId } from '../lib/connection_id'; -import type { Identity } from '../lib/identity'; -import type { Timestamp } from '../lib/timestamp'; +import type { ProductType } from './algebraic_type'; +import Lifecycle from './autogen/lifecycle_type'; +import type RawReducerDefV9 from './autogen/raw_reducer_def_v_9_type'; +import type { ConnectionId } from './connection_id'; +import type { Identity } from './identity'; +import type { Timestamp } from './timestamp'; +import type { UntypedReducersDef } from '../sdk/reducers'; +import type { DbView } from '../server/db_view'; import { MODULE_DEF, type UntypedSchemaDef } from './schema'; -import type { Table } from './table'; -import type { - InferTypeOfRow, +import { RowBuilder, - RowObj, - TypeBuilder, + type Infer, + type InferTypeOfRow, + type RowObj, + type TypeBuilder, } from './type_builders'; +import type { ReducerSchema } from './reducer_schema'; +import { toCamelCase } from './util'; +import type { CamelCase } from './type_util'; /** * Helper to extract the parameter types from an object type @@ -58,13 +63,6 @@ export type Reducer< payload: ParamsAsObject ) => void | { tag: 'ok' } | { tag: 'err'; value: string }; -/** - * A type representing the database view, mapping table names to their corresponding Table handles. - */ -export type DbView = { - readonly [Tbl in SchemaDef['tables'][number] as Tbl['name']]: Table; -}; - /** * Authentication information for the caller of a reducer. */ @@ -131,16 +129,17 @@ export function pushReducer( name: string, params: RowObj | RowBuilder, fn: Reducer, - lifecycle?: RawReducerDefV9['lifecycle'] + lifecycle?: Infer['lifecycle'] ): void { - if (existingReducers.has(name)) + if (existingReducers.has(name)) { throw new TypeError(`There is already a reducer with the name '${name}'`); + } existingReducers.add(name); const paramType: ProductType = { elements: Object.entries(params).map(([n, c]) => ({ name: n, - algebraicType: ('typeBuilder' in c ? c.typeBuilder : c).algebraicType, + algebraicType: c.algebraicType, })), }; @@ -263,3 +262,109 @@ export function clientDisconnected< >(name: string, params: Params, fn: Reducer): void { pushReducer(name, params, fn, Lifecycle.OnDisconnect); } + +class Reducers { + reducersType: ReducersDef; + + constructor(handles: readonly ReducerSchema[]) { + this.reducersType = reducersToSchema(handles) as ReducersDef; + } +} + +/** + * Helper type to convert an array of TableSchema into a schema definition + */ +type ReducersToSchema[]> = { + reducers: { + /** @type {UntypedReducerDef} */ + readonly [i in keyof T]: { + name: T[i]['reducerName']; + accessorName: CamelCase; + params: T[i]['params']['row']; + paramsType: T[i]['paramsSpacetimeType']; + }; + }; +}; + +export function reducersToSchema< + const T extends readonly ReducerSchema[], +>(reducers: T): ReducersToSchema { + const mapped = reducers.map(r => { + const paramsRow = r.params.row; + + return { + name: r.reducerName, + // Prefer the schema's own accessorName if present at runtime; otherwise derive it. + accessorName: r.accessorName, + params: paramsRow, + paramsType: r.paramsSpacetimeType, + } as const; + }) as { + readonly [I in keyof T]: { + name: T[I]['reducerName']; + accessorName: T[I]['accessorName']; + params: T[I]['params']['row']; + paramsType: T[I]['paramsSpacetimeType']; + }; + }; + + const result = { reducers: mapped } satisfies ReducersToSchema; + return result; +} + +/** + * Creates a schema from table definitions + * @param handles - Array of table handles created by table() function + * @returns ColumnBuilder representing the complete database schema + * @example + * ```ts + * const s = schema( + * table({ name: 'user' }, userType), + * table({ name: 'post' }, postType) + * ); + * ``` + */ +export function reducers[]>( + ...handles: H +): Reducers>; + +/** + * Creates a schema from table definitions (array overload) + * @param handles - Array of table handles created by table() function + * @returns ColumnBuilder representing the complete database schema + */ +export function reducers[]>( + handles: H +): Reducers>; + +export function reducers[]>( + ...args: [H] | H +): Reducers> { + const handles = ( + args.length === 1 && Array.isArray(args[0]) ? args[0] : args + ) as H; + return new Reducers(handles); +} + +export function reducerSchema< + ReducerName extends string, + Params extends ParamsObj, +>(name: ReducerName, params: Params): ReducerSchema { + const paramType: ProductType = { + elements: Object.entries(params).map(([n, c]) => ({ + name: n, + algebraicType: c.algebraicType, + })), + }; + return { + reducerName: name, + accessorName: toCamelCase(name), + params: new RowBuilder(params), + paramsSpacetimeType: paramType, + reducerDef: { + name, + params: paramType, + lifecycle: undefined, + }, + }; +} diff --git a/crates/bindings-typescript/src/server/schema.ts b/crates/bindings-typescript/src/lib/schema.ts similarity index 69% rename from crates/bindings-typescript/src/server/schema.ts rename to crates/bindings-typescript/src/lib/schema.ts index d9cdede9a3f..367a0018929 100644 --- a/crates/bindings-typescript/src/server/schema.ts +++ b/crates/bindings-typescript/src/lib/schema.ts @@ -1,13 +1,20 @@ -import type RawTableDefV9 from '../lib/autogen/raw_table_def_v_9_type'; -import type Typespace from '../lib/autogen/typespace_type'; +import type RawTableDefV9 from './autogen/raw_table_def_v_9_type'; +import type Typespace from './autogen/typespace_type'; import { // eslint-disable-next-line @typescript-eslint/no-unused-vars - type ColumnBuilder, + ColumnBuilder, + ProductBuilder, + RefBuilder, + RowBuilder, + SumBuilder, + type ElementsObj, + type Infer, type RowObj, // eslint-disable-next-line @typescript-eslint/no-unused-vars type TypeBuilder, + type VariantsObj, } from './type_builders'; -import type { TableSchema, UntypedTableDef } from './table'; +import type { UntypedTableDef } from './table'; import { clientConnected, clientDisconnected, @@ -16,12 +23,16 @@ import { type ParamsObj, type Reducer, } from './reducers'; -import type RawModuleDefV9 from '../lib/autogen/raw_module_def_v_9_type'; +import type RawModuleDefV9 from './autogen/raw_module_def_v_9_type'; import { AlgebraicType, + type AlgebraicTypeType, type AlgebraicTypeVariants, -} from '../lib/algebraic_type'; -import type RawScopedTypeNameV9 from '../lib/autogen/raw_scoped_type_name_v_9_type'; +} from './algebraic_type'; +import type RawScopedTypeNameV9 from './autogen/raw_scoped_type_name_v_9_type'; +import type { CamelCase } from './type_util'; +import type { TableSchema } from './table_schema'; +import { toCamelCase } from './util'; import { defineView, type AnonymousViewFn, @@ -29,10 +40,63 @@ import { type ViewReturnTypeBuilder, } from './views'; +export type TableNamesOf = + S['tables'][number]['name']; + +/** + * An untyped representation of the database schema. + */ +export type UntypedSchemaDef = { + tables: readonly UntypedTableDef[]; +}; + +/** + * Helper type to convert an array of TableSchema into a schema definition + */ +type TablesToSchema[]> = { + tables: { + /** @type {UntypedTableDef} */ + readonly [i in keyof T]: { + name: T[i]['tableName']; + accessorName: CamelCase; + columns: T[i]['rowType']['row']; + rowType: T[i]['rowSpacetimeType']; + indexes: T[i]['idxs']; + }; + }; +}; + +export function tablesToSchema< + const T extends readonly TableSchema[], +>(tables: T): TablesToSchema { + const result = { + tables: tables.map(schema => { + return { + name: schema.tableName, + accessorName: toCamelCase(schema.tableName), + columns: schema.rowType.row, // typed as T[i]['rowType']['row'] under TablesToSchema + rowType: schema.rowSpacetimeType, + // UntypedTableDef expects mutable array; idxs are readonly, spread to copy. + indexes: [...schema.idxs], + } as const; + }) as { + // preserve tuple indices so the return type matches `[i in keyof T]` + readonly [I in keyof T]: { + name: T[I]['tableName']; + accessorName: CamelCase; + columns: T[I]['rowType']['row']; + rowType: T[I]['rowSpacetimeType']; + indexes: T[I]['idxs']; + }; + }, + } satisfies TablesToSchema; + return result; +} + /** * The global module definition that gets populated by calls to `reducer()` and lifecycle hooks. */ -export const MODULE_DEF: RawModuleDefV9 = { +export const MODULE_DEF: Infer = { typespace: { types: [] }, tables: [], reducers: [], @@ -43,61 +107,112 @@ export const MODULE_DEF: RawModuleDefV9 = { const COMPOUND_TYPES = new Map< AlgebraicTypeVariants.Product | AlgebraicTypeVariants.Sum, - AlgebraicTypeVariants.Ref + RefBuilder >(); -export function addType( - name: string | undefined, - ty: T -): T | AlgebraicTypeVariants.Ref { - if ( - (ty.tag === 'Product' && (ty.value.elements.length > 0 || name != null)) || - (ty.tag === 'Sum' && (ty.value.variants.length > 0 || name != null)) - ) { - let r = COMPOUND_TYPES.get(ty); - if (r == null) { - r = AlgebraicType.Ref(MODULE_DEF.typespace.types.length); - MODULE_DEF.typespace.types.push(ty); - COMPOUND_TYPES.set(ty, r); - if (name != null) - MODULE_DEF.types.push({ - name: splitName(name), - ty: r.value, - customOrdering: true, - }); - } +/** + * Resolves the actual type of a TypeBuilder by following its references until it reaches a non-ref type. + * @param typespace The typespace to resolve types against. + * @param typeBuilder The TypeBuilder to resolve. + * @returns The resolved algebraic type. + */ +export function resolveType( + typespace: Infer, + typeBuilder: TypeBuilder +): AT { + let ty: AlgebraicType = typeBuilder.algebraicType; + while (ty.tag === 'Ref') { + ty = typespace.types[ty.value]; + } + return ty as AT; +} + +/** + * Adds a type to the module definition's typespace as a `Ref` if it is a named compound type (Product or Sum). + * Otherwise, returns the type as is. + * @param name + * @param ty + * @returns + */ +export function registerTypesRecursively( + typeBuilder: + | SumBuilder + | ProductBuilder + | RowBuilder +): RefBuilder { + const ty = typeBuilder.algebraicType; + const name = typeBuilder.typeName; + + let r = COMPOUND_TYPES.get(ty); + if (r != null) { + // Already added to typespace return r; - } else { - return ty; } + + // Recursively register nested compound types + if (typeBuilder instanceof RowBuilder) { + for (const [name, elem] of Object.entries(typeBuilder.row)) { + if ( + !( + elem instanceof ProductBuilder || + elem instanceof SumBuilder || + elem instanceof RowBuilder + ) + ) { + continue; + } + typeBuilder.row[name] = new ColumnBuilder( + registerTypesRecursively(elem), + {} + ); + } + } else if (typeBuilder instanceof ProductBuilder) { + for (const [name, elem] of Object.entries(typeBuilder.elements)) { + if ( + !( + elem instanceof ProductBuilder || + elem instanceof SumBuilder || + elem instanceof RowBuilder + ) + ) { + continue; + } + typeBuilder.elements[name] = registerTypesRecursively(elem); + } + } else if (typeBuilder instanceof SumBuilder) { + for (const [name, variant] of Object.entries(typeBuilder.variants)) { + if ( + !( + variant instanceof ProductBuilder || + variant instanceof SumBuilder || + variant instanceof RowBuilder + ) + ) { + continue; + } + typeBuilder.variants[name] = registerTypesRecursively(variant); + } + } + + // Add to typespace and return a Ref type + r = new RefBuilder(MODULE_DEF.typespace.types.length); + MODULE_DEF.typespace.types.push(ty); + + COMPOUND_TYPES.set(ty, r); + if (name !== undefined) + MODULE_DEF.types.push({ + name: splitName(name), + ty: r.ref, + customOrdering: true, + }); + return r; } -export function splitName(name: string): RawScopedTypeNameV9 { +export function splitName(name: string): Infer { const scope = name.split('.'); return { name: scope.pop()!, scope }; } -/** - * An untyped representation of the database schema. - */ -export type UntypedSchemaDef = { - tables: readonly UntypedTableDef[]; -}; - -/** - * Helper type to convert an array of TableSchema into a schema definition - */ -type TablesToSchema[]> = { - tables: { - /** @type {UntypedTableDef} */ - readonly [i in keyof T]: { - name: T[i]['tableName']; - columns: T[i]['rowType']['row']; - indexes: T[i]['idxs']; - }; - }; -}; - /** * The Schema class represents the database schema for a SpacetimeDB application. * It encapsulates the table definitions and typespace, and provides methods to define @@ -133,13 +248,19 @@ type TablesToSchema[]> = { // for the tables from the schema object, e.g. `spacetimedb.user.type` would // be the type of the user table. class Schema { - readonly tablesDef: { tables: RawTableDefV9[] }; - readonly typespace: Typespace; - readonly schemaType!: S; + readonly tablesDef: { tables: Infer[] }; + readonly typespace: Infer; + readonly schemaType: S; - constructor(tables: RawTableDefV9[], typespace: Typespace) { + constructor( + tables: Infer[], + typespace: Infer, + handles: readonly TableSchema[] + ) { this.tablesDef = { tables }; this.typespace = typespace; + // TODO: TableSchema and TableDef should really be unified + this.schemaType = tablesToSchema(handles) as S; } /** @@ -376,22 +497,6 @@ export function schema[]>( ...handles: H ): Schema>; -/** - * Creates a schema from table definitions - * @param handles - Array of table handles created by table() function - * @returns ColumnBuilder representing the complete database schema - * @example - * ```ts - * const s = schema( - * table({ name: 'user' }, userType), - * table({ name: 'post' }, postType) - * ); - * ``` - */ -export function schema[]>( - ...handles: H -): Schema>; - /** * Creates a schema from table definitions (array overload) * @param handles - Array of table handles created by table() function @@ -413,14 +518,12 @@ export function schema[]>( * ); * ``` */ -export function schema( - ...args: - | [readonly TableSchema[]] - | readonly TableSchema[] -): Schema { - const handles: readonly TableSchema[] = - args.length === 1 && Array.isArray(args[0]) ? args[0] : args; - +export function schema[]>( + ...args: [H] | H +): Schema> { + const handles = ( + args.length === 1 && Array.isArray(args[0]) ? args[0] : args + ) as H; const tableDefs = handles.map(h => h.tableDef); // Side-effect: @@ -437,5 +540,19 @@ export function schema( // .join('\n') // ); - return new Schema(tableDefs, MODULE_DEF.typespace); + return new Schema(tableDefs, MODULE_DEF.typespace, handles); +} + +type HasAccessor = { accessorName: PropertyKey }; + +export type ConvertToAccessorMap = { + [Tbl in TableDefs[number] as Tbl['accessorName']]: Tbl; +}; + +export function convertToAccessorMap( + arr: T +): ConvertToAccessorMap { + return Object.fromEntries( + arr.map(v => [v.accessorName, v]) + ) as ConvertToAccessorMap; } diff --git a/crates/bindings-typescript/src/server/table.ts b/crates/bindings-typescript/src/lib/table.ts similarity index 80% rename from crates/bindings-typescript/src/server/table.ts rename to crates/bindings-typescript/src/lib/table.ts index 6c2d584166a..6f18b2603ae 100644 --- a/crates/bindings-typescript/src/server/table.ts +++ b/crates/bindings-typescript/src/lib/table.ts @@ -1,10 +1,10 @@ -import { AlgebraicType } from '../lib/algebraic_type'; -import type RawConstraintDefV9 from '../lib/autogen/raw_constraint_def_v_9_type'; -import RawIndexAlgorithm from '../lib/autogen/raw_index_algorithm_type'; -import type RawIndexDefV9 from '../lib/autogen/raw_index_def_v_9_type'; -import type RawSequenceDefV9 from '../lib/autogen/raw_sequence_def_v_9_type'; -import type RawTableDefV9 from '../lib/autogen/raw_table_def_v_9_type'; -import type { AllUnique } from './constraints'; +import { ProductType } from './algebraic_type'; +import type RawConstraintDefV9 from './autogen/raw_constraint_def_v_9_type'; +import RawIndexAlgorithm from './autogen/raw_index_algorithm_type'; +import type RawIndexDefV9 from './autogen/raw_index_def_v_9_type'; +import type RawSequenceDefV9 from './autogen/raw_sequence_def_v_9_type'; +import type RawTableDefV9 from './autogen/raw_table_def_v_9_type'; +import type { AllUnique, ConstraintOpts } from './constraints'; import type { ColumnIndex, IndexColumns, @@ -12,11 +12,18 @@ import type { IndexOpts, ReadonlyIndexes, } from './indexes'; -import { MODULE_DEF, splitName } from './schema'; +import { + registerTypesRecursively, + MODULE_DEF, + resolveType, + splitName, +} from './schema'; +import type { TableSchema } from './table_schema'; import { RowBuilder, type ColumnBuilder, type ColumnMetadata, + type Infer, type InferTypeOfRow, type RowObj, type TypeBuilder, @@ -40,7 +47,9 @@ export type RowType = InferTypeOfRow< export type CoerceColumn< Col extends TypeBuilder | ColumnBuilder, > = - Col extends TypeBuilder ? ColumnBuilder : Col; + Col extends TypeBuilder + ? ColumnBuilder> + : Col; /** * Coerces a RowObj where TypeBuilders are replaced with ColumnBuilders @@ -59,7 +68,9 @@ type CoerceArray[]> = X; */ export type UntypedTableDef = { name: string; + accessorName: string; columns: Record>>; + rowType: ProductType; indexes: readonly IndexOpts[]; }; @@ -114,6 +125,7 @@ export type TableOpts = { name: string; public?: boolean; indexes?: IndexOpts[]; // declarative multi‑column indexes + constraints?: ConstraintOpts[]; scheduled?: string; }; @@ -169,37 +181,6 @@ export interface TableMethods delete(row: RowType): boolean; } -/** - * Represents a handle to a database table, including its name, row type, and row spacetime type. - */ -export type TableSchema< - TableName extends string, - Row extends Record>, - Idx extends readonly IndexOpts[], -> = { - readonly rowType: RowBuilder; - - /** - * The name of the table. - */ - readonly tableName: TableName; - - /** - * The {@link AlgebraicType} representing the structure of a row in the table. - */ - readonly rowSpacetimeType: AlgebraicType; - - /** - * The {@link RawTableDefV9} of the configured table - */ - readonly tableDef: RawTableDefV9; - - /** - * The indexes defined on the table. - */ - readonly idxs: Idx; -}; - /** * Defines a database table with schema and options * @param opts - Table configuration including name, indexes, and access control @@ -235,16 +216,18 @@ export function table>( row = new RowBuilder(row); } - row.resolveType().value.elements.forEach((elem, i) => { + const rowTypeRef = registerTypesRecursively(row); + + row.algebraicType.value.elements.forEach((elem, i) => { colIds.set(elem.name, i); colNameList.push(elem.name); }); // gather primary keys, per‑column indexes, uniques, sequences const pk: ColList = []; - const indexes: RawIndexDefV9[] = []; - const constraints: RawConstraintDefV9[] = []; - const sequences: RawSequenceDefV9[] = []; + const indexes: Infer[] = []; + const constraints: Infer[] = []; + const sequences: Infer[] = []; let scheduleAtCol: ColId | undefined; @@ -261,7 +244,7 @@ export function table>( if (meta.indexType || isUnique) { const algo = meta.indexType ?? 'btree'; const id = colIds.get(name)!; - let algorithm: RawIndexAlgorithm; + let algorithm: Infer; switch (algo) { case 'btree': algorithm = RawIndexAlgorithm.BTree([id]); @@ -302,7 +285,7 @@ export function table>( // convert explicit multi‑column indexes coming from options.indexes for (const indexOpts of userIndexes ?? []) { - let algorithm: RawIndexAlgorithm; + let algorithm: Infer; switch (indexOpts.algorithm) { case 'btree': algorithm = { @@ -317,6 +300,21 @@ export function table>( indexes.push({ name: undefined, accessorName: indexOpts.name, algorithm }); } + // add explicit constraints from options.constraints + for (const constraintOpts of opts.constraints ?? []) { + if (constraintOpts.constraint === 'unique') { + const data: Infer['data'] = { + tag: 'Unique', + value: { columns: constraintOpts.columns.map(c => colIds.get(c)!) }, + }; + constraints.push({ name: constraintOpts.name, data }); + continue; + } + if (constraintOpts.constraint === 'primaryKey') { + pk.push(...constraintOpts.columns.map(c => colIds.get(c)!)); + } + } + for (const index of indexes) { const cols = index.algorithm.tag === 'Direct' @@ -329,9 +327,9 @@ export function table>( // Temporarily set the type ref to 0. We will set this later // in the schema function. - const tableDef: RawTableDefV9 = { + const tableDef: Infer = { name, - productTypeRef: row.algebraicType.value as number, + productTypeRef: rowTypeRef.ref, primaryKey: pk, indexes, constraints, @@ -348,19 +346,21 @@ export function table>( tableAccess: { tag: isPublic ? 'Public' : 'Private' }, }; - if (!row.nameProvided) { + if (row.typeName === undefined) { MODULE_DEF.types.push({ customOrdering: true, name: splitName(name), - ty: row.algebraicType.value as number, + ty: rowTypeRef.ref, }); } - const productType = AlgebraicType.Product({ - elements: row.resolveType().value.elements.map(elem => { - return { name: elem.name, algebraicType: elem.algebraicType }; - }), - }); + const productType = { + elements: resolveType(MODULE_DEF.typespace, row).value.elements.map( + elem => { + return { name: elem.name, algebraicType: elem.algebraicType }; + } + ), + }; return { rowType: row as RowBuilder>, diff --git a/crates/bindings-typescript/src/lib/table_schema.ts b/crates/bindings-typescript/src/lib/table_schema.ts new file mode 100644 index 00000000000..540af16673a --- /dev/null +++ b/crates/bindings-typescript/src/lib/table_schema.ts @@ -0,0 +1,38 @@ +import type { ProductType } from './algebraic_type'; +import type RawTableDefV9 from './autogen/raw_table_def_v_9_type'; +import type { IndexOpts } from './indexes'; +import type { ColumnBuilder, Infer, RowBuilder } from './type_builders'; + +/** + * Represents a handle to a database table, including its name, row type, and row spacetime type. + */ +export type TableSchema< + TableName extends string, + Row extends Record>, + Idx extends readonly IndexOpts[], +> = { + /** + * The name of the table. + */ + readonly tableName: TableName; + + /** + * The TypeBuilder representation of the type of the rows in the table. + **/ + readonly rowType: RowBuilder; + + /** + * The {@link ProductType} representing the structure of a row in the table. + */ + readonly rowSpacetimeType: ProductType; + + /** + * The {@link RawTableDefV9} of the configured table + */ + readonly tableDef: Infer; + + /** + * The indexes defined on the table. + */ + readonly idxs: Idx; +}; diff --git a/crates/bindings-typescript/src/server/type_builders.test-d.ts b/crates/bindings-typescript/src/lib/type_builders.test-d.ts similarity index 100% rename from crates/bindings-typescript/src/server/type_builders.test-d.ts rename to crates/bindings-typescript/src/lib/type_builders.test-d.ts diff --git a/crates/bindings-typescript/src/server/type_builders.ts b/crates/bindings-typescript/src/lib/type_builders.ts similarity index 56% rename from crates/bindings-typescript/src/server/type_builders.ts rename to crates/bindings-typescript/src/lib/type_builders.ts index 4fa2b5484db..ebd8ff36795 100644 --- a/crates/bindings-typescript/src/server/type_builders.ts +++ b/crates/bindings-typescript/src/lib/type_builders.ts @@ -1,27 +1,23 @@ -import { - AlgebraicType, - ConnectionId, - Identity, - ScheduleAt, - TimeDuration, - Timestamp, - Option, - type AlgebraicTypeVariants, - type ConnectionIdAlgebraicType, - type IdentityAlgebraicType, - type TimeDurationAlgebraicType, - type TimestampAlgebraicType, -} from '..'; -import type { OptionAlgebraicType } from '../lib/option'; -import { addType, MODULE_DEF } from './schema'; +import { AlgebraicType, type AlgebraicTypeVariants } from './algebraic_type'; +import type BinaryReader from './binary_reader'; +import type BinaryWriter from './binary_writer'; +import { ConnectionId, type ConnectionIdAlgebraicType } from './connection_id'; +import { Identity, type IdentityAlgebraicType } from './identity'; +import { Option, type OptionAlgebraicType } from './option'; +import ScheduleAt from './schedule_at'; import type { CoerceRow } from './table'; -import { set, type Set } from './type_util'; +import { TimeDuration, type TimeDurationAlgebraicType } from './time_duration'; +import { Timestamp, type TimestampAlgebraicType } from './timestamp'; +import { set, type Prettify, type SetField } from './type_util'; + +// Used in codegen files +export { type AlgebraicTypeType } from './algebraic_type'; /** * Helper type to extract the TypeScript type from a TypeBuilder */ export type InferTypeOfTypeBuilder> = - T extends TypeBuilder ? U : never; + T extends TypeBuilder ? Prettify : never; /** * Helper type to extract the Spacetime type from a TypeBuilder @@ -54,7 +50,7 @@ type CollapseColumn< */ export type RowObj = Record< string, - TypeBuilder | ColumnBuilder + TypeBuilder | ColumnBuilder> >; /** @@ -83,7 +79,7 @@ type RowType = { /** * Type which represents a valid argument to the ProductColumnBuilder */ -type ElementsObj = Record>; +export type ElementsObj = Record>; /** * Type which converts the elements of ElementsObj to a ProductType elements array @@ -108,10 +104,12 @@ type ObjectType = { [K in keyof Elements]: InferTypeOfTypeBuilder; }; -type VariantsObj = Record>; +export type VariantsObj = Record>; type UnitBuilder = ProductBuilder<{}>; type SimpleVariantsObj = Record; +type IsUnit = B extends UnitBuilder ? true : false; + /** * A type which converts the elements of ElementsObj to a TypeScript object type. * It works by `Infer`ing the types of the column builders which are the values of @@ -120,8 +118,10 @@ type SimpleVariantsObj = Record; * e.g. { A: I32TypeBuilder, B: StringBuilder } -> { tag: "A", value: number } | { tag: "B", value: string } */ type EnumType = { - [K in keyof Variants]: { tag: K; value: InferTypeOfTypeBuilder }; -}[keyof Variants]; + [K in keyof Variants & string]: IsUnit extends true + ? { tag: K } + : { tag: K; value: InferTypeOfTypeBuilder }; +}[keyof Variants & string]; /** * Type which converts the elements of VariantsObj to a SumType variants array @@ -136,8 +136,7 @@ type VariantsArrayFromVariantsObj = { * and the corresponding `AlgebraicType`. */ export class TypeBuilder - implements Optional -{ + implements Optional { /** * The TypeScript phantom type. This is not stored at runtime, * but is visible to the compiler @@ -153,21 +152,23 @@ export class TypeBuilder * * e.g. `string` corresponds to `AlgebraicType.String` */ - readonly algebraicType: SpacetimeType | AlgebraicTypeVariants.Ref; + readonly algebraicType: SpacetimeType; - constructor(algebraicType: SpacetimeType | AlgebraicTypeVariants.Ref) { + constructor(algebraicType: SpacetimeType) { this.algebraicType = algebraicType; } - resolveType(): SpacetimeType { - let ty: AlgebraicType = this.algebraicType; - while (ty.tag === 'Ref') ty = MODULE_DEF.typespace.types[ty.value]; - return ty as SpacetimeType; - } - optional(): OptionBuilder { return new OptionBuilder(this); } + + serialize(writer: BinaryWriter, value: Type): void { + AlgebraicType.serializeValue(writer, this.algebraicType, value); + } + + deserialize(reader: BinaryReader): Type { + return AlgebraicType.deserializeValue(reader, this.algebraicType); + } } /** @@ -198,7 +199,7 @@ interface PrimaryKeyable< primaryKey(): ColumnBuilder< Type, SpacetimeType, - Set + SetField >; } @@ -227,7 +228,7 @@ interface Uniqueable< /** * Specify this column as unique */ - unique(): ColumnBuilder>; + unique(): ColumnBuilder>; } /** @@ -255,10 +256,14 @@ interface Indexable< * Specify the index type for this column * @param algorithm The index algorithm to use */ - index(): ColumnBuilder>; + index(): ColumnBuilder< + Type, + SpacetimeType, + SetField + >; index>( algorithm: N - ): ColumnBuilder>; + ): ColumnBuilder>; } /** @@ -289,7 +294,7 @@ interface AutoIncrementable< autoInc(): ColumnBuilder< Type, SpacetimeType, - Set + SetField >; } @@ -343,43 +348,46 @@ interface Defaultable< */ default( value: Type - ): ColumnBuilder>; + ): ColumnBuilder>; } export class U8Builder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { constructor() { super(AlgebraicType.U8); } - index(): U8ColumnBuilder>; + index(): U8ColumnBuilder>; index>( algorithm: N - ): U8ColumnBuilder>; + ): U8ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): U8ColumnBuilder> { + ): U8ColumnBuilder> { return new U8ColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): U8ColumnBuilder> { + unique(): U8ColumnBuilder> { return new U8ColumnBuilder(this, set(defaultMetadata, { isUnique: true })); } - primaryKey(): U8ColumnBuilder> { + primaryKey(): U8ColumnBuilder< + SetField + > { return new U8ColumnBuilder( this, set(defaultMetadata, { isPrimaryKey: true }) ); } - autoInc(): U8ColumnBuilder> { + autoInc(): U8ColumnBuilder< + SetField + > { return new U8ColumnBuilder( this, set(defaultMetadata, { isAutoIncrement: true }) @@ -387,7 +395,7 @@ export class U8Builder } default( value: number - ): U8ColumnBuilder> { + ): U8ColumnBuilder> { return new U8ColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -398,37 +406,40 @@ export class U8Builder export class U16Builder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { constructor() { super(AlgebraicType.U16); } - index(): U16ColumnBuilder>; + index(): U16ColumnBuilder>; index>( algorithm: N - ): U16ColumnBuilder>; + ): U16ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): U16ColumnBuilder> { + ): U16ColumnBuilder> { return new U16ColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): U16ColumnBuilder> { + unique(): U16ColumnBuilder> { return new U16ColumnBuilder(this, set(defaultMetadata, { isUnique: true })); } - primaryKey(): U16ColumnBuilder> { + primaryKey(): U16ColumnBuilder< + SetField + > { return new U16ColumnBuilder( this, set(defaultMetadata, { isPrimaryKey: true }) ); } - autoInc(): U16ColumnBuilder> { + autoInc(): U16ColumnBuilder< + SetField + > { return new U16ColumnBuilder( this, set(defaultMetadata, { isAutoIncrement: true }) @@ -436,7 +447,7 @@ export class U16Builder } default( value: number - ): U16ColumnBuilder> { + ): U16ColumnBuilder> { return new U16ColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -447,37 +458,40 @@ export class U16Builder export class U32Builder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { constructor() { super(AlgebraicType.U32); } - index(): U32ColumnBuilder>; + index(): U32ColumnBuilder>; index>( algorithm: N - ): U32ColumnBuilder>; + ): U32ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): U32ColumnBuilder> { + ): U32ColumnBuilder> { return new U32ColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): U32ColumnBuilder> { + unique(): U32ColumnBuilder> { return new U32ColumnBuilder(this, set(defaultMetadata, { isUnique: true })); } - primaryKey(): U32ColumnBuilder> { + primaryKey(): U32ColumnBuilder< + SetField + > { return new U32ColumnBuilder( this, set(defaultMetadata, { isPrimaryKey: true }) ); } - autoInc(): U32ColumnBuilder> { + autoInc(): U32ColumnBuilder< + SetField + > { return new U32ColumnBuilder( this, set(defaultMetadata, { isAutoIncrement: true }) @@ -485,7 +499,7 @@ export class U32Builder } default( value: number - ): U32ColumnBuilder> { + ): U32ColumnBuilder> { return new U32ColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -496,37 +510,40 @@ export class U32Builder export class U64Builder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { constructor() { super(AlgebraicType.U64); } - index(): U64ColumnBuilder>; + index(): U64ColumnBuilder>; index>( algorithm: N - ): U64ColumnBuilder>; + ): U64ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): U64ColumnBuilder> { + ): U64ColumnBuilder> { return new U64ColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): U64ColumnBuilder> { + unique(): U64ColumnBuilder> { return new U64ColumnBuilder(this, set(defaultMetadata, { isUnique: true })); } - primaryKey(): U64ColumnBuilder> { + primaryKey(): U64ColumnBuilder< + SetField + > { return new U64ColumnBuilder( this, set(defaultMetadata, { isPrimaryKey: true }) ); } - autoInc(): U64ColumnBuilder> { + autoInc(): U64ColumnBuilder< + SetField + > { return new U64ColumnBuilder( this, set(defaultMetadata, { isAutoIncrement: true }) @@ -534,7 +551,7 @@ export class U64Builder } default( value: bigint - ): U64ColumnBuilder> { + ): U64ColumnBuilder> { return new U64ColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -545,40 +562,43 @@ export class U64Builder export class U128Builder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { constructor() { super(AlgebraicType.U128); } - index(): U128ColumnBuilder>; + index(): U128ColumnBuilder>; index>( algorithm: N - ): U128ColumnBuilder>; + ): U128ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): U128ColumnBuilder> { + ): U128ColumnBuilder> { return new U128ColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): U128ColumnBuilder> { + unique(): U128ColumnBuilder> { return new U128ColumnBuilder( this, set(defaultMetadata, { isUnique: true }) ); } - primaryKey(): U128ColumnBuilder> { + primaryKey(): U128ColumnBuilder< + SetField + > { return new U128ColumnBuilder( this, set(defaultMetadata, { isPrimaryKey: true }) ); } - autoInc(): U128ColumnBuilder> { + autoInc(): U128ColumnBuilder< + SetField + > { return new U128ColumnBuilder( this, set(defaultMetadata, { isAutoIncrement: true }) @@ -586,7 +606,7 @@ export class U128Builder } default( value: bigint - ): U128ColumnBuilder> { + ): U128ColumnBuilder> { return new U128ColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -597,40 +617,43 @@ export class U128Builder export class U256Builder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { constructor() { super(AlgebraicType.U256); } - index(): U256ColumnBuilder>; + index(): U256ColumnBuilder>; index>( algorithm: N - ): U256ColumnBuilder>; + ): U256ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): U256ColumnBuilder> { + ): U256ColumnBuilder> { return new U256ColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): U256ColumnBuilder> { + unique(): U256ColumnBuilder> { return new U256ColumnBuilder( this, set(defaultMetadata, { isUnique: true }) ); } - primaryKey(): U256ColumnBuilder> { + primaryKey(): U256ColumnBuilder< + SetField + > { return new U256ColumnBuilder( this, set(defaultMetadata, { isPrimaryKey: true }) ); } - autoInc(): U256ColumnBuilder> { + autoInc(): U256ColumnBuilder< + SetField + > { return new U256ColumnBuilder( this, set(defaultMetadata, { isAutoIncrement: true }) @@ -638,7 +661,7 @@ export class U256Builder } default( value: bigint - ): U256ColumnBuilder> { + ): U256ColumnBuilder> { return new U256ColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -649,37 +672,40 @@ export class U256Builder export class I8Builder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { constructor() { super(AlgebraicType.I8); } - index(): I8ColumnBuilder>; + index(): I8ColumnBuilder>; index>( algorithm: N - ): I8ColumnBuilder>; + ): I8ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): I8ColumnBuilder> { + ): I8ColumnBuilder> { return new I8ColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): I8ColumnBuilder> { + unique(): I8ColumnBuilder> { return new I8ColumnBuilder(this, set(defaultMetadata, { isUnique: true })); } - primaryKey(): I8ColumnBuilder> { + primaryKey(): I8ColumnBuilder< + SetField + > { return new I8ColumnBuilder( this, set(defaultMetadata, { isPrimaryKey: true }) ); } - autoInc(): I8ColumnBuilder> { + autoInc(): I8ColumnBuilder< + SetField + > { return new I8ColumnBuilder( this, set(defaultMetadata, { isAutoIncrement: true }) @@ -687,7 +713,7 @@ export class I8Builder } default( value: number - ): I8ColumnBuilder> { + ): I8ColumnBuilder> { return new I8ColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -698,37 +724,40 @@ export class I8Builder export class I16Builder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { constructor() { super(AlgebraicType.I16); } - index(): I16ColumnBuilder>; + index(): I16ColumnBuilder>; index>( algorithm: N - ): I16ColumnBuilder>; + ): I16ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): I16ColumnBuilder> { + ): I16ColumnBuilder> { return new I16ColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): I16ColumnBuilder> { + unique(): I16ColumnBuilder> { return new I16ColumnBuilder(this, set(defaultMetadata, { isUnique: true })); } - primaryKey(): I16ColumnBuilder> { + primaryKey(): I16ColumnBuilder< + SetField + > { return new I16ColumnBuilder( this, set(defaultMetadata, { isPrimaryKey: true }) ); } - autoInc(): I16ColumnBuilder> { + autoInc(): I16ColumnBuilder< + SetField + > { return new I16ColumnBuilder( this, set(defaultMetadata, { isAutoIncrement: true }) @@ -736,7 +765,7 @@ export class I16Builder } default( value: number - ): I16ColumnBuilder> { + ): I16ColumnBuilder> { return new I16ColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -747,38 +776,41 @@ export class I16Builder export class I32Builder extends TypeBuilder implements - TypeBuilder, - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ + TypeBuilder, + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { constructor() { super(AlgebraicType.I32); } - index(): I32ColumnBuilder>; + index(): I32ColumnBuilder>; index>( algorithm: N - ): I32ColumnBuilder>; + ): I32ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): I32ColumnBuilder> { + ): I32ColumnBuilder> { return new I32ColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): I32ColumnBuilder> { + unique(): I32ColumnBuilder> { return new I32ColumnBuilder(this, set(defaultMetadata, { isUnique: true })); } - primaryKey(): I32ColumnBuilder> { + primaryKey(): I32ColumnBuilder< + SetField + > { return new I32ColumnBuilder( this, set(defaultMetadata, { isPrimaryKey: true }) ); } - autoInc(): I32ColumnBuilder> { + autoInc(): I32ColumnBuilder< + SetField + > { return new I32ColumnBuilder( this, set(defaultMetadata, { isAutoIncrement: true }) @@ -786,7 +818,7 @@ export class I32Builder } default( value: number - ): I32ColumnBuilder> { + ): I32ColumnBuilder> { return new I32ColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -797,37 +829,40 @@ export class I32Builder export class I64Builder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { constructor() { super(AlgebraicType.I64); } - index(): I64ColumnBuilder>; + index(): I64ColumnBuilder>; index>( algorithm: N - ): I64ColumnBuilder>; + ): I64ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): I64ColumnBuilder> { + ): I64ColumnBuilder> { return new I64ColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): I64ColumnBuilder> { + unique(): I64ColumnBuilder> { return new I64ColumnBuilder(this, set(defaultMetadata, { isUnique: true })); } - primaryKey(): I64ColumnBuilder> { + primaryKey(): I64ColumnBuilder< + SetField + > { return new I64ColumnBuilder( this, set(defaultMetadata, { isPrimaryKey: true }) ); } - autoInc(): I64ColumnBuilder> { + autoInc(): I64ColumnBuilder< + SetField + > { return new I64ColumnBuilder( this, set(defaultMetadata, { isAutoIncrement: true }) @@ -835,7 +870,7 @@ export class I64Builder } default( value: bigint - ): I64ColumnBuilder> { + ): I64ColumnBuilder> { return new I64ColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -846,40 +881,43 @@ export class I64Builder export class I128Builder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { constructor() { super(AlgebraicType.I128); } - index(): I128ColumnBuilder>; + index(): I128ColumnBuilder>; index>( algorithm: N - ): I128ColumnBuilder>; + ): I128ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): I128ColumnBuilder> { + ): I128ColumnBuilder> { return new I128ColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): I128ColumnBuilder> { + unique(): I128ColumnBuilder> { return new I128ColumnBuilder( this, set(defaultMetadata, { isUnique: true }) ); } - primaryKey(): I128ColumnBuilder> { + primaryKey(): I128ColumnBuilder< + SetField + > { return new I128ColumnBuilder( this, set(defaultMetadata, { isPrimaryKey: true }) ); } - autoInc(): I128ColumnBuilder> { + autoInc(): I128ColumnBuilder< + SetField + > { return new I128ColumnBuilder( this, set(defaultMetadata, { isAutoIncrement: true }) @@ -887,7 +925,7 @@ export class I128Builder } default( value: bigint - ): I128ColumnBuilder> { + ): I128ColumnBuilder> { return new I128ColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -898,40 +936,43 @@ export class I128Builder export class I256Builder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { constructor() { super(AlgebraicType.I256); } - index(): I256ColumnBuilder>; + index(): I256ColumnBuilder>; index>( algorithm: N - ): I256ColumnBuilder>; + ): I256ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): I256ColumnBuilder> { + ): I256ColumnBuilder> { return new I256ColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): I256ColumnBuilder> { + unique(): I256ColumnBuilder> { return new I256ColumnBuilder( this, set(defaultMetadata, { isUnique: true }) ); } - primaryKey(): I256ColumnBuilder> { + primaryKey(): I256ColumnBuilder< + SetField + > { return new I256ColumnBuilder( this, set(defaultMetadata, { isPrimaryKey: true }) ); } - autoInc(): I256ColumnBuilder> { + autoInc(): I256ColumnBuilder< + SetField + > { return new I256ColumnBuilder( this, set(defaultMetadata, { isAutoIncrement: true }) @@ -939,7 +980,7 @@ export class I256Builder } default( value: bigint - ): I256ColumnBuilder> { + ): I256ColumnBuilder> { return new I256ColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -949,14 +990,13 @@ export class I256Builder export class F32Builder extends TypeBuilder - implements Defaultable -{ + implements Defaultable { constructor() { super(AlgebraicType.F32); } default( value: number - ): F32ColumnBuilder> { + ): F32ColumnBuilder> { return new F32ColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -966,14 +1006,13 @@ export class F32Builder export class F64Builder extends TypeBuilder - implements Defaultable -{ + implements Defaultable { constructor() { super(AlgebraicType.F64); } default( value: number - ): F64ColumnBuilder> { + ): F64ColumnBuilder> { return new F64ColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -984,33 +1023,34 @@ export class F64Builder export class BoolBuilder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + Defaultable { constructor() { super(AlgebraicType.Bool); } - index(): BoolColumnBuilder>; + index(): BoolColumnBuilder>; index>( algorithm: N - ): BoolColumnBuilder>; + ): BoolColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): BoolColumnBuilder> { + ): BoolColumnBuilder> { return new BoolColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): BoolColumnBuilder> { + unique(): BoolColumnBuilder> { return new BoolColumnBuilder( this, set(defaultMetadata, { isUnique: true }) ); } - primaryKey(): BoolColumnBuilder> { + primaryKey(): BoolColumnBuilder< + SetField + > { return new BoolColumnBuilder( this, set(defaultMetadata, { isPrimaryKey: true }) @@ -1018,7 +1058,7 @@ export class BoolBuilder } default( value: boolean - ): BoolColumnBuilder> { + ): BoolColumnBuilder> { return new BoolColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -1029,34 +1069,33 @@ export class BoolBuilder export class StringBuilder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + Defaultable { constructor() { super(AlgebraicType.String); } - index(): StringColumnBuilder>; + index(): StringColumnBuilder>; index>( algorithm: N - ): StringColumnBuilder>; + ): StringColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): StringColumnBuilder> { + ): StringColumnBuilder> { return new StringColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): StringColumnBuilder> { + unique(): StringColumnBuilder> { return new StringColumnBuilder( this, set(defaultMetadata, { isUnique: true }) ); } primaryKey(): StringColumnBuilder< - Set + SetField > { return new StringColumnBuilder( this, @@ -1065,7 +1104,7 @@ export class StringBuilder } default( value: string - ): StringColumnBuilder> { + ): StringColumnBuilder> { return new StringColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -1078,8 +1117,7 @@ export class ArrayBuilder> Array>, { tag: 'Array'; value: InferSpacetimeTypeOfTypeBuilder } > - implements Defaultable>, any> -{ + implements Defaultable>, any> { /** * The phantom element type of the array for TypeScript */ @@ -1090,7 +1128,10 @@ export class ArrayBuilder> } default( value: Array> - ): ArrayColumnBuilder> { + ): ArrayColumnBuilder< + Element, + SetField + > { return new ArrayColumnBuilder( this.element, set(defaultMetadata, { defaultValue: value }) @@ -1098,17 +1139,34 @@ export class ArrayBuilder> } } +export class ByteArrayBuilder + extends TypeBuilder< + Uint8Array, + { tag: 'Array'; value: AlgebraicTypeVariants.U8 } + > + implements Defaultable { + constructor() { + super(AlgebraicType.Array(AlgebraicType.U8)); + } + default( + value: Uint8Array + ): ByteArrayColumnBuilder> { + return new ByteArrayColumnBuilder( + set(defaultMetadata, { defaultValue: value }) + ); + } +} + export class OptionBuilder> extends TypeBuilder< InferTypeOfTypeBuilder | undefined, OptionAlgebraicType> > implements - Defaultable< - InferTypeOfTypeBuilder | undefined, - OptionAlgebraicType> - > -{ + Defaultable< + InferTypeOfTypeBuilder | undefined, + OptionAlgebraicType> + > { /** * The phantom value type of the option for TypeScript */ @@ -1126,8 +1184,8 @@ export class OptionBuilder> default( value: InferTypeOfTypeBuilder | undefined ): OptionColumnBuilder< - InferTypeOfTypeBuilder, - Set< + Value, + SetField< DefaultMetadata, 'defaultValue', InferTypeOfTypeBuilder | undefined @@ -1148,27 +1206,30 @@ export class ProductBuilder value: { elements: ElementsArrayFromElementsObj }; } > - implements Defaultable, any> -{ + implements Defaultable, any> { + readonly typeName: string | undefined; + readonly elements: Elements; constructor(elements: Elements, name?: string) { function elementsArrayFromElementsObj(obj: Obj) { - return Object.entries(obj).map(([name, { algebraicType }]) => ({ + return Object.entries(obj).map(([name, value]) => ({ name, - algebraicType, + algebraicType: value.algebraicType, })); } super( - addType( - name, - AlgebraicType.Product({ - elements: elementsArrayFromElementsObj(elements), - }) - ) + AlgebraicType.Product({ + elements: elementsArrayFromElementsObj(elements), + }) ); + this.typeName = name; + this.elements = elements; } default( value: ObjectType - ): ProductColumnBuilder> { + ): ProductColumnBuilder< + Elements, + SetField + > { return new ProductColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -1183,12 +1244,12 @@ export class RowBuilder extends TypeBuilder< value: { elements: ElementsArrayFromRowObj }; } > { - row: CoerceRow; - nameProvided: boolean; + readonly row: CoerceRow; + readonly typeName: string | undefined; constructor(row: Row, name?: string) { const mappedRow = Object.fromEntries( - Object.entries(row).map(([name, builder]) => [ - name, + Object.entries(row).map(([colName, builder]) => [ + colName, builder instanceof ColumnBuilder ? builder : new ColumnBuilder(builder, {}), @@ -1198,40 +1259,120 @@ export class RowBuilder extends TypeBuilder< const elements = Object.entries(mappedRow).map(([name, builder]) => ({ name, algebraicType: builder.typeBuilder.algebraicType, - })) as ElementsArrayFromRowObj; - - super(addType(name, AlgebraicType.Product({ elements }))); - this.nameProvided = name != null; + })); + super(AlgebraicType.Product({ elements })); this.row = mappedRow; + this.typeName = name; } } -export class SumBuilder extends TypeBuilder< +// Value type produced for a given variant key + builder +type EnumValue> = + IsUnit extends true + ? { tag: K } + : { tag: K; value: InferTypeOfTypeBuilder }; + +type VariantConstructor< + K extends string, + V extends TypeBuilder +> = IsUnit extends true + ? EnumValue + : (value: InferTypeOfTypeBuilder) => EnumValue; + +type SumBuilderVariantConstructors = { + [K in keyof Variants & string]: VariantConstructor; +}; + +export type SumBuilder = SumBuilderImpl & + SumBuilderVariantConstructors; + +class SumBuilderImpl extends TypeBuilder< EnumType, { tag: 'Sum'; value: { variants: VariantsArrayFromVariantsObj } } > { + readonly variants: Variants; + readonly typeName: string | undefined; + constructor(variants: Variants, name?: string) { function variantsArrayFromVariantsObj( variants: Variants ) { - return Object.entries(variants).map(([name, { algebraicType }]) => ({ + return Object.entries(variants).map(([name, value]) => ({ name, - algebraicType, + algebraicType: value.algebraicType, })); } + super( - addType( - name, - AlgebraicType.Sum({ - variants: variantsArrayFromVariantsObj(variants), - }) - ) + AlgebraicType.Sum({ + variants: variantsArrayFromVariantsObj(variants), + }) ); + + this.variants = variants; + this.typeName = name; + + // ---- Runtime unit detection ---- + // Adjust this to your real shape if needed. + // From your code, you have `value.algebraicType` available. + function isUnitRuntime(v: any): boolean { + // common patterns — tweak as necessary: + if (!v || !v.algebraicType) return false; + const t = v.algebraicType; + return t.tag === 'Unit' || t.kind === 'Unit' || t.type === 'Unit'; + } + + // wire dynamic per-variant methods + // e.g. mySumBuilder.Foo(value) + for (const key of Object.keys(variants) as Array) { + const variant = variants[key]; + + if (isUnitRuntime(variant)) { + // Unit: expose a read-only VALUE (no call) + const constant = this.create(key as any) as EnumValue; + Object.defineProperty(this, key, { + value: constant, + writable: false, + enumerable: true, + configurable: false, + }); + } else { + // Payload: expose a function(value) -> EnumValue + const fn = ((value: any) => this.create(key as any, value)) as VariantConstructor< + typeof key & string, + Variants[typeof key] + >; + Object.defineProperty(this, key, { + value: fn, + writable: false, + enumerable: true, + configurable: false, + }); + } + } + } + + /** + * Create a value of this sum type. + * - Unit variants: create('bar') + * - Payload variants: create('foo', value) + */ + private create(tag: K): EnumValue; + private create( + tag: K, + value: InferTypeOfTypeBuilder + ): EnumValue; + private create(tag: string, value?: unknown) { + return (value === undefined ? { tag } : { tag, value }); } + default( value: EnumType - ): SumColumnBuilder> { + ): SumColumnBuilder< + Variants, + SetField + > { return new SumColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -1239,36 +1380,45 @@ export class SumBuilder extends TypeBuilder< } } -export class SimpleSumBuilder - extends SumBuilder +export const SumBuilder: { + new ( + variants: Variants, + name?: string + ): SumBuilderImpl & SumBuilderVariantConstructors; +} = SumBuilderImpl as any; + +class SimpleSumBuilderImpl + extends SumBuilderImpl implements - Indexable< - EnumType, - { - tag: 'Sum'; - value: { variants: VariantsArrayFromVariantsObj }; - } - >, - PrimaryKeyable< - EnumType, - { - tag: 'Sum'; - value: { variants: VariantsArrayFromVariantsObj }; - } - > -{ + Indexable< + EnumType, + { + tag: 'Sum'; + value: { variants: VariantsArrayFromVariantsObj }; + } + >, + PrimaryKeyable< + EnumType, + { + tag: 'Sum'; + value: { variants: VariantsArrayFromVariantsObj }; + } + > { index(): SimpleSumColumnBuilder< Variants, - Set + SetField >; index>( algorithm: N - ): SimpleSumColumnBuilder>; + ): SimpleSumColumnBuilder< + Variants, + SetField + >; index( algorithm: IndexTypes = 'btree' ): SimpleSumColumnBuilder< Variants, - Set + SetField > { return new SimpleSumColumnBuilder( this, @@ -1277,7 +1427,7 @@ export class SimpleSumBuilder } primaryKey(): SimpleSumColumnBuilder< Variants, - Set + SetField > { return new SimpleSumColumnBuilder( this, @@ -1286,37 +1436,48 @@ export class SimpleSumBuilder } } +export const SimpleSumBuilder: { + new ( + variants: Variants, + name?: string + ): SimpleSumBuilderImpl & SumBuilderVariantConstructors; +} = SimpleSumBuilderImpl as any; + +export type SimpleSumBuilder = + SimpleSumBuilderImpl & SumBuilderVariantConstructors; + export class IdentityBuilder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + Defaultable { constructor() { super(Identity.getAlgebraicType()); } - index(): IdentityColumnBuilder>; + index(): IdentityColumnBuilder< + SetField + >; index>( algorithm: N - ): IdentityColumnBuilder>; + ): IdentityColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): IdentityColumnBuilder> { + ): IdentityColumnBuilder> { return new IdentityColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): IdentityColumnBuilder> { + unique(): IdentityColumnBuilder> { return new IdentityColumnBuilder( this, set(defaultMetadata, { isUnique: true }) ); } primaryKey(): IdentityColumnBuilder< - Set + SetField > { return new IdentityColumnBuilder( this, @@ -1324,7 +1485,7 @@ export class IdentityBuilder ); } autoInc(): IdentityColumnBuilder< - Set + SetField > { return new IdentityColumnBuilder( this, @@ -1333,7 +1494,9 @@ export class IdentityBuilder } default( value: Identity - ): IdentityColumnBuilder> { + ): IdentityColumnBuilder< + SetField + > { return new IdentityColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -1344,36 +1507,39 @@ export class IdentityBuilder export class ConnectionIdBuilder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + Defaultable { constructor() { super(ConnectionId.getAlgebraicType()); } index(): ConnectionIdColumnBuilder< - Set + SetField >; index>( algorithm: N - ): ConnectionIdColumnBuilder>; + ): ConnectionIdColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): ConnectionIdColumnBuilder> { + ): ConnectionIdColumnBuilder< + SetField + > { return new ConnectionIdColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): ConnectionIdColumnBuilder> { + unique(): ConnectionIdColumnBuilder< + SetField + > { return new ConnectionIdColumnBuilder( this, set(defaultMetadata, { isUnique: true }) ); } primaryKey(): ConnectionIdColumnBuilder< - Set + SetField > { return new ConnectionIdColumnBuilder( this, @@ -1381,7 +1547,7 @@ export class ConnectionIdBuilder ); } autoInc(): ConnectionIdColumnBuilder< - Set + SetField > { return new ConnectionIdColumnBuilder( this, @@ -1391,7 +1557,7 @@ export class ConnectionIdBuilder default( value: ConnectionId ): ConnectionIdColumnBuilder< - Set + SetField > { return new ConnectionIdColumnBuilder( this, @@ -1403,34 +1569,39 @@ export class ConnectionIdBuilder export class TimestampBuilder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + Defaultable { constructor() { super(Timestamp.getAlgebraicType()); } - index(): TimestampColumnBuilder>; + index(): TimestampColumnBuilder< + SetField + >; index>( algorithm: N - ): TimestampColumnBuilder>; + ): TimestampColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): TimestampColumnBuilder> { + ): TimestampColumnBuilder< + SetField + > { return new TimestampColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): TimestampColumnBuilder> { + unique(): TimestampColumnBuilder< + SetField + > { return new TimestampColumnBuilder( this, set(defaultMetadata, { isUnique: true }) ); } primaryKey(): TimestampColumnBuilder< - Set + SetField > { return new TimestampColumnBuilder( this, @@ -1438,7 +1609,7 @@ export class TimestampBuilder ); } autoInc(): TimestampColumnBuilder< - Set + SetField > { return new TimestampColumnBuilder( this, @@ -1447,7 +1618,9 @@ export class TimestampBuilder } default( value: Timestamp - ): TimestampColumnBuilder> { + ): TimestampColumnBuilder< + SetField + > { return new TimestampColumnBuilder( this, set(defaultMetadata, { defaultValue: value }) @@ -1458,36 +1631,39 @@ export class TimestampBuilder export class TimeDurationBuilder extends TypeBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - Defaultable -{ + Indexable, + Uniqueable, + PrimaryKeyable, + Defaultable { constructor() { super(TimeDuration.getAlgebraicType()); } index(): TimeDurationColumnBuilder< - Set + SetField >; index>( algorithm: N - ): TimeDurationColumnBuilder>; + ): TimeDurationColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): TimeDurationColumnBuilder> { + ): TimeDurationColumnBuilder< + SetField + > { return new TimeDurationColumnBuilder( this, set(defaultMetadata, { indexType: algorithm }) ); } - unique(): TimeDurationColumnBuilder> { + unique(): TimeDurationColumnBuilder< + SetField + > { return new TimeDurationColumnBuilder( this, set(defaultMetadata, { isUnique: true }) ); } primaryKey(): TimeDurationColumnBuilder< - Set + SetField > { return new TimeDurationColumnBuilder( this, @@ -1495,7 +1671,7 @@ export class TimeDurationBuilder ); } autoInc(): TimeDurationColumnBuilder< - Set + SetField > { return new TimeDurationColumnBuilder( this, @@ -1505,7 +1681,7 @@ export class TimeDurationBuilder default( value: TimeDuration ): TimeDurationColumnBuilder< - Set + SetField > { return new TimeDurationColumnBuilder( this, @@ -1548,6 +1724,11 @@ const defaultMetadata: ColumnMetadata = {}; * * It carries both a phantom TypeScript type (the `Type`) and * runtime algebraic type information. + * + * IMPORTANT! We have deliberately chosen to not have {@link ColumnBuilder} + * extend {@link TypeBuilder} so that you cannot pass a {@link ColumnBuilder} + * where a {@link TypeBuilder} is expected. i.e. We want to maintain + * contravariance for functions that accept {@link TypeBuilder} parameters. */ export class ColumnBuilder< Type, @@ -1561,768 +1742,837 @@ export class ColumnBuilder< this.typeBuilder = typeBuilder; this.columnMetadata = metadata; } + + serialize(writer: BinaryWriter, value: Type): void { + AlgebraicType.serializeValue(writer, this.typeBuilder.algebraicType, value); + } + + deserialize(reader: BinaryReader): Type { + return AlgebraicType.deserializeValue(reader, this.typeBuilder.algebraicType); + } } export class U8ColumnBuilder = DefaultMetadata> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ - index(): U8ColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { + index(): U8ColumnBuilder>; index>( algorithm: N - ): U8ColumnBuilder>; + ): U8ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): U8ColumnBuilder> { + ): U8ColumnBuilder> { return new U8ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): U8ColumnBuilder> { + unique(): U8ColumnBuilder> { return new U8ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): U8ColumnBuilder> { + primaryKey(): U8ColumnBuilder> { return new U8ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) ); } - autoInc(): U8ColumnBuilder> { + autoInc(): U8ColumnBuilder> { return new U8ColumnBuilder( this.typeBuilder, - set(this.columnMetadata, { isAutoIncrement: true }) + set(this.columnMetadata, { isAutoIncrement: true as const }) ); } - default(value: number): U8ColumnBuilder> { - return new U8ColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + default(value: number): U8ColumnBuilder> { + return new U8ColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class U16ColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ - index(): U16ColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { + index(): U16ColumnBuilder>; index>( algorithm: N - ): U16ColumnBuilder>; + ): U16ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): U16ColumnBuilder> { + ): U16ColumnBuilder> { return new U16ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): U16ColumnBuilder> { + unique(): U16ColumnBuilder> { return new U16ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): U16ColumnBuilder> { + primaryKey(): U16ColumnBuilder> { return new U16ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) ); } - autoInc(): U16ColumnBuilder> { + autoInc(): U16ColumnBuilder> { return new U16ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isAutoIncrement: true }) ); } - default(value: number): U16ColumnBuilder> { - return new U16ColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + default( + value: number + ): U16ColumnBuilder> { + return new U16ColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class U32ColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ - index(): U32ColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { + index(): U32ColumnBuilder>; index>( algorithm: N - ): U32ColumnBuilder>; + ): U32ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): U32ColumnBuilder> { + ): U32ColumnBuilder> { return new U32ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): U32ColumnBuilder> { + unique(): U32ColumnBuilder> { return new U32ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): U32ColumnBuilder> { + primaryKey(): U32ColumnBuilder> { return new U32ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) ); } - autoInc(): U32ColumnBuilder> { + autoInc(): U32ColumnBuilder> { return new U32ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isAutoIncrement: true }) ); } - default(value: number): U32ColumnBuilder> { - return new U32ColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + default( + value: number + ): U32ColumnBuilder> { + return new U32ColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class U64ColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ - index(): U64ColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { + index(): U64ColumnBuilder>; index>( algorithm: N - ): U64ColumnBuilder>; + ): U64ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): U64ColumnBuilder> { + ): U64ColumnBuilder> { return new U64ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): U64ColumnBuilder> { + unique(): U64ColumnBuilder> { return new U64ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): U64ColumnBuilder> { + primaryKey(): U64ColumnBuilder> { return new U64ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) ); } - autoInc(): U64ColumnBuilder> { + autoInc(): U64ColumnBuilder> { return new U64ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isAutoIncrement: true }) ); } - default(value: bigint): U64ColumnBuilder> { - return new U64ColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + default( + value: bigint + ): U64ColumnBuilder> { + return new U64ColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class U128ColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ - index(): U128ColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { + index(): U128ColumnBuilder>; index>( algorithm: N - ): U128ColumnBuilder>; + ): U128ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): U128ColumnBuilder> { + ): U128ColumnBuilder> { return new U128ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): U128ColumnBuilder> { + unique(): U128ColumnBuilder> { return new U128ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): U128ColumnBuilder> { + primaryKey(): U128ColumnBuilder> { return new U128ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) ); } - autoInc(): U128ColumnBuilder> { + autoInc(): U128ColumnBuilder> { return new U128ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isAutoIncrement: true }) ); } - default(value: bigint): U128ColumnBuilder> { - return new U128ColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + default( + value: bigint + ): U128ColumnBuilder> { + return new U128ColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class U256ColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ - index(): U256ColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { + index(): U256ColumnBuilder>; index>( algorithm: N - ): U256ColumnBuilder>; + ): U256ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): U256ColumnBuilder> { + ): U256ColumnBuilder> { return new U256ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): U256ColumnBuilder> { + unique(): U256ColumnBuilder> { return new U256ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): U256ColumnBuilder> { + primaryKey(): U256ColumnBuilder> { return new U256ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) ); } - autoInc(): U256ColumnBuilder> { + autoInc(): U256ColumnBuilder> { return new U256ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isAutoIncrement: true }) ); } - default(value: bigint): U256ColumnBuilder> { - return new U256ColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + default( + value: bigint + ): U256ColumnBuilder> { + return new U256ColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class I8ColumnBuilder = DefaultMetadata> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ - index(): I8ColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { + index(): I8ColumnBuilder>; index>( algorithm: N - ): I8ColumnBuilder>; + ): I8ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): I8ColumnBuilder> { + ): I8ColumnBuilder> { return new I8ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): I8ColumnBuilder> { + unique(): I8ColumnBuilder> { return new I8ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): I8ColumnBuilder> { + primaryKey(): I8ColumnBuilder> { return new I8ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) ); } - autoInc(): I8ColumnBuilder> { + autoInc(): I8ColumnBuilder> { return new I8ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isAutoIncrement: true }) ); } - default(value: number): I8ColumnBuilder> { - return new I8ColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + default(value: number): I8ColumnBuilder> { + return new I8ColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class I16ColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ - index(): I16ColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { + index(): I16ColumnBuilder>; index>( algorithm: N - ): I16ColumnBuilder>; + ): I16ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): I16ColumnBuilder> { + ): I16ColumnBuilder> { return new I16ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): I16ColumnBuilder> { + unique(): I16ColumnBuilder> { return new I16ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): I16ColumnBuilder> { + primaryKey(): I16ColumnBuilder> { return new I16ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) ); } - autoInc(): I16ColumnBuilder> { + autoInc(): I16ColumnBuilder> { return new I16ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isAutoIncrement: true }) ); } - default(value: number): I16ColumnBuilder> { - return new I16ColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + default( + value: number + ): I16ColumnBuilder> { + return new I16ColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class I32ColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ - index(): I32ColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { + index(): I32ColumnBuilder>; index>( algorithm: N - ): I32ColumnBuilder>; + ): I32ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): I32ColumnBuilder> { + ): I32ColumnBuilder> { return new I32ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): I32ColumnBuilder> { + unique(): I32ColumnBuilder> { return new I32ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): I32ColumnBuilder> { + primaryKey(): I32ColumnBuilder> { return new I32ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) ); } - autoInc(): I32ColumnBuilder> { + autoInc(): I32ColumnBuilder> { return new I32ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isAutoIncrement: true }) ); } - default(value: number): I32ColumnBuilder> { - return new I32ColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + default( + value: number + ): I32ColumnBuilder> { + return new I32ColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class I64ColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ - index(): I64ColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { + index(): I64ColumnBuilder>; index>( algorithm: N - ): I64ColumnBuilder>; + ): I64ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): I64ColumnBuilder> { + ): I64ColumnBuilder> { return new I64ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): I64ColumnBuilder> { + unique(): I64ColumnBuilder> { return new I64ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): I64ColumnBuilder> { + primaryKey(): I64ColumnBuilder> { return new I64ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) ); } - autoInc(): I64ColumnBuilder> { + autoInc(): I64ColumnBuilder> { return new I64ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isAutoIncrement: true }) ); } - default(value: bigint): I64ColumnBuilder> { - return new I64ColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + default( + value: bigint + ): I64ColumnBuilder> { + return new I64ColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class I128ColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ - index(): I128ColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { + index(): I128ColumnBuilder>; index>( algorithm: N - ): I128ColumnBuilder>; + ): I128ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): I128ColumnBuilder> { + ): I128ColumnBuilder> { return new I128ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): I128ColumnBuilder> { + unique(): I128ColumnBuilder> { return new I128ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): I128ColumnBuilder> { + primaryKey(): I128ColumnBuilder> { return new I128ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) ); } - autoInc(): I128ColumnBuilder> { + autoInc(): I128ColumnBuilder> { return new I128ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isAutoIncrement: true }) ); } - default(value: bigint): I128ColumnBuilder> { - return new I128ColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + default( + value: bigint + ): I128ColumnBuilder> { + return new I128ColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class I256ColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - AutoIncrementable, - Defaultable -{ - index(): I256ColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + AutoIncrementable, + Defaultable { + index(): I256ColumnBuilder>; index>( algorithm: N - ): I256ColumnBuilder>; + ): I256ColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): I256ColumnBuilder> { + ): I256ColumnBuilder> { return new I256ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): I256ColumnBuilder> { + unique(): I256ColumnBuilder> { return new I256ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): I256ColumnBuilder> { + primaryKey(): I256ColumnBuilder> { return new I256ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) ); } - autoInc(): I256ColumnBuilder> { + autoInc(): I256ColumnBuilder> { return new I256ColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isAutoIncrement: true }) ); } - default(value: bigint): I256ColumnBuilder> { - return new I256ColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + default( + value: bigint + ): I256ColumnBuilder> { + return new I256ColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class F32ColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder - implements Defaultable -{ - default(value: number): F32ColumnBuilder> { - return new F32ColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + implements Defaultable { + default( + value: number + ): F32ColumnBuilder> { + return new F32ColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class F64ColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder - implements Defaultable -{ - default(value: number): F64ColumnBuilder> { - return new F64ColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + implements Defaultable { + default( + value: number + ): F64ColumnBuilder> { + return new F64ColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class BoolColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - Defaultable -{ - index(): BoolColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + Defaultable { + index(): BoolColumnBuilder>; index>( algorithm: N - ): BoolColumnBuilder>; + ): BoolColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): BoolColumnBuilder> { + ): BoolColumnBuilder> { return new BoolColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): BoolColumnBuilder> { + unique(): BoolColumnBuilder> { return new BoolColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): BoolColumnBuilder> { + primaryKey(): BoolColumnBuilder> { return new BoolColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) ); } - default(value: boolean): BoolColumnBuilder> { - return new BoolColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + default( + value: boolean + ): BoolColumnBuilder> { + return new BoolColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class StringColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - Defaultable -{ - index(): StringColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + Defaultable { + index(): StringColumnBuilder>; index>( algorithm: N - ): StringColumnBuilder>; + ): StringColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): StringColumnBuilder> { + ): StringColumnBuilder> { return new StringColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): StringColumnBuilder> { + unique(): StringColumnBuilder> { return new StringColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): StringColumnBuilder> { + primaryKey(): StringColumnBuilder> { return new StringColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) ); } - default(value: string): StringColumnBuilder> { - return new StringColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + default( + value: string + ): StringColumnBuilder> { + return new StringColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class ArrayColumnBuilder< - Element extends TypeBuilder, - M extends ColumnMetadata< - Array> - > = DefaultMetadata, - > + Element extends TypeBuilder, + M extends ColumnMetadata< + Array> + > = DefaultMetadata, +> extends ColumnBuilder< Array>, { tag: 'Array'; value: InferSpacetimeTypeOfTypeBuilder }, M > implements - Defaultable< - Array>, - AlgebraicTypeVariants.Array - > -{ + Defaultable< + Array>, + AlgebraicTypeVariants.Array + > { default( value: Array> ): ArrayColumnBuilder< Element, - Set>> + SetField>> > { - return new ArrayColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + return new ArrayColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); + } +} + +export class ByteArrayColumnBuilder< + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder< + Uint8Array, + { + tag: 'Array'; + value: AlgebraicTypeVariants.U8; + }, + M +> { + constructor(metadata: M) { + super(new TypeBuilder(AlgebraicType.Array(AlgebraicType.U8)), metadata); } } export class OptionColumnBuilder< - Value extends TypeBuilder, - M extends ColumnMetadata< - InferTypeOfTypeBuilder | undefined - > = DefaultMetadata, - > + Value extends TypeBuilder, + M extends ColumnMetadata< + InferTypeOfTypeBuilder | undefined + > = DefaultMetadata, +> extends ColumnBuilder< InferTypeOfTypeBuilder | undefined, OptionAlgebraicType>, M > implements - Defaultable< - InferTypeOfTypeBuilder | undefined, - OptionAlgebraicType> - > -{ + Defaultable< + InferTypeOfTypeBuilder | undefined, + OptionAlgebraicType> + > { default( value: InferTypeOfTypeBuilder | undefined ): OptionColumnBuilder< - InferTypeOfTypeBuilder, - Set | undefined> + Value, + SetField | undefined> > { - return new OptionColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + return new OptionColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { + defaultValue: value, + }) + ); } } export class ProductColumnBuilder< - Elements extends ElementsObj, - M extends ColumnMetadata> = DefaultMetadata, - > + Elements extends ElementsObj, + M extends ColumnMetadata> = DefaultMetadata, +> extends ColumnBuilder< ObjectType, { @@ -2331,11 +2581,13 @@ export class ProductColumnBuilder< }, M > - implements Defaultable, AlgebraicTypeVariants.Product> -{ + implements Defaultable, AlgebraicTypeVariants.Product> { default( value: ObjectType - ): ProductColumnBuilder> { + ): ProductColumnBuilder< + Elements, + SetField + > { return new ProductColumnBuilder( this.typeBuilder, set(this.columnMetadata, { defaultValue: value }) @@ -2344,19 +2596,21 @@ export class ProductColumnBuilder< } export class SumColumnBuilder< - Variants extends VariantsObj, - M extends ColumnMetadata> = DefaultMetadata, - > + Variants extends VariantsObj, + M extends ColumnMetadata> = DefaultMetadata, +> extends ColumnBuilder< EnumType, { tag: 'Sum'; value: { variants: VariantsArrayFromVariantsObj } }, M > - implements Defaultable, AlgebraicTypeVariants.Sum> -{ + implements Defaultable, AlgebraicTypeVariants.Sum> { default( value: EnumType - ): SumColumnBuilder> { + ): SumColumnBuilder< + Variants, + SetField + > { return new SumColumnBuilder( this.typeBuilder, set(this.columnMetadata, { defaultValue: value }) @@ -2365,26 +2619,28 @@ export class SumColumnBuilder< } export class SimpleSumColumnBuilder< - Variants extends VariantsObj, - M extends ColumnMetadata> = DefaultMetadata, - > + Variants extends VariantsObj, + M extends ColumnMetadata> = DefaultMetadata, +> extends SumColumnBuilder implements - Indexable, AlgebraicTypeVariants.Sum>, - PrimaryKeyable, AlgebraicTypeVariants.Sum> -{ + Indexable, AlgebraicTypeVariants.Sum>, + PrimaryKeyable, AlgebraicTypeVariants.Sum> { index(): SimpleSumColumnBuilder< Variants, - Set + SetField >; index>( algorithm: N - ): SimpleSumColumnBuilder>; + ): SimpleSumColumnBuilder< + Variants, + SetField + >; index( algorithm: IndexTypes = 'btree' ): SimpleSumColumnBuilder< Variants, - Set + SetField > { return new SimpleSumColumnBuilder( this.typeBuilder, @@ -2393,7 +2649,7 @@ export class SimpleSumColumnBuilder< } primaryKey(): SimpleSumColumnBuilder< Variants, - Set + SetField > { return new SimpleSumColumnBuilder( this.typeBuilder, @@ -2403,34 +2659,33 @@ export class SimpleSumColumnBuilder< } export class IdentityColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - Defaultable -{ - index(): IdentityColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + Defaultable { + index(): IdentityColumnBuilder>; index>( algorithm: N - ): IdentityColumnBuilder>; + ): IdentityColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): IdentityColumnBuilder> { + ): IdentityColumnBuilder> { return new IdentityColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): IdentityColumnBuilder> { + unique(): IdentityColumnBuilder> { return new IdentityColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): IdentityColumnBuilder> { + primaryKey(): IdentityColumnBuilder> { return new IdentityColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) @@ -2438,43 +2693,42 @@ export class IdentityColumnBuilder< } default( value: Identity - ): IdentityColumnBuilder> { - return new IdentityColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + ): IdentityColumnBuilder> { + return new IdentityColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { defaultValue: value }) + ); } } export class ConnectionIdColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - Defaultable -{ - index(): ConnectionIdColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + Defaultable { + index(): ConnectionIdColumnBuilder>; index>( algorithm: N - ): ConnectionIdColumnBuilder>; + ): ConnectionIdColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): ConnectionIdColumnBuilder> { + ): ConnectionIdColumnBuilder> { return new ConnectionIdColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): ConnectionIdColumnBuilder> { + unique(): ConnectionIdColumnBuilder> { return new ConnectionIdColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): ConnectionIdColumnBuilder> { + primaryKey(): ConnectionIdColumnBuilder> { return new ConnectionIdColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) @@ -2482,43 +2736,42 @@ export class ConnectionIdColumnBuilder< } default( value: ConnectionId - ): ConnectionIdColumnBuilder> { - return new ConnectionIdColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + ): ConnectionIdColumnBuilder> { + return new ConnectionIdColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { defaultValue: value }) + ); } } export class TimestampColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - Defaultable -{ - index(): TimestampColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + Defaultable { + index(): TimestampColumnBuilder>; index>( algorithm: N - ): TimestampColumnBuilder>; + ): TimestampColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): TimestampColumnBuilder> { + ): TimestampColumnBuilder> { return new TimestampColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): TimestampColumnBuilder> { + unique(): TimestampColumnBuilder> { return new TimestampColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): TimestampColumnBuilder> { + primaryKey(): TimestampColumnBuilder> { return new TimestampColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) @@ -2526,43 +2779,42 @@ export class TimestampColumnBuilder< } default( value: Timestamp - ): TimestampColumnBuilder> { - return new TimestampColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + ): TimestampColumnBuilder> { + return new TimestampColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { defaultValue: value }) + ); } } export class TimeDurationColumnBuilder< - M extends ColumnMetadata = DefaultMetadata, - > + M extends ColumnMetadata = DefaultMetadata, +> extends ColumnBuilder implements - Indexable, - Uniqueable, - PrimaryKeyable, - Defaultable -{ - index(): TimeDurationColumnBuilder>; + Indexable, + Uniqueable, + PrimaryKeyable, + Defaultable { + index(): TimeDurationColumnBuilder>; index>( algorithm: N - ): TimeDurationColumnBuilder>; + ): TimeDurationColumnBuilder>; index( algorithm: IndexTypes = 'btree' - ): TimeDurationColumnBuilder> { + ): TimeDurationColumnBuilder> { return new TimeDurationColumnBuilder( this.typeBuilder, set(this.columnMetadata, { indexType: algorithm }) ); } - unique(): TimeDurationColumnBuilder> { + unique(): TimeDurationColumnBuilder> { return new TimeDurationColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isUnique: true }) ); } - primaryKey(): TimeDurationColumnBuilder> { + primaryKey(): TimeDurationColumnBuilder> { return new TimeDurationColumnBuilder( this.typeBuilder, set(this.columnMetadata, { isPrimaryKey: true }) @@ -2570,14 +2822,86 @@ export class TimeDurationColumnBuilder< } default( value: TimeDuration - ): TimeDurationColumnBuilder> { - return new TimeDurationColumnBuilder(this.typeBuilder, { - ...this.columnMetadata, - defaultValue: value, - }); + ): TimeDurationColumnBuilder> { + return new TimeDurationColumnBuilder( + this.typeBuilder, + set(this.columnMetadata, { defaultValue: value }) + ); } } +export class RefBuilder extends TypeBuilder { + readonly ref: number; + constructor(ref: number) { + super(AlgebraicType.Ref(ref)); + this.ref = ref; + } +} + +interface EnumFn { + /** + * Creates a simple sum type whose cases are all unit variants. + * Each string in the array becomes a case of the enum. + * + * Example: + * ```ts + * t.enum("Color", ["red", "green", "blue"]); + * ``` + */ + ( + name: string, + cases: readonly [Case, ...Case[]] + ): SimpleSumBuilderImpl>; + + /** + * Creates an empty simple sum type (no cases, equivalent to `never`). + * This can be useful for code generation or placeholder types. + * Example: + * ```ts + * t.enum("Never", []); + * ``` + */ + (name: string, cases: []): SimpleSumBuilderImpl>; + + /** + * Creates a full sum type, where each case can have a payload. + * Each value in the object must be a {@link TypeBuilder}. + * + * Example: + * ```ts + * t.enum("Result", { Ok: t.unit(), Err: t.string() }); + * ``` + */ + (name: string, obj: Obj): SumBuilder; +} + +const enumImpl = ((nameOrObj: any, maybeObj?: any) => { + let obj: any = nameOrObj; + let name: string | undefined = undefined; + + if (typeof nameOrObj === 'string') { + if (!maybeObj) { + throw new TypeError( + 'When providing a name, you must also provide the variants object or array.' + ); + } + obj = maybeObj; + name = nameOrObj; + } + + // Simple sum (array form) + if (Array.isArray(obj)) { + const simpleVariantsObj: Record = {}; + for (const variant of obj) { + simpleVariantsObj[variant] = new ProductBuilder({}); + } + return new SimpleSumBuilderImpl(simpleVariantsObj, name); + } + + // Regular sum (object form) + return new SumBuilder(obj, name); +}) as EnumFn; + /** * A collection of factory functions for creating various SpacetimeDB algebraic types * to be used in table definitions. Each function returns a corresponding builder @@ -2784,47 +3108,7 @@ export const t = { return new ArrayBuilder(e); }, - /** - * Creates a new `Sum` {@link AlgebraicType} to be used in table definitions. Sum types in SpacetimeDB - * are similar to enums or unions in languages like Rust or TypeScript respectively. - * Each variant of the enum must be a {@link TypeBuilder}. - * Represented as a union of string literals in TypeScript. - * - * @param name (optional) A display name for the sum type. If omitted, an anonymous sum type is created. - * @param obj The object defining the variants of the enum, whose variant - * types must be {@link TypeBuilder}s. - * @returns A new {@link SumBuilder} instance. - */ - enum: ((nameOrObj: any, maybeObj?: any) => { - let obj: VariantsObj = nameOrObj; - let name: string | undefined = undefined; - if (typeof nameOrObj === 'string') { - if (!maybeObj) { - throw new TypeError( - 'When providing a name, you must also provide the variants object.' - ); - } - obj = maybeObj; - name = nameOrObj; - } - if ( - Object.values(obj).every(x => { - const ty: AlgebraicType = x.resolveType(); - return ty.tag === 'Product' && ty.value.elements.length === 0; - }) - ) { - return new SimpleSumBuilder(obj as SimpleVariantsObj, name); - } - return new SumBuilder(obj, name); - }) as { - ( - name: string, - obj: Obj - ): SimpleSumBuilder; - (name: string, obj: Obj): SumBuilder; - // TODO: Currently names are not optional - // (obj: Obj): SumBuilder; - }, + enum: enumImpl, /** * This is a special helper function for conveniently creating {@link Product} type columns with no fields. @@ -2835,6 +3119,46 @@ export const t = { return new ProductBuilder({}); }, + /** + * Creates a lazily-evaluated {@link TypeBuilder}. This is useful for creating + * recursive types, such as a tree or linked list. + * @param thunk A function that returns a {@link TypeBuilder}. + * @returns A proxy {@link TypeBuilder} that evaluates the thunk on first access. + */ + lazy TypeBuilder>( + thunk: Build + ): ReturnType { + type B = ReturnType; + let cached: B | null = null; + const get = (): B => (cached ??= thunk() as B); + + const proxy = new Proxy({} as unknown as B, { + get(_t, prop, recv) { + const target = get() as any; + const val = Reflect.get(target, prop, recv); + return typeof val === 'function' ? val.bind(target) : val; + }, + set(_t, prop, value, recv) { + return Reflect.set(get() as any, prop, value, recv); + }, + has(_t, prop) { + return prop in (get() as any); + }, + ownKeys() { + return Reflect.ownKeys(get() as any); + }, + getOwnPropertyDescriptor(_t, prop) { + return Object.getOwnPropertyDescriptor(get() as any, prop); + }, + getPrototypeOf() { + // makes `instanceof TypeBuilder` work if you care about it + return Object.getPrototypeOf(get() as any); + }, + }) as B; + + return proxy; + }, + /** * This is a special helper function for conveniently creating {@link ScheduleAt} type columns. * @returns A new ColumnBuilder instance with the {@link ScheduleAt} type. @@ -2897,5 +3221,15 @@ export const t = { timeDuration: (): TimeDurationBuilder => { return new TimeDurationBuilder(); }, + + /** + * This is a convenience method for creating a column with the {@link ByteArray} type. + * You can create a column of the same type by constructing an `array` of `u8`. + * The TypeScript representation is {@link Uint8Array}. + * @returns A new {@link ByteArrayBuilder} instance with the {@link ByteArray} type. + */ + byteArray: (): ByteArrayBuilder => { + return new ByteArrayBuilder(); + }, } as const; export default t; diff --git a/crates/bindings-typescript/src/lib/type_util.ts b/crates/bindings-typescript/src/lib/type_util.ts new file mode 100644 index 00000000000..55aa63ec162 --- /dev/null +++ b/crates/bindings-typescript/src/lib/type_util.ts @@ -0,0 +1,62 @@ +import type { ConnectionId } from './connection_id'; +import type { Identity } from './identity'; +import type { ScheduleAt } from './schedule_at'; +import type { TimeDuration } from './time_duration'; +import type { Timestamp } from './timestamp'; + +type DoNotPrettify = + | Identity + | ConnectionId + | Timestamp + | TimeDuration + | ScheduleAt; + +/** + * Utility to make TS show cleaner types by flattening intersections. + */ +export type Prettify = T extends DoNotPrettify + ? T + : { [K in keyof T]: T[K] } & {}; + +/** + * Helper function to sets a field in an object + */ +export type SetField = Prettify< + Omit & { [K in F]: V } +>; + +/** + * Sets a field in an object + * @param x The original object + * @param t The object containing the field to set + * @returns A new object with the field set + */ +export function set( + x: T, + t: { [k in F]: V } +): SetField { + return { ...x, ...t } as SetField; +} + +/** + * Helper to extract the value types from an object type + */ +export type Values = T[keyof T]; + +/** + * A helper type to collapse a tuple into a single type if it has only one element. + */ +export type CollapseTuple = A extends [infer T] ? T : A; + +type CamelCaseImpl = S extends `${infer Head}_${infer Tail}` + ? `${Head}${Capitalize>}` + : S extends `${infer Head}-${infer Tail}` + ? `${Head}${Capitalize>}` + : S; + +/** + * Convert "Some_identifier-name" -> "someIdentifierName" + * - No spaces; allowed separators: "_" and "-" + * - Normalizes the *first* character to lowercase (e.g. "User_Name" -> "userName") + */ +export type CamelCase = Uncapitalize>; diff --git a/crates/bindings-typescript/src/lib/utils.ts b/crates/bindings-typescript/src/lib/util.ts similarity index 64% rename from crates/bindings-typescript/src/lib/utils.ts rename to crates/bindings-typescript/src/lib/util.ts index 0b09319dc53..c13a90b0e53 100644 --- a/crates/bindings-typescript/src/lib/utils.ts +++ b/crates/bindings-typescript/src/lib/util.ts @@ -1,5 +1,6 @@ import BinaryReader from './binary_reader'; import BinaryWriter from './binary_writer'; +import type { CamelCase } from './type_util'; export function toPascalCase(s: string): string { const str = s.replace(/([-_][a-z])/gi, $1 => { @@ -98,3 +99,60 @@ export function u256ToUint8Array(data: bigint): Uint8Array { export function u256ToHexString(data: bigint): string { return uint8ArrayToHexString(u256ToUint8Array(data)); } + +/** + * Type safe conversion from a string like "some_identifier-name" to "someIdentifierName". + * @param str The string to convert + * @returns The converted string + */ +export function toCamelCase(str: T): CamelCase { + return str.replace(/[-_]+(\w)/g, (_, c) => c.toUpperCase()) as CamelCase; +} + +import type { AlgebraicType } from './algebraic_type'; +import type Typespace from './autogen/typespace_type'; +import type { Infer } from './type_builders'; + +export function bsatnBaseSize( + typespace: Infer, + ty: AlgebraicType +): number { + const assumedArrayLength = 4; + while (ty.tag === 'Ref') ty = typespace.types[ty.value]; + if (ty.tag === 'Product') { + let sum = 0; + for (const { algebraicType: elem } of ty.value.elements) { + sum += bsatnBaseSize(typespace, elem); + } + return sum; + } else if (ty.tag === 'Sum') { + let min = Infinity; + for (const { algebraicType: vari } of ty.value.variants) { + const vSize = bsatnBaseSize(typespace, vari); + if (vSize < min) min = vSize; + } + if (min === Infinity) min = 0; + return 4 + min; + } else if (ty.tag == 'Array') { + return 4 + assumedArrayLength * bsatnBaseSize(typespace, ty.value); + } + return { + String: 4 + assumedArrayLength, + Sum: 1, + Bool: 1, + I8: 1, + U8: 1, + I16: 2, + U16: 2, + I32: 4, + U32: 4, + F32: 4, + I64: 8, + U64: 8, + F64: 8, + I128: 16, + U128: 16, + I256: 32, + U256: 32, + }[ty.tag]; +} diff --git a/crates/bindings-typescript/src/server/views.ts b/crates/bindings-typescript/src/lib/views.ts similarity index 100% rename from crates/bindings-typescript/src/server/views.ts rename to crates/bindings-typescript/src/lib/views.ts diff --git a/crates/bindings-typescript/src/react/SpacetimeDBProvider.ts b/crates/bindings-typescript/src/react/SpacetimeDBProvider.ts index 0af29acf067..5c10b2aed8c 100644 --- a/crates/bindings-typescript/src/react/SpacetimeDBProvider.ts +++ b/crates/bindings-typescript/src/react/SpacetimeDBProvider.ts @@ -1,38 +1,99 @@ import { DbConnectionBuilder, type DbConnectionImpl, + type ErrorContextInterface, + type RemoteModuleOf, } from '../sdk/db_connection_impl'; import * as React from 'react'; import { SpacetimeDBContext } from './useSpacetimeDB'; +import type { ConnectionState } from './connection_state'; +import { ConnectionId } from '../lib/connection_id'; export interface SpacetimeDBProviderProps< - DbConnection extends DbConnectionImpl, - ErrorContext, - SubscriptionEventContext, + DbConnection extends DbConnectionImpl, > { - connectionBuilder: DbConnectionBuilder< - DbConnection, - ErrorContext, - SubscriptionEventContext - >; + connectionBuilder: DbConnectionBuilder; children?: React.ReactNode; } export function SpacetimeDBProvider< - DbConnection extends DbConnectionImpl, - ErrorContext, - SubscriptionEventContext, + DbConnection extends DbConnectionImpl, >({ connectionBuilder, children, -}: SpacetimeDBProviderProps< - DbConnection, - ErrorContext, - SubscriptionEventContext ->): React.JSX.Element { +}: SpacetimeDBProviderProps): React.JSX.Element { + // Holds the imperative connection instance when (and only when) we’re on the client. + const connRef = React.useRef(null); + const getConnection = React.useCallback(() => connRef.current, []); + + const [state, setState] = React.useState({ + isActive: false, + identity: undefined, + token: undefined, + connectionId: ConnectionId.random(), + connectionError: undefined, + getConnection: getConnection as ConnectionState['getConnection'], + }); + + // Build on the client only; useEffect won't run during SSR. + React.useEffect(() => { + if (!connRef.current) { + connRef.current = connectionBuilder.build(); + } + console.log('HAPPPP'); + // Register callback for onConnect to update state + const onConnect = (conn: DbConnection) => { + setState(s => ({ + ...s, + isActive: conn.isActive, + identity: conn.identity, + token: conn.token, + connectionId: conn.connectionId, + })); + }; + const onDisconnect = ( + ctx: ErrorContextInterface> + ) => { + setState(s => ({ + ...s, + isActive: ctx.isActive, + })); + }; + const onConnectError = ( + ctx: ErrorContextInterface>, + err: Error + ) => { + setState(s => ({ + ...s, + isActive: ctx.isActive, + connectionError: err, + })); + }; + connectionBuilder.onConnect(onConnect); + connectionBuilder.onDisconnect(onDisconnect); + connectionBuilder.onConnectError(onConnectError); + + const conn = connRef.current; + setState(s => ({ + ...s, + isActive: conn.isActive, + identity: conn.identity, + token: conn.token, + connectionId: conn.connectionId, + })); + + return () => { + connRef.current?.removeOnConnect(onConnect as any); + connRef.current?.removeOnDisconnect(onDisconnect as any); + connRef.current?.removeOnConnectError(onConnectError as any); + connRef.current?.disconnect(); + connRef.current = null; + }; + }, [connectionBuilder]); + return React.createElement( SpacetimeDBContext.Provider, - { value: connectionBuilder.build() }, // May need to modify this to do it lazily in server-side rendering + { value: state }, children ); } diff --git a/crates/bindings-typescript/src/react/connection_state.ts b/crates/bindings-typescript/src/react/connection_state.ts new file mode 100644 index 00000000000..056a3c7b3d3 --- /dev/null +++ b/crates/bindings-typescript/src/react/connection_state.ts @@ -0,0 +1,14 @@ +import type { ConnectionId } from '../lib/connection_id'; +import type { Identity } from '../lib/identity'; +import type { DbConnectionImpl } from '../sdk/db_connection_impl'; + +export type ConnectionState = { + isActive: boolean; + identity?: Identity; + token?: string; + connectionId: ConnectionId; + connectionError?: Error; + getConnection< + DbConnection extends DbConnectionImpl, + >(): DbConnection | null; +}; diff --git a/crates/bindings-typescript/src/react/index.ts b/crates/bindings-typescript/src/react/index.ts index b99fe7f78f4..6bcf01a6a28 100644 --- a/crates/bindings-typescript/src/react/index.ts +++ b/crates/bindings-typescript/src/react/index.ts @@ -1,3 +1,4 @@ export * from './SpacetimeDBProvider.ts'; export { useSpacetimeDB } from './useSpacetimeDB.ts'; export { useTable, where, eq } from './useTable.ts'; +export { useReducer } from './useReducer.ts'; diff --git a/crates/bindings-typescript/src/react/useReducer.ts b/crates/bindings-typescript/src/react/useReducer.ts new file mode 100644 index 00000000000..742f456ae31 --- /dev/null +++ b/crates/bindings-typescript/src/react/useReducer.ts @@ -0,0 +1,54 @@ +import { useCallback, useEffect, useRef } from 'react'; +import type { InferTypeOfRow } from '../lib/type_builders'; +import type { UntypedReducerDef } from '../sdk/reducers'; +import { useSpacetimeDB } from './useSpacetimeDB'; +import type { Prettify } from '../lib/type_util'; + +type IsEmptyObject = [keyof T] extends [never] ? true : false; +type MaybeParams = IsEmptyObject extends true ? [] : [params: T]; + +type ParamsType = MaybeParams< + Prettify> +>; + +export function useReducer( + reducerDef: ReducerDef +): (...params: ParamsType) => void { + const { getConnection, isActive } = useSpacetimeDB(); + const reducerName = reducerDef.accessorName; + + // Holds calls made before the connection exists + const queueRef = useRef[]>([]); + + // Flush when we finally have a connection + useEffect(() => { + const conn = getConnection(); + if (!conn) { + return; + } + const fn = (conn.reducers as any)[reducerName] as ( + p: ParamsType + ) => void; + if (queueRef.current.length) { + const pending = queueRef.current.splice(0); + for (const params of pending) { + fn(params); + } + } + }, [getConnection, reducerName, isActive]); + + return useCallback( + (...params: ParamsType) => { + const conn = getConnection(); + if (!conn) { + queueRef.current.push(params); + return; + } + const fn = (conn.reducers as any)[reducerName] as ( + p: ParamsType + ) => void; + return fn(params); + }, + [getConnection, reducerName] + ); +} diff --git a/crates/bindings-typescript/src/react/useSpacetimeDB.ts b/crates/bindings-typescript/src/react/useSpacetimeDB.ts index 505c8143742..2a7cbfc828a 100644 --- a/crates/bindings-typescript/src/react/useSpacetimeDB.ts +++ b/crates/bindings-typescript/src/react/useSpacetimeDB.ts @@ -1,15 +1,14 @@ -import { createContext, useContext, type Context } from 'react'; -import type { DbConnectionImpl } from '../sdk/db_connection_impl'; +import { createContext, useContext } from 'react'; +import type { ConnectionState } from './connection_state'; -export const SpacetimeDBContext: Context = - createContext(undefined); +export const SpacetimeDBContext = createContext( + undefined +); // Throws an error if used outside of a SpacetimeDBProvider // Error is caught by other hooks like useTable so they can provide better error messages -export function useSpacetimeDB< - DbConnection extends DbConnectionImpl, ->(): DbConnection { - const context = useContext(SpacetimeDBContext) as DbConnection | undefined; +export function useSpacetimeDB(): ConnectionState { + const context = useContext(SpacetimeDBContext) as ConnectionState | undefined; if (!context) { throw new Error( 'useSpacetimeDB must be used within a SpacetimeDBProvider component. Did you forget to add a `SpacetimeDBProvider` to your component tree?' diff --git a/crates/bindings-typescript/src/react/useTable.ts b/crates/bindings-typescript/src/react/useTable.ts index 78f675f6e31..98b4d55a68c 100644 --- a/crates/bindings-typescript/src/react/useTable.ts +++ b/crates/bindings-typescript/src/react/useTable.ts @@ -6,10 +6,13 @@ import { useSyncExternalStore, } from 'react'; import { useSpacetimeDB } from './useSpacetimeDB'; -import { DbConnectionImpl, TableCache } from '../sdk/db_connection_impl'; -import type { TableNamesFromDb } from '../sdk/table_handle'; +import { type EventContextInterface } from '../sdk/db_connection_impl'; +import type { ConnectionState } from './connection_state'; +import type { UntypedRemoteModule } from '../sdk/spacetime_module'; +import type { RowType, UntypedTableDef } from '../lib/table'; +import type { Prettify } from '../lib/type_util'; -export interface UseQueryCallbacks { +export interface UseTableCallbacks { onInsert?: (row: RowType) => void; onDelete?: (row: RowType) => void; onUpdate?: (oldRow: RowType, newRow: RowType) => void; @@ -67,11 +70,9 @@ export const isOr = ( e: Expr ): e is Extract, { type: 'or' }> => e.type === 'or'; -type RecordLike = Record; - export function evaluate( expr: Expr, - row: RecordLike + row: Record ): boolean { switch (expr.type) { case 'eq': { @@ -137,11 +138,6 @@ export function where(expr: Expr): Expr { return expr; } -type Snapshot = { - readonly rows: readonly RowType[]; - readonly state: 'loading' | 'ready'; -}; - type MembershipChange = 'enter' | 'leave' | 'stayIn' | 'stayOut'; function classifyMembership< @@ -210,17 +206,11 @@ type ColumnsFromRow = { * }); * ``` */ -export function useTable< - DbConnection extends DbConnectionImpl, - RowType extends Record, - TableName extends TableNamesFromDb = TableNamesFromDb< - DbConnection['db'] - >, ->( - tableName: TableName, - where: Expr>, - callbacks?: UseQueryCallbacks -): Snapshot; +export function useTable( + tableDef: TableDef, + where: Expr>>, + callbacks?: UseTableCallbacks>> +): readonly Prettify>[]; /** * React hook to subscribe to a table in SpacetimeDB and receive live updates as rows are inserted, updated, or deleted. @@ -255,46 +245,38 @@ export function useTable< * }); * ``` */ -export function useTable< - DbConnection extends DbConnectionImpl, - RowType extends Record, - TableName extends TableNamesFromDb = TableNamesFromDb< - DbConnection['db'] - >, ->( - tableName: TableName, - callbacks?: UseQueryCallbacks -): Snapshot; - -export function useTable< - DbConnection extends DbConnectionImpl, - RowType extends Record, - TableName extends TableNamesFromDb = TableNamesFromDb< - DbConnection['db'] - >, ->( - tableName: TableName, +export function useTable( + tableDef: TableDef, + callbacks?: UseTableCallbacks>> +): readonly Prettify>[]; + +export function useTable( + tableDef: TableDef, whereClauseOrCallbacks?: - | Expr> - | UseQueryCallbacks, - callbacks?: UseQueryCallbacks -): Snapshot { - let whereClause: Expr> | undefined; + | Expr>> + | UseTableCallbacks>, + callbacks?: UseTableCallbacks> +): readonly Prettify>[] { + type UseTableRowType = RowType; + const tableName = tableDef.name; + let whereClause: Expr> | undefined; if ( whereClauseOrCallbacks && typeof whereClauseOrCallbacks === 'object' && 'type' in whereClauseOrCallbacks ) { - whereClause = whereClauseOrCallbacks as Expr>; + whereClause = whereClauseOrCallbacks as Expr< + ColumnsFromRow + >; } else { callbacks = whereClauseOrCallbacks as - | UseQueryCallbacks + | UseTableCallbacks | undefined; } const [subscribeApplied, setSubscribeApplied] = useState(false); - let spacetime: DbConnection | undefined; + let connectionState: ConnectionState | undefined; try { - spacetime = useSpacetimeDB(); + connectionState = useSpacetimeDB(); } catch { throw new Error( 'Could not find SpacetimeDB client! Did you forget to add a ' + @@ -302,34 +284,38 @@ export function useTable< 'under a `SpacetimeDBProvider` component.' ); } - const client = spacetime; const query = `SELECT * FROM ${tableName}` + (whereClause ? ` WHERE ${toString(whereClause)}` : ''); const latestTransactionEvent = useRef(null); - const lastSnapshotRef = useRef | null>(null); + const lastSnapshotRef = useRef[] | null>( + null + ); const whereKey = whereClause ? toString(whereClause) : ''; - const computeSnapshot = useCallback((): Snapshot => { - const table = client.db[ - tableName as keyof typeof client.db - ] as unknown as TableCache; - const result: readonly RowType[] = whereClause - ? table.iter().filter(row => evaluate(whereClause, row)) - : table.iter(); - return { - rows: result, - state: subscribeApplied ? 'ready' : 'loading', - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [client, tableName, whereKey, subscribeApplied]); + const computeSnapshot = + useCallback((): readonly Prettify[] => { + const connection = connectionState.getConnection(); + if (!connection) { + return []; + } + const table = connection.db[tableName]; + const result: readonly Prettify[] = whereClause + ? (Array.from(table.iter()).filter(row => + evaluate(whereClause, row as UseTableRowType) + ) as Prettify[]) + : (Array.from(table.iter()) as Prettify[]); + return result; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [connectionState, tableName, whereKey, subscribeApplied]); useEffect(() => { - if (client.isActive) { - const cancel = client + const connection = connectionState.getConnection()!; + if (connectionState.isActive && connection) { + const cancel = connection .subscriptionBuilder() .onApplied(() => { setSubscribeApplied(true); @@ -339,11 +325,14 @@ export function useTable< cancel.unsubscribe(); }; } - }, [query, client.isActive, client]); + }, [query, connectionState.isActive, connectionState]); const subscribe = useCallback( (onStoreChange: () => void) => { - const onInsert = (ctx: any, row: RowType) => { + const onInsert = ( + ctx: EventContextInterface, + row: any + ) => { if (whereClause && !evaluate(whereClause, row)) { return; } @@ -358,7 +347,10 @@ export function useTable< } }; - const onDelete = (ctx: any, row: RowType) => { + const onDelete = ( + ctx: EventContextInterface, + row: any + ) => { if (whereClause && !evaluate(whereClause, row)) { return; } @@ -373,7 +365,11 @@ export function useTable< } }; - const onUpdate = (ctx: any, oldRow: RowType, newRow: RowType) => { + const onUpdate = ( + ctx: EventContextInterface, + oldRow: any, + newRow: any + ) => { const change = classifyMembership(whereClause, oldRow, newRow); switch (change) { @@ -400,9 +396,12 @@ export function useTable< } }; - const table = client.db[ - tableName as keyof typeof client.db - ] as unknown as TableCache; + const connection = connectionState.getConnection(); + if (!connection) { + return () => {}; + } + + const table = connection.db[tableName]; table.onInsert(onInsert); table.onDelete(onDelete); table.onUpdate?.(onUpdate); @@ -415,7 +414,7 @@ export function useTable< }, // eslint-disable-next-line react-hooks/exhaustive-deps [ - client, + connectionState, tableName, whereKey, callbacks?.onDelete, @@ -424,7 +423,7 @@ export function useTable< ] ); - const getSnapshot = useCallback((): Snapshot => { + const getSnapshot = useCallback((): readonly Prettify[] => { if (!lastSnapshotRef.current) { lastSnapshotRef.current = computeSnapshot(); } diff --git a/crates/bindings-typescript/src/sdk/client_api/bsatn_row_list_type.ts b/crates/bindings-typescript/src/sdk/client_api/bsatn_row_list_type.ts index 2e769689c07..785d9595b7e 100644 --- a/crates/bindings-typescript/src/sdk/client_api/bsatn_row_list_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/bsatn_row_list_type.ts @@ -4,79 +4,16 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { RowSizeHint } from './row_size_hint_type'; -// Mark import as potentially unused -declare type __keep_RowSizeHint = RowSizeHint; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import RowSizeHint from './row_size_hint_type'; -export type BsatnRowList = { - sizeHint: RowSizeHint; - rowsData: Uint8Array; -}; -let _cached_BsatnRowList_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const BsatnRowList = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_BsatnRowList_type_value) return _cached_BsatnRowList_type_value; - _cached_BsatnRowList_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_BsatnRowList_type_value.value.elements.push( - { - name: 'sizeHint', - algebraicType: RowSizeHint.getTypeScriptAlgebraicType(), - }, - { - name: 'rowsData', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.U8), - } - ); - return _cached_BsatnRowList_type_value; - }, - - serialize(writer: __BinaryWriter, value: BsatnRowList): void { - __AlgebraicTypeValue.serializeValue( - writer, - BsatnRowList.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('BsatnRowList', { + get sizeHint() { + return RowSizeHint; }, - - deserialize(reader: __BinaryReader): BsatnRowList { - return __AlgebraicTypeValue.deserializeValue( - reader, - BsatnRowList.getTypeScriptAlgebraicType() - ); - }, -}; - -export default BsatnRowList; + rowsData: __t.byteArray(), +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/call_procedure_type.ts b/crates/bindings-typescript/src/sdk/client_api/call_procedure_type.ts new file mode 100644 index 00000000000..6be8e6916d7 --- /dev/null +++ b/crates/bindings-typescript/src/sdk/client_api/call_procedure_type.ts @@ -0,0 +1,18 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; + +export default __t.object('CallProcedure', { + procedure: __t.string(), + args: __t.byteArray(), + requestId: __t.u32(), + flags: __t.u8(), +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/call_reducer_type.ts b/crates/bindings-typescript/src/sdk/client_api/call_reducer_type.ts index 8b41532f796..b1b7045c927 100644 --- a/crates/bindings-typescript/src/sdk/client_api/call_reducer_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/call_reducer_type.ts @@ -4,77 +4,15 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; -export type CallReducer = { - reducer: string; - args: Uint8Array; - requestId: number; - flags: number; -}; -let _cached_CallReducer_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const CallReducer = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_CallReducer_type_value) return _cached_CallReducer_type_value; - _cached_CallReducer_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_CallReducer_type_value.value.elements.push( - { name: 'reducer', algebraicType: __AlgebraicTypeValue.String }, - { - name: 'args', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.U8), - }, - { name: 'requestId', algebraicType: __AlgebraicTypeValue.U32 }, - { name: 'flags', algebraicType: __AlgebraicTypeValue.U8 } - ); - return _cached_CallReducer_type_value; - }, - - serialize(writer: __BinaryWriter, value: CallReducer): void { - __AlgebraicTypeValue.serializeValue( - writer, - CallReducer.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): CallReducer { - return __AlgebraicTypeValue.deserializeValue( - reader, - CallReducer.getTypeScriptAlgebraicType() - ); - }, -}; - -export default CallReducer; +export default __t.object('CallReducer', { + reducer: __t.string(), + args: __t.byteArray(), + requestId: __t.u32(), + flags: __t.u8(), +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/client_message_type.ts b/crates/bindings-typescript/src/sdk/client_api/client_message_type.ts index 4883bbf7a85..7024d9d2840 100644 --- a/crates/bindings-typescript/src/sdk/client_api/client_message_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/client_message_type.ts @@ -4,158 +4,46 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { CallReducer } from './call_reducer_type'; -// Mark import as potentially unused -declare type __keep_CallReducer = CallReducer; -import { Subscribe } from './subscribe_type'; -// Mark import as potentially unused -declare type __keep_Subscribe = Subscribe; -import { OneOffQuery } from './one_off_query_type'; -// Mark import as potentially unused -declare type __keep_OneOffQuery = OneOffQuery; -import { SubscribeSingle } from './subscribe_single_type'; -// Mark import as potentially unused -declare type __keep_SubscribeSingle = SubscribeSingle; -import { SubscribeMulti } from './subscribe_multi_type'; -// Mark import as potentially unused -declare type __keep_SubscribeMulti = SubscribeMulti; -import { Unsubscribe } from './unsubscribe_type'; -// Mark import as potentially unused -declare type __keep_Unsubscribe = Unsubscribe; -import { UnsubscribeMulti } from './unsubscribe_multi_type'; -// Mark import as potentially unused -declare type __keep_UnsubscribeMulti = UnsubscribeMulti; - -import * as ClientMessageVariants from './client_message_variants'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import CallReducer from './call_reducer_type'; +import Subscribe from './subscribe_type'; +import OneOffQuery from './one_off_query_type'; +import SubscribeSingle from './subscribe_single_type'; +import SubscribeMulti from './subscribe_multi_type'; +import Unsubscribe from './unsubscribe_type'; +import UnsubscribeMulti from './unsubscribe_multi_type'; +import CallProcedure from './call_procedure_type'; // The tagged union or sum type for the algebraic type `ClientMessage`. -export type ClientMessage = - | ClientMessageVariants.CallReducer - | ClientMessageVariants.Subscribe - | ClientMessageVariants.OneOffQuery - | ClientMessageVariants.SubscribeSingle - | ClientMessageVariants.SubscribeMulti - | ClientMessageVariants.Unsubscribe - | ClientMessageVariants.UnsubscribeMulti; - -let _cached_ClientMessage_type_value: __AlgebraicTypeType | null = null; - -// A value with helper functions to construct the type. -export const ClientMessage = { - // Helper functions for constructing each variant of the tagged union. - // ``` - // const foo = Foo.A(42); - // assert!(foo.tag === "A"); - // assert!(foo.value === 42); - // ``` - CallReducer: (value: CallReducer): ClientMessageVariants.CallReducer => ({ - tag: 'CallReducer', - value, - }), - Subscribe: (value: Subscribe): ClientMessageVariants.Subscribe => ({ - tag: 'Subscribe', - value, - }), - OneOffQuery: (value: OneOffQuery): ClientMessageVariants.OneOffQuery => ({ - tag: 'OneOffQuery', - value, - }), - SubscribeSingle: ( - value: SubscribeSingle - ): ClientMessageVariants.SubscribeSingle => ({ - tag: 'SubscribeSingle', - value, - }), - SubscribeMulti: ( - value: SubscribeMulti - ): ClientMessageVariants.SubscribeMulti => ({ tag: 'SubscribeMulti', value }), - Unsubscribe: (value: Unsubscribe): ClientMessageVariants.Unsubscribe => ({ - tag: 'Unsubscribe', - value, - }), - UnsubscribeMulti: ( - value: UnsubscribeMulti - ): ClientMessageVariants.UnsubscribeMulti => ({ - tag: 'UnsubscribeMulti', - value, - }), - - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_ClientMessage_type_value) - return _cached_ClientMessage_type_value; - _cached_ClientMessage_type_value = __AlgebraicTypeValue.Sum({ - variants: [], - }); - _cached_ClientMessage_type_value.value.variants.push( - { - name: 'CallReducer', - algebraicType: CallReducer.getTypeScriptAlgebraicType(), - }, - { - name: 'Subscribe', - algebraicType: Subscribe.getTypeScriptAlgebraicType(), - }, - { - name: 'OneOffQuery', - algebraicType: OneOffQuery.getTypeScriptAlgebraicType(), - }, - { - name: 'SubscribeSingle', - algebraicType: SubscribeSingle.getTypeScriptAlgebraicType(), - }, - { - name: 'SubscribeMulti', - algebraicType: SubscribeMulti.getTypeScriptAlgebraicType(), - }, - { - name: 'Unsubscribe', - algebraicType: Unsubscribe.getTypeScriptAlgebraicType(), - }, - { - name: 'UnsubscribeMulti', - algebraicType: UnsubscribeMulti.getTypeScriptAlgebraicType(), - } - ); - return _cached_ClientMessage_type_value; +const ClientMessage = __t.enum('ClientMessage', { + get CallReducer() { + return CallReducer; }, - - serialize(writer: __BinaryWriter, value: ClientMessage): void { - __AlgebraicTypeValue.serializeValue( - writer, - ClientMessage.getTypeScriptAlgebraicType(), - value - ); + get Subscribe() { + return Subscribe; }, - - deserialize(reader: __BinaryReader): ClientMessage { - return __AlgebraicTypeValue.deserializeValue( - reader, - ClientMessage.getTypeScriptAlgebraicType() - ); + get OneOffQuery() { + return OneOffQuery; + }, + get SubscribeSingle() { + return SubscribeSingle; + }, + get SubscribeMulti() { + return SubscribeMulti; + }, + get Unsubscribe() { + return Unsubscribe; + }, + get UnsubscribeMulti() { + return UnsubscribeMulti; + }, + get CallProcedure() { + return CallProcedure; }, -}; +}); export default ClientMessage; diff --git a/crates/bindings-typescript/src/sdk/client_api/client_message_variants.ts b/crates/bindings-typescript/src/sdk/client_api/client_message_variants.ts deleted file mode 100644 index a5bcbd5eae6..00000000000 --- a/crates/bindings-typescript/src/sdk/client_api/client_message_variants.ts +++ /dev/null @@ -1,67 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -/* eslint-disable */ -/* tslint:disable */ -import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { CallReducer as CallReducerType } from './call_reducer_type'; -// Mark import as potentially unused -declare type __keep_CallReducerType = CallReducerType; -import { Subscribe as SubscribeType } from './subscribe_type'; -// Mark import as potentially unused -declare type __keep_SubscribeType = SubscribeType; -import { OneOffQuery as OneOffQueryType } from './one_off_query_type'; -// Mark import as potentially unused -declare type __keep_OneOffQueryType = OneOffQueryType; -import { SubscribeSingle as SubscribeSingleType } from './subscribe_single_type'; -// Mark import as potentially unused -declare type __keep_SubscribeSingleType = SubscribeSingleType; -import { SubscribeMulti as SubscribeMultiType } from './subscribe_multi_type'; -// Mark import as potentially unused -declare type __keep_SubscribeMultiType = SubscribeMultiType; -import { Unsubscribe as UnsubscribeType } from './unsubscribe_type'; -// Mark import as potentially unused -declare type __keep_UnsubscribeType = UnsubscribeType; -import { UnsubscribeMulti as UnsubscribeMultiType } from './unsubscribe_multi_type'; -// Mark import as potentially unused -declare type __keep_UnsubscribeMultiType = UnsubscribeMultiType; - -export type CallReducer = { tag: 'CallReducer'; value: CallReducerType }; -export type Subscribe = { tag: 'Subscribe'; value: SubscribeType }; -export type OneOffQuery = { tag: 'OneOffQuery'; value: OneOffQueryType }; -export type SubscribeSingle = { - tag: 'SubscribeSingle'; - value: SubscribeSingleType; -}; -export type SubscribeMulti = { - tag: 'SubscribeMulti'; - value: SubscribeMultiType; -}; -export type Unsubscribe = { tag: 'Unsubscribe'; value: UnsubscribeType }; -export type UnsubscribeMulti = { - tag: 'UnsubscribeMulti'; - value: UnsubscribeMultiType; -}; diff --git a/crates/bindings-typescript/src/sdk/client_api/compressable_query_update_type.ts b/crates/bindings-typescript/src/sdk/client_api/compressable_query_update_type.ts index 65ec3b3f8eb..fd07c71773b 100644 --- a/crates/bindings-typescript/src/sdk/client_api/compressable_query_update_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/compressable_query_update_type.ts @@ -4,104 +4,20 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { QueryUpdate } from './query_update_type'; -// Mark import as potentially unused -declare type __keep_QueryUpdate = QueryUpdate; - -import * as CompressableQueryUpdateVariants from './compressable_query_update_variants'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import QueryUpdate from './query_update_type'; // The tagged union or sum type for the algebraic type `CompressableQueryUpdate`. -export type CompressableQueryUpdate = - | CompressableQueryUpdateVariants.Uncompressed - | CompressableQueryUpdateVariants.Brotli - | CompressableQueryUpdateVariants.Gzip; - -let _cached_CompressableQueryUpdate_type_value: __AlgebraicTypeType | null = - null; - -// A value with helper functions to construct the type. -export const CompressableQueryUpdate = { - // Helper functions for constructing each variant of the tagged union. - // ``` - // const foo = Foo.A(42); - // assert!(foo.tag === "A"); - // assert!(foo.value === 42); - // ``` - Uncompressed: ( - value: QueryUpdate - ): CompressableQueryUpdateVariants.Uncompressed => ({ - tag: 'Uncompressed', - value, - }), - Brotli: (value: Uint8Array): CompressableQueryUpdateVariants.Brotli => ({ - tag: 'Brotli', - value, - }), - Gzip: (value: Uint8Array): CompressableQueryUpdateVariants.Gzip => ({ - tag: 'Gzip', - value, - }), - - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_CompressableQueryUpdate_type_value) - return _cached_CompressableQueryUpdate_type_value; - _cached_CompressableQueryUpdate_type_value = __AlgebraicTypeValue.Sum({ - variants: [], - }); - _cached_CompressableQueryUpdate_type_value.value.variants.push( - { - name: 'Uncompressed', - algebraicType: QueryUpdate.getTypeScriptAlgebraicType(), - }, - { - name: 'Brotli', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.U8), - }, - { - name: 'Gzip', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.U8), - } - ); - return _cached_CompressableQueryUpdate_type_value; - }, - - serialize(writer: __BinaryWriter, value: CompressableQueryUpdate): void { - __AlgebraicTypeValue.serializeValue( - writer, - CompressableQueryUpdate.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): CompressableQueryUpdate { - return __AlgebraicTypeValue.deserializeValue( - reader, - CompressableQueryUpdate.getTypeScriptAlgebraicType() - ); +const CompressableQueryUpdate = __t.enum('CompressableQueryUpdate', { + get Uncompressed() { + return QueryUpdate; }, -}; + Brotli: __t.byteArray(), + Gzip: __t.byteArray(), +}); export default CompressableQueryUpdate; diff --git a/crates/bindings-typescript/src/sdk/client_api/compressable_query_update_variants.ts b/crates/bindings-typescript/src/sdk/client_api/compressable_query_update_variants.ts deleted file mode 100644 index a1542e7d2bc..00000000000 --- a/crates/bindings-typescript/src/sdk/client_api/compressable_query_update_variants.ts +++ /dev/null @@ -1,36 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -/* eslint-disable */ -/* tslint:disable */ -import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { QueryUpdate as QueryUpdateType } from './query_update_type'; -// Mark import as potentially unused -declare type __keep_QueryUpdateType = QueryUpdateType; - -export type Uncompressed = { tag: 'Uncompressed'; value: QueryUpdateType }; -export type Brotli = { tag: 'Brotli'; value: Uint8Array }; -export type Gzip = { tag: 'Gzip'; value: Uint8Array }; diff --git a/crates/bindings-typescript/src/sdk/client_api/database_update_type.ts b/crates/bindings-typescript/src/sdk/client_api/database_update_type.ts index 45745374d29..0334e62ff43 100644 --- a/crates/bindings-typescript/src/sdk/client_api/database_update_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/database_update_type.ts @@ -4,75 +4,15 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { TableUpdate } from './table_update_type'; -// Mark import as potentially unused -declare type __keep_TableUpdate = TableUpdate; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import TableUpdate from './table_update_type'; -export type DatabaseUpdate = { - tables: TableUpdate[]; -}; -let _cached_DatabaseUpdate_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const DatabaseUpdate = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_DatabaseUpdate_type_value) - return _cached_DatabaseUpdate_type_value; - _cached_DatabaseUpdate_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_DatabaseUpdate_type_value.value.elements.push({ - name: 'tables', - algebraicType: __AlgebraicTypeValue.Array( - TableUpdate.getTypeScriptAlgebraicType() - ), - }); - return _cached_DatabaseUpdate_type_value; - }, - - serialize(writer: __BinaryWriter, value: DatabaseUpdate): void { - __AlgebraicTypeValue.serializeValue( - writer, - DatabaseUpdate.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('DatabaseUpdate', { + get tables() { + return __t.array(TableUpdate); }, - - deserialize(reader: __BinaryReader): DatabaseUpdate { - return __AlgebraicTypeValue.deserializeValue( - reader, - DatabaseUpdate.getTypeScriptAlgebraicType() - ); - }, -}; - -export default DatabaseUpdate; +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/energy_quanta_type.ts b/crates/bindings-typescript/src/sdk/client_api/energy_quanta_type.ts index 73ab3911e5c..4c100ba390c 100644 --- a/crates/bindings-typescript/src/sdk/client_api/energy_quanta_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/energy_quanta_type.ts @@ -4,69 +4,12 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; - -export type EnergyQuanta = { - quanta: bigint; -}; -let _cached_EnergyQuanta_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const EnergyQuanta = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_EnergyQuanta_type_value) return _cached_EnergyQuanta_type_value; - _cached_EnergyQuanta_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_EnergyQuanta_type_value.value.elements.push({ - name: 'quanta', - algebraicType: __AlgebraicTypeValue.U128, - }); - return _cached_EnergyQuanta_type_value; - }, - - serialize(writer: __BinaryWriter, value: EnergyQuanta): void { - __AlgebraicTypeValue.serializeValue( - writer, - EnergyQuanta.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): EnergyQuanta { - return __AlgebraicTypeValue.deserializeValue( - reader, - EnergyQuanta.getTypeScriptAlgebraicType() - ); - }, -}; - -export default EnergyQuanta; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; + +export default __t.object('EnergyQuanta', { + quanta: __t.u128(), +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/identity_token_type.ts b/crates/bindings-typescript/src/sdk/client_api/identity_token_type.ts index e92172030cd..e251e103e92 100644 --- a/crates/bindings-typescript/src/sdk/client_api/identity_token_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/identity_token_type.ts @@ -4,79 +4,14 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; -export type IdentityToken = { - identity: __Identity; - token: string; - connectionId: __ConnectionId; -}; -let _cached_IdentityToken_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const IdentityToken = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_IdentityToken_type_value) - return _cached_IdentityToken_type_value; - _cached_IdentityToken_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_IdentityToken_type_value.value.elements.push( - { - name: 'identity', - algebraicType: __AlgebraicTypeValue.createIdentityType(), - }, - { name: 'token', algebraicType: __AlgebraicTypeValue.String }, - { - name: 'connectionId', - algebraicType: __AlgebraicTypeValue.createConnectionIdType(), - } - ); - return _cached_IdentityToken_type_value; - }, - - serialize(writer: __BinaryWriter, value: IdentityToken): void { - __AlgebraicTypeValue.serializeValue( - writer, - IdentityToken.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): IdentityToken { - return __AlgebraicTypeValue.deserializeValue( - reader, - IdentityToken.getTypeScriptAlgebraicType() - ); - }, -}; - -export default IdentityToken; +export default __t.object('IdentityToken', { + identity: __t.identity(), + token: __t.string(), + connectionId: __t.connectionId(), +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/index.ts b/crates/bindings-typescript/src/sdk/client_api/index.ts index 5e3cc809133..8548380f1dd 100644 --- a/crates/bindings-typescript/src/sdk/client_api/index.ts +++ b/crates/bindings-typescript/src/sdk/client_api/index.ts @@ -1,33 +1,30 @@ // THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE // WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. -// This was generated using ../../index cli version 1.5.0 (commit 5bfc84351742a6a8dc717b6c0011946f2d1b632d). +// This was generated using spacetimedb cli version 1.7.0 (commit cb16789be729954a7c47b87fb40b35baa0bd1029). /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, DbConnectionBuilder as __DbConnectionBuilder, DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, + TypeBuilder as __TypeBuilder, + convertToAccessorMap as __convertToAccessorMap, + reducerSchema as __reducerSchema, + reducers as __reducers, + schema as __schema, + t as __t, + table as __table, + type AlgebraicTypeType as __AlgebraicTypeType, + type DbConnectionConfig as __DbConnectionConfig, type ErrorContextInterface as __ErrorContextInterface, type Event as __Event, type EventContextInterface as __EventContextInterface, + type Infer as __Infer, type ReducerEventContextInterface as __ReducerEventContextInterface, + type RemoteModule as __RemoteModule, type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, } from '../../index'; // Import and reexport all reducer arg types @@ -35,167 +32,119 @@ import { // Import and reexport all table handle types // Import and reexport all types -import { BsatnRowList } from './bsatn_row_list_type.ts'; +import BsatnRowList from './bsatn_row_list_type'; export { BsatnRowList }; -import { CallReducer } from './call_reducer_type.ts'; +import CallProcedure from './call_procedure_type'; +export { CallProcedure }; +import CallReducer from './call_reducer_type'; export { CallReducer }; -import { ClientMessage } from './client_message_type.ts'; +import ClientMessage from './client_message_type'; export { ClientMessage }; -import { CompressableQueryUpdate } from './compressable_query_update_type.ts'; +import CompressableQueryUpdate from './compressable_query_update_type'; export { CompressableQueryUpdate }; -import { DatabaseUpdate } from './database_update_type.ts'; +import DatabaseUpdate from './database_update_type'; export { DatabaseUpdate }; -import { EnergyQuanta } from './energy_quanta_type.ts'; +import EnergyQuanta from './energy_quanta_type'; export { EnergyQuanta }; -import { IdentityToken } from './identity_token_type.ts'; +import IdentityToken from './identity_token_type'; export { IdentityToken }; -import { InitialSubscription } from './initial_subscription_type.ts'; +import InitialSubscription from './initial_subscription_type'; export { InitialSubscription }; -import { OneOffQuery } from './one_off_query_type.ts'; +import OneOffQuery from './one_off_query_type'; export { OneOffQuery }; -import { OneOffQueryResponse } from './one_off_query_response_type.ts'; +import OneOffQueryResponse from './one_off_query_response_type'; export { OneOffQueryResponse }; -import { OneOffTable } from './one_off_table_type.ts'; +import OneOffTable from './one_off_table_type'; export { OneOffTable }; -import { QueryId } from './query_id_type.ts'; +import ProcedureResult from './procedure_result_type'; +export { ProcedureResult }; +import ProcedureStatus from './procedure_status_type'; +export { ProcedureStatus }; +import QueryId from './query_id_type'; export { QueryId }; -import { QueryUpdate } from './query_update_type.ts'; +import QueryUpdate from './query_update_type'; export { QueryUpdate }; -import { ReducerCallInfo } from './reducer_call_info_type.ts'; +import ReducerCallInfo from './reducer_call_info_type'; export { ReducerCallInfo }; -import { RowSizeHint } from './row_size_hint_type.ts'; +import RowSizeHint from './row_size_hint_type'; export { RowSizeHint }; -import { ServerMessage } from './server_message_type.ts'; +import ServerMessage from './server_message_type'; export { ServerMessage }; -import { Subscribe } from './subscribe_type.ts'; +import Subscribe from './subscribe_type'; export { Subscribe }; -import { SubscribeApplied } from './subscribe_applied_type.ts'; +import SubscribeApplied from './subscribe_applied_type'; export { SubscribeApplied }; -import { SubscribeMulti } from './subscribe_multi_type.ts'; +import SubscribeMulti from './subscribe_multi_type'; export { SubscribeMulti }; -import { SubscribeMultiApplied } from './subscribe_multi_applied_type.ts'; +import SubscribeMultiApplied from './subscribe_multi_applied_type'; export { SubscribeMultiApplied }; -import { SubscribeRows } from './subscribe_rows_type.ts'; +import SubscribeRows from './subscribe_rows_type'; export { SubscribeRows }; -import { SubscribeSingle } from './subscribe_single_type.ts'; +import SubscribeSingle from './subscribe_single_type'; export { SubscribeSingle }; -import { SubscriptionError } from './subscription_error_type.ts'; +import SubscriptionError from './subscription_error_type'; export { SubscriptionError }; -import { TableUpdate } from './table_update_type.ts'; +import TableUpdate from './table_update_type'; export { TableUpdate }; -import { TransactionUpdate } from './transaction_update_type.ts'; +import TransactionUpdate from './transaction_update_type'; export { TransactionUpdate }; -import { TransactionUpdateLight } from './transaction_update_light_type.ts'; +import TransactionUpdateLight from './transaction_update_light_type'; export { TransactionUpdateLight }; -import { Unsubscribe } from './unsubscribe_type.ts'; +import Unsubscribe from './unsubscribe_type'; export { Unsubscribe }; -import { UnsubscribeApplied } from './unsubscribe_applied_type.ts'; +import UnsubscribeApplied from './unsubscribe_applied_type'; export { UnsubscribeApplied }; -import { UnsubscribeMulti } from './unsubscribe_multi_type.ts'; +import UnsubscribeMulti from './unsubscribe_multi_type'; export { UnsubscribeMulti }; -import { UnsubscribeMultiApplied } from './unsubscribe_multi_applied_type.ts'; +import UnsubscribeMultiApplied from './unsubscribe_multi_applied_type'; export { UnsubscribeMultiApplied }; -import { UpdateStatus } from './update_status_type.ts'; +import UpdateStatus from './update_status_type'; export { UpdateStatus }; +const tablesSchema = __schema(); + +const reducersSchema = __reducers(); + const REMOTE_MODULE = { - tables: {}, - reducers: {}, versionInfo: { - cliVersion: '1.5.0', - }, - // Constructors which are used by the DbConnectionImpl to - // extract type information from the generated RemoteModule. - // - // NOTE: This is not strictly necessary for `eventContextConstructor` because - // all we do is build a TypeScript object which we could have done inside the - // SDK, but if in the future we wanted to create a class this would be - // necessary because classes have methods, so we'll keep it. - eventContextConstructor: ( - imp: __DbConnectionImpl, - event: __Event - ) => { - return { - ...(imp as DbConnection), - event, - }; - }, - dbViewConstructor: (imp: __DbConnectionImpl) => { - return new RemoteTables(imp); - }, - reducersConstructor: ( - imp: __DbConnectionImpl, - setReducerFlags: SetReducerFlags - ) => { - return new RemoteReducers(imp, setReducerFlags); - }, - setReducerFlagsConstructor: () => { - return new SetReducerFlags(); + cliVersion: '1.7.0' as const, }, -}; - -// A type representing all the possible variants of a reducer. -export type Reducer = never; - -export class RemoteReducers { - constructor( - private connection: __DbConnectionImpl, - private setCallReducerFlags: SetReducerFlags - ) {} -} + tables: tablesSchema.schemaType.tables, + reducers: reducersSchema.reducersType.reducers, +} satisfies __RemoteModule< + typeof tablesSchema.schemaType, + typeof reducersSchema.reducersType +>; -export class SetReducerFlags {} +export const tables = __convertToAccessorMap(tablesSchema.schemaType.tables); +export const reducers = __convertToAccessorMap( + reducersSchema.reducersType.reducers +); -export class RemoteTables { - constructor(private connection: __DbConnectionImpl) {} -} +export type EventContext = __EventContextInterface; +export type ReducerEventContext = __ReducerEventContextInterface< + typeof REMOTE_MODULE +>; +export type SubscriptionEventContext = __SubscriptionEventContextInterface< + typeof REMOTE_MODULE +>; +export type ErrorContext = __ErrorContextInterface; export class SubscriptionBuilder extends __SubscriptionBuilderImpl< - RemoteTables, - RemoteReducers, - SetReducerFlags + typeof REMOTE_MODULE > {} -export class DbConnection extends __DbConnectionImpl< - RemoteTables, - RemoteReducers, - SetReducerFlags -> { - static builder = (): __DbConnectionBuilder< - DbConnection, - ErrorContext, - SubscriptionEventContext - > => { - return new __DbConnectionBuilder< - DbConnection, - ErrorContext, - SubscriptionEventContext - >(REMOTE_MODULE, (imp: __DbConnectionImpl) => imp as DbConnection); +export class DbConnectionBuilder extends __DbConnectionBuilder {} + +export class DbConnection extends __DbConnectionImpl { + static builder = (): DbConnectionBuilder => { + return new DbConnectionBuilder( + REMOTE_MODULE, + (config: __DbConnectionConfig) => + new DbConnection(config) + ); }; subscriptionBuilder = (): SubscriptionBuilder => { return new SubscriptionBuilder(this); }; } - -export type EventContext = __EventContextInterface< - RemoteTables, - RemoteReducers, - SetReducerFlags, - Reducer ->; -export type ReducerEventContext = __ReducerEventContextInterface< - RemoteTables, - RemoteReducers, - SetReducerFlags, - Reducer ->; -export type SubscriptionEventContext = __SubscriptionEventContextInterface< - RemoteTables, - RemoteReducers, - SetReducerFlags ->; -export type ErrorContext = __ErrorContextInterface< - RemoteTables, - RemoteReducers, - SetReducerFlags ->; diff --git a/crates/bindings-typescript/src/sdk/client_api/initial_subscription_type.ts b/crates/bindings-typescript/src/sdk/client_api/initial_subscription_type.ts index 26533c4e263..05d2ff3e671 100644 --- a/crates/bindings-typescript/src/sdk/client_api/initial_subscription_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/initial_subscription_type.ts @@ -4,82 +4,17 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { DatabaseUpdate } from './database_update_type'; -// Mark import as potentially unused -declare type __keep_DatabaseUpdate = DatabaseUpdate; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import DatabaseUpdate from './database_update_type'; -export type InitialSubscription = { - databaseUpdate: DatabaseUpdate; - requestId: number; - totalHostExecutionDuration: __TimeDuration; -}; -let _cached_InitialSubscription_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const InitialSubscription = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_InitialSubscription_type_value) - return _cached_InitialSubscription_type_value; - _cached_InitialSubscription_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_InitialSubscription_type_value.value.elements.push( - { - name: 'databaseUpdate', - algebraicType: DatabaseUpdate.getTypeScriptAlgebraicType(), - }, - { name: 'requestId', algebraicType: __AlgebraicTypeValue.U32 }, - { - name: 'totalHostExecutionDuration', - algebraicType: __AlgebraicTypeValue.createTimeDurationType(), - } - ); - return _cached_InitialSubscription_type_value; - }, - - serialize(writer: __BinaryWriter, value: InitialSubscription): void { - __AlgebraicTypeValue.serializeValue( - writer, - InitialSubscription.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('InitialSubscription', { + get databaseUpdate() { + return DatabaseUpdate; }, - - deserialize(reader: __BinaryReader): InitialSubscription { - return __AlgebraicTypeValue.deserializeValue( - reader, - InitialSubscription.getTypeScriptAlgebraicType() - ); - }, -}; - -export default InitialSubscription; + requestId: __t.u32(), + totalHostExecutionDuration: __t.timeDuration(), +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/one_off_query_response_type.ts b/crates/bindings-typescript/src/sdk/client_api/one_off_query_response_type.ts index 3e0dd287591..03dee420bd8 100644 --- a/crates/bindings-typescript/src/sdk/client_api/one_off_query_response_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/one_off_query_response_type.ts @@ -4,94 +4,18 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { OneOffTable } from './one_off_table_type'; -// Mark import as potentially unused -declare type __keep_OneOffTable = OneOffTable; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import OneOffTable from './one_off_table_type'; -export type OneOffQueryResponse = { - messageId: Uint8Array; - error: string | undefined; - tables: OneOffTable[]; - totalHostExecutionDuration: __TimeDuration; -}; -let _cached_OneOffQueryResponse_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const OneOffQueryResponse = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_OneOffQueryResponse_type_value) - return _cached_OneOffQueryResponse_type_value; - _cached_OneOffQueryResponse_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_OneOffQueryResponse_type_value.value.elements.push( - { - name: 'messageId', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.U8), - }, - { - name: 'error', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.String - ), - }, - { - name: 'tables', - algebraicType: __AlgebraicTypeValue.Array( - OneOffTable.getTypeScriptAlgebraicType() - ), - }, - { - name: 'totalHostExecutionDuration', - algebraicType: __AlgebraicTypeValue.createTimeDurationType(), - } - ); - return _cached_OneOffQueryResponse_type_value; - }, - - serialize(writer: __BinaryWriter, value: OneOffQueryResponse): void { - __AlgebraicTypeValue.serializeValue( - writer, - OneOffQueryResponse.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('OneOffQueryResponse', { + messageId: __t.byteArray(), + error: __t.option(__t.string()), + get tables() { + return __t.array(OneOffTable); }, - - deserialize(reader: __BinaryReader): OneOffQueryResponse { - return __AlgebraicTypeValue.deserializeValue( - reader, - OneOffQueryResponse.getTypeScriptAlgebraicType() - ); - }, -}; - -export default OneOffQueryResponse; + totalHostExecutionDuration: __t.timeDuration(), +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/one_off_query_type.ts b/crates/bindings-typescript/src/sdk/client_api/one_off_query_type.ts index 14ef4c02b90..b550bf4304f 100644 --- a/crates/bindings-typescript/src/sdk/client_api/one_off_query_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/one_off_query_type.ts @@ -4,73 +4,13 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; -export type OneOffQuery = { - messageId: Uint8Array; - queryString: string; -}; -let _cached_OneOffQuery_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const OneOffQuery = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_OneOffQuery_type_value) return _cached_OneOffQuery_type_value; - _cached_OneOffQuery_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_OneOffQuery_type_value.value.elements.push( - { - name: 'messageId', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.U8), - }, - { name: 'queryString', algebraicType: __AlgebraicTypeValue.String } - ); - return _cached_OneOffQuery_type_value; - }, - - serialize(writer: __BinaryWriter, value: OneOffQuery): void { - __AlgebraicTypeValue.serializeValue( - writer, - OneOffQuery.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): OneOffQuery { - return __AlgebraicTypeValue.deserializeValue( - reader, - OneOffQuery.getTypeScriptAlgebraicType() - ); - }, -}; - -export default OneOffQuery; +export default __t.object('OneOffQuery', { + messageId: __t.byteArray(), + queryString: __t.string(), +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/one_off_table_type.ts b/crates/bindings-typescript/src/sdk/client_api/one_off_table_type.ts index 9767f476433..2b7017d1b34 100644 --- a/crates/bindings-typescript/src/sdk/client_api/one_off_table_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/one_off_table_type.ts @@ -4,73 +4,16 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { BsatnRowList } from './bsatn_row_list_type'; -// Mark import as potentially unused -declare type __keep_BsatnRowList = BsatnRowList; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import BsatnRowList from './bsatn_row_list_type'; -export type OneOffTable = { - tableName: string; - rows: BsatnRowList; -}; -let _cached_OneOffTable_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const OneOffTable = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_OneOffTable_type_value) return _cached_OneOffTable_type_value; - _cached_OneOffTable_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_OneOffTable_type_value.value.elements.push( - { name: 'tableName', algebraicType: __AlgebraicTypeValue.String }, - { name: 'rows', algebraicType: BsatnRowList.getTypeScriptAlgebraicType() } - ); - return _cached_OneOffTable_type_value; - }, - - serialize(writer: __BinaryWriter, value: OneOffTable): void { - __AlgebraicTypeValue.serializeValue( - writer, - OneOffTable.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('OneOffTable', { + tableName: __t.string(), + get rows() { + return BsatnRowList; }, - - deserialize(reader: __BinaryReader): OneOffTable { - return __AlgebraicTypeValue.deserializeValue( - reader, - OneOffTable.getTypeScriptAlgebraicType() - ); - }, -}; - -export default OneOffTable; +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/procedure_result_type.ts b/crates/bindings-typescript/src/sdk/client_api/procedure_result_type.ts new file mode 100644 index 00000000000..c83dd849bcf --- /dev/null +++ b/crates/bindings-typescript/src/sdk/client_api/procedure_result_type.ts @@ -0,0 +1,21 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import ProcedureStatus from './procedure_status_type'; + +export default __t.object('ProcedureResult', { + get status() { + return ProcedureStatus; + }, + timestamp: __t.timestamp(), + totalHostExecutionDuration: __t.timeDuration(), + requestId: __t.u32(), +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/procedure_status_type.ts b/crates/bindings-typescript/src/sdk/client_api/procedure_status_type.ts new file mode 100644 index 00000000000..29f444f66bd --- /dev/null +++ b/crates/bindings-typescript/src/sdk/client_api/procedure_status_type.ts @@ -0,0 +1,20 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; + +// The tagged union or sum type for the algebraic type `ProcedureStatus`. +const ProcedureStatus = __t.enum('ProcedureStatus', { + Returned: __t.byteArray(), + OutOfEnergy: __t.unit(), + InternalError: __t.string(), +}); + +export default ProcedureStatus; diff --git a/crates/bindings-typescript/src/sdk/client_api/query_id_type.ts b/crates/bindings-typescript/src/sdk/client_api/query_id_type.ts index a2ffef60aad..9c8cd403090 100644 --- a/crates/bindings-typescript/src/sdk/client_api/query_id_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/query_id_type.ts @@ -4,67 +4,12 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; - -export type QueryId = { - id: number; -}; -let _cached_QueryId_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const QueryId = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_QueryId_type_value) return _cached_QueryId_type_value; - _cached_QueryId_type_value = __AlgebraicTypeValue.Product({ elements: [] }); - _cached_QueryId_type_value.value.elements.push({ - name: 'id', - algebraicType: __AlgebraicTypeValue.U32, - }); - return _cached_QueryId_type_value; - }, - - serialize(writer: __BinaryWriter, value: QueryId): void { - __AlgebraicTypeValue.serializeValue( - writer, - QueryId.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): QueryId { - return __AlgebraicTypeValue.deserializeValue( - reader, - QueryId.getTypeScriptAlgebraicType() - ); - }, -}; - -export default QueryId; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; + +export default __t.object('QueryId', { + id: __t.u32(), +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/query_update_type.ts b/crates/bindings-typescript/src/sdk/client_api/query_update_type.ts index 3523e9f5196..89338dc40ae 100644 --- a/crates/bindings-typescript/src/sdk/client_api/query_update_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/query_update_type.ts @@ -4,79 +4,18 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { BsatnRowList } from './bsatn_row_list_type'; -// Mark import as potentially unused -declare type __keep_BsatnRowList = BsatnRowList; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import BsatnRowList from './bsatn_row_list_type'; -export type QueryUpdate = { - deletes: BsatnRowList; - inserts: BsatnRowList; -}; -let _cached_QueryUpdate_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const QueryUpdate = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_QueryUpdate_type_value) return _cached_QueryUpdate_type_value; - _cached_QueryUpdate_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_QueryUpdate_type_value.value.elements.push( - { - name: 'deletes', - algebraicType: BsatnRowList.getTypeScriptAlgebraicType(), - }, - { - name: 'inserts', - algebraicType: BsatnRowList.getTypeScriptAlgebraicType(), - } - ); - return _cached_QueryUpdate_type_value; +export default __t.object('QueryUpdate', { + get deletes() { + return BsatnRowList; }, - - serialize(writer: __BinaryWriter, value: QueryUpdate): void { - __AlgebraicTypeValue.serializeValue( - writer, - QueryUpdate.getTypeScriptAlgebraicType(), - value - ); + get inserts() { + return BsatnRowList; }, - - deserialize(reader: __BinaryReader): QueryUpdate { - return __AlgebraicTypeValue.deserializeValue( - reader, - QueryUpdate.getTypeScriptAlgebraicType() - ); - }, -}; - -export default QueryUpdate; +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/reducer_call_info_type.ts b/crates/bindings-typescript/src/sdk/client_api/reducer_call_info_type.ts index ce37a59a355..8df1255dd45 100644 --- a/crates/bindings-typescript/src/sdk/client_api/reducer_call_info_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/reducer_call_info_type.ts @@ -4,78 +4,15 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; -export type ReducerCallInfo = { - reducerName: string; - reducerId: number; - args: Uint8Array; - requestId: number; -}; -let _cached_ReducerCallInfo_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const ReducerCallInfo = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_ReducerCallInfo_type_value) - return _cached_ReducerCallInfo_type_value; - _cached_ReducerCallInfo_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_ReducerCallInfo_type_value.value.elements.push( - { name: 'reducerName', algebraicType: __AlgebraicTypeValue.String }, - { name: 'reducerId', algebraicType: __AlgebraicTypeValue.U32 }, - { - name: 'args', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.U8), - }, - { name: 'requestId', algebraicType: __AlgebraicTypeValue.U32 } - ); - return _cached_ReducerCallInfo_type_value; - }, - - serialize(writer: __BinaryWriter, value: ReducerCallInfo): void { - __AlgebraicTypeValue.serializeValue( - writer, - ReducerCallInfo.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): ReducerCallInfo { - return __AlgebraicTypeValue.deserializeValue( - reader, - ReducerCallInfo.getTypeScriptAlgebraicType() - ); - }, -}; - -export default ReducerCallInfo; +export default __t.object('ReducerCallInfo', { + reducerName: __t.string(), + reducerId: __t.u32(), + args: __t.byteArray(), + requestId: __t.u32(), +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/row_size_hint_type.ts b/crates/bindings-typescript/src/sdk/client_api/row_size_hint_type.ts index 345dbeefd25..112417b2ac3 100644 --- a/crates/bindings-typescript/src/sdk/client_api/row_size_hint_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/row_size_hint_type.ts @@ -4,82 +4,16 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import * as RowSizeHintVariants from './row_size_hint_variants'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; // The tagged union or sum type for the algebraic type `RowSizeHint`. -export type RowSizeHint = - | RowSizeHintVariants.FixedSize - | RowSizeHintVariants.RowOffsets; - -let _cached_RowSizeHint_type_value: __AlgebraicTypeType | null = null; - -// A value with helper functions to construct the type. -export const RowSizeHint = { - // Helper functions for constructing each variant of the tagged union. - // ``` - // const foo = Foo.A(42); - // assert!(foo.tag === "A"); - // assert!(foo.value === 42); - // ``` - FixedSize: (value: number): RowSizeHintVariants.FixedSize => ({ - tag: 'FixedSize', - value, - }), - RowOffsets: (value: bigint[]): RowSizeHintVariants.RowOffsets => ({ - tag: 'RowOffsets', - value, - }), - - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_RowSizeHint_type_value) return _cached_RowSizeHint_type_value; - _cached_RowSizeHint_type_value = __AlgebraicTypeValue.Sum({ variants: [] }); - _cached_RowSizeHint_type_value.value.variants.push( - { name: 'FixedSize', algebraicType: __AlgebraicTypeValue.U16 }, - { - name: 'RowOffsets', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.U64), - } - ); - return _cached_RowSizeHint_type_value; - }, - - serialize(writer: __BinaryWriter, value: RowSizeHint): void { - __AlgebraicTypeValue.serializeValue( - writer, - RowSizeHint.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): RowSizeHint { - return __AlgebraicTypeValue.deserializeValue( - reader, - RowSizeHint.getTypeScriptAlgebraicType() - ); - }, -}; +const RowSizeHint = __t.enum('RowSizeHint', { + FixedSize: __t.u16(), + RowOffsets: __t.array(__t.u64()), +}); export default RowSizeHint; diff --git a/crates/bindings-typescript/src/sdk/client_api/row_size_hint_variants.ts b/crates/bindings-typescript/src/sdk/client_api/row_size_hint_variants.ts deleted file mode 100644 index 48f9ef80f43..00000000000 --- a/crates/bindings-typescript/src/sdk/client_api/row_size_hint_variants.ts +++ /dev/null @@ -1,32 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -/* eslint-disable */ -/* tslint:disable */ -import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; - -export type FixedSize = { tag: 'FixedSize'; value: number }; -export type RowOffsets = { tag: 'RowOffsets'; value: bigint[] }; diff --git a/crates/bindings-typescript/src/sdk/client_api/server_message_type.ts b/crates/bindings-typescript/src/sdk/client_api/server_message_type.ts index 868a382da42..cd9e0e2ea23 100644 --- a/crates/bindings-typescript/src/sdk/client_api/server_message_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/server_message_type.ts @@ -4,208 +4,58 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { InitialSubscription } from './initial_subscription_type'; -// Mark import as potentially unused -declare type __keep_InitialSubscription = InitialSubscription; -import { TransactionUpdate } from './transaction_update_type'; -// Mark import as potentially unused -declare type __keep_TransactionUpdate = TransactionUpdate; -import { TransactionUpdateLight } from './transaction_update_light_type'; -// Mark import as potentially unused -declare type __keep_TransactionUpdateLight = TransactionUpdateLight; -import { IdentityToken } from './identity_token_type'; -// Mark import as potentially unused -declare type __keep_IdentityToken = IdentityToken; -import { OneOffQueryResponse } from './one_off_query_response_type'; -// Mark import as potentially unused -declare type __keep_OneOffQueryResponse = OneOffQueryResponse; -import { SubscribeApplied } from './subscribe_applied_type'; -// Mark import as potentially unused -declare type __keep_SubscribeApplied = SubscribeApplied; -import { UnsubscribeApplied } from './unsubscribe_applied_type'; -// Mark import as potentially unused -declare type __keep_UnsubscribeApplied = UnsubscribeApplied; -import { SubscriptionError } from './subscription_error_type'; -// Mark import as potentially unused -declare type __keep_SubscriptionError = SubscriptionError; -import { SubscribeMultiApplied } from './subscribe_multi_applied_type'; -// Mark import as potentially unused -declare type __keep_SubscribeMultiApplied = SubscribeMultiApplied; -import { UnsubscribeMultiApplied } from './unsubscribe_multi_applied_type'; -// Mark import as potentially unused -declare type __keep_UnsubscribeMultiApplied = UnsubscribeMultiApplied; - -import * as ServerMessageVariants from './server_message_variants'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import InitialSubscription from './initial_subscription_type'; +import TransactionUpdate from './transaction_update_type'; +import TransactionUpdateLight from './transaction_update_light_type'; +import IdentityToken from './identity_token_type'; +import OneOffQueryResponse from './one_off_query_response_type'; +import SubscribeApplied from './subscribe_applied_type'; +import UnsubscribeApplied from './unsubscribe_applied_type'; +import SubscriptionError from './subscription_error_type'; +import SubscribeMultiApplied from './subscribe_multi_applied_type'; +import UnsubscribeMultiApplied from './unsubscribe_multi_applied_type'; +import ProcedureResult from './procedure_result_type'; // The tagged union or sum type for the algebraic type `ServerMessage`. -export type ServerMessage = - | ServerMessageVariants.InitialSubscription - | ServerMessageVariants.TransactionUpdate - | ServerMessageVariants.TransactionUpdateLight - | ServerMessageVariants.IdentityToken - | ServerMessageVariants.OneOffQueryResponse - | ServerMessageVariants.SubscribeApplied - | ServerMessageVariants.UnsubscribeApplied - | ServerMessageVariants.SubscriptionError - | ServerMessageVariants.SubscribeMultiApplied - | ServerMessageVariants.UnsubscribeMultiApplied; - -let _cached_ServerMessage_type_value: __AlgebraicTypeType | null = null; - -// A value with helper functions to construct the type. -export const ServerMessage = { - // Helper functions for constructing each variant of the tagged union. - // ``` - // const foo = Foo.A(42); - // assert!(foo.tag === "A"); - // assert!(foo.value === 42); - // ``` - InitialSubscription: ( - value: InitialSubscription - ): ServerMessageVariants.InitialSubscription => ({ - tag: 'InitialSubscription', - value, - }), - TransactionUpdate: ( - value: TransactionUpdate - ): ServerMessageVariants.TransactionUpdate => ({ - tag: 'TransactionUpdate', - value, - }), - TransactionUpdateLight: ( - value: TransactionUpdateLight - ): ServerMessageVariants.TransactionUpdateLight => ({ - tag: 'TransactionUpdateLight', - value, - }), - IdentityToken: ( - value: IdentityToken - ): ServerMessageVariants.IdentityToken => ({ tag: 'IdentityToken', value }), - OneOffQueryResponse: ( - value: OneOffQueryResponse - ): ServerMessageVariants.OneOffQueryResponse => ({ - tag: 'OneOffQueryResponse', - value, - }), - SubscribeApplied: ( - value: SubscribeApplied - ): ServerMessageVariants.SubscribeApplied => ({ - tag: 'SubscribeApplied', - value, - }), - UnsubscribeApplied: ( - value: UnsubscribeApplied - ): ServerMessageVariants.UnsubscribeApplied => ({ - tag: 'UnsubscribeApplied', - value, - }), - SubscriptionError: ( - value: SubscriptionError - ): ServerMessageVariants.SubscriptionError => ({ - tag: 'SubscriptionError', - value, - }), - SubscribeMultiApplied: ( - value: SubscribeMultiApplied - ): ServerMessageVariants.SubscribeMultiApplied => ({ - tag: 'SubscribeMultiApplied', - value, - }), - UnsubscribeMultiApplied: ( - value: UnsubscribeMultiApplied - ): ServerMessageVariants.UnsubscribeMultiApplied => ({ - tag: 'UnsubscribeMultiApplied', - value, - }), - - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_ServerMessage_type_value) - return _cached_ServerMessage_type_value; - _cached_ServerMessage_type_value = __AlgebraicTypeValue.Sum({ - variants: [], - }); - _cached_ServerMessage_type_value.value.variants.push( - { - name: 'InitialSubscription', - algebraicType: InitialSubscription.getTypeScriptAlgebraicType(), - }, - { - name: 'TransactionUpdate', - algebraicType: TransactionUpdate.getTypeScriptAlgebraicType(), - }, - { - name: 'TransactionUpdateLight', - algebraicType: TransactionUpdateLight.getTypeScriptAlgebraicType(), - }, - { - name: 'IdentityToken', - algebraicType: IdentityToken.getTypeScriptAlgebraicType(), - }, - { - name: 'OneOffQueryResponse', - algebraicType: OneOffQueryResponse.getTypeScriptAlgebraicType(), - }, - { - name: 'SubscribeApplied', - algebraicType: SubscribeApplied.getTypeScriptAlgebraicType(), - }, - { - name: 'UnsubscribeApplied', - algebraicType: UnsubscribeApplied.getTypeScriptAlgebraicType(), - }, - { - name: 'SubscriptionError', - algebraicType: SubscriptionError.getTypeScriptAlgebraicType(), - }, - { - name: 'SubscribeMultiApplied', - algebraicType: SubscribeMultiApplied.getTypeScriptAlgebraicType(), - }, - { - name: 'UnsubscribeMultiApplied', - algebraicType: UnsubscribeMultiApplied.getTypeScriptAlgebraicType(), - } - ); - return _cached_ServerMessage_type_value; +const ServerMessage = __t.enum('ServerMessage', { + get InitialSubscription() { + return InitialSubscription; }, - - serialize(writer: __BinaryWriter, value: ServerMessage): void { - __AlgebraicTypeValue.serializeValue( - writer, - ServerMessage.getTypeScriptAlgebraicType(), - value - ); + get TransactionUpdate() { + return TransactionUpdate; }, - - deserialize(reader: __BinaryReader): ServerMessage { - return __AlgebraicTypeValue.deserializeValue( - reader, - ServerMessage.getTypeScriptAlgebraicType() - ); + get TransactionUpdateLight() { + return TransactionUpdateLight; + }, + get IdentityToken() { + return IdentityToken; + }, + get OneOffQueryResponse() { + return OneOffQueryResponse; + }, + get SubscribeApplied() { + return SubscribeApplied; + }, + get UnsubscribeApplied() { + return UnsubscribeApplied; + }, + get SubscriptionError() { + return SubscriptionError; + }, + get SubscribeMultiApplied() { + return SubscribeMultiApplied; + }, + get UnsubscribeMultiApplied() { + return UnsubscribeMultiApplied; + }, + get ProcedureResult() { + return ProcedureResult; }, -}; +}); export default ServerMessage; diff --git a/crates/bindings-typescript/src/sdk/client_api/server_message_variants.ts b/crates/bindings-typescript/src/sdk/client_api/server_message_variants.ts deleted file mode 100644 index 530882d718b..00000000000 --- a/crates/bindings-typescript/src/sdk/client_api/server_message_variants.ts +++ /dev/null @@ -1,97 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -/* eslint-disable */ -/* tslint:disable */ -import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { InitialSubscription as InitialSubscriptionType } from './initial_subscription_type'; -// Mark import as potentially unused -declare type __keep_InitialSubscriptionType = InitialSubscriptionType; -import { TransactionUpdate as TransactionUpdateType } from './transaction_update_type'; -// Mark import as potentially unused -declare type __keep_TransactionUpdateType = TransactionUpdateType; -import { TransactionUpdateLight as TransactionUpdateLightType } from './transaction_update_light_type'; -// Mark import as potentially unused -declare type __keep_TransactionUpdateLightType = TransactionUpdateLightType; -import { IdentityToken as IdentityTokenType } from './identity_token_type'; -// Mark import as potentially unused -declare type __keep_IdentityTokenType = IdentityTokenType; -import { OneOffQueryResponse as OneOffQueryResponseType } from './one_off_query_response_type'; -// Mark import as potentially unused -declare type __keep_OneOffQueryResponseType = OneOffQueryResponseType; -import { SubscribeApplied as SubscribeAppliedType } from './subscribe_applied_type'; -// Mark import as potentially unused -declare type __keep_SubscribeAppliedType = SubscribeAppliedType; -import { UnsubscribeApplied as UnsubscribeAppliedType } from './unsubscribe_applied_type'; -// Mark import as potentially unused -declare type __keep_UnsubscribeAppliedType = UnsubscribeAppliedType; -import { SubscriptionError as SubscriptionErrorType } from './subscription_error_type'; -// Mark import as potentially unused -declare type __keep_SubscriptionErrorType = SubscriptionErrorType; -import { SubscribeMultiApplied as SubscribeMultiAppliedType } from './subscribe_multi_applied_type'; -// Mark import as potentially unused -declare type __keep_SubscribeMultiAppliedType = SubscribeMultiAppliedType; -import { UnsubscribeMultiApplied as UnsubscribeMultiAppliedType } from './unsubscribe_multi_applied_type'; -// Mark import as potentially unused -declare type __keep_UnsubscribeMultiAppliedType = UnsubscribeMultiAppliedType; - -export type InitialSubscription = { - tag: 'InitialSubscription'; - value: InitialSubscriptionType; -}; -export type TransactionUpdate = { - tag: 'TransactionUpdate'; - value: TransactionUpdateType; -}; -export type TransactionUpdateLight = { - tag: 'TransactionUpdateLight'; - value: TransactionUpdateLightType; -}; -export type IdentityToken = { tag: 'IdentityToken'; value: IdentityTokenType }; -export type OneOffQueryResponse = { - tag: 'OneOffQueryResponse'; - value: OneOffQueryResponseType; -}; -export type SubscribeApplied = { - tag: 'SubscribeApplied'; - value: SubscribeAppliedType; -}; -export type UnsubscribeApplied = { - tag: 'UnsubscribeApplied'; - value: UnsubscribeAppliedType; -}; -export type SubscriptionError = { - tag: 'SubscriptionError'; - value: SubscriptionErrorType; -}; -export type SubscribeMultiApplied = { - tag: 'SubscribeMultiApplied'; - value: SubscribeMultiAppliedType; -}; -export type UnsubscribeMultiApplied = { - tag: 'UnsubscribeMultiApplied'; - value: UnsubscribeMultiAppliedType; -}; diff --git a/crates/bindings-typescript/src/sdk/client_api/subscribe_applied_type.ts b/crates/bindings-typescript/src/sdk/client_api/subscribe_applied_type.ts index 637b77472ea..58bfe91169d 100644 --- a/crates/bindings-typescript/src/sdk/client_api/subscribe_applied_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/subscribe_applied_type.ts @@ -4,87 +4,21 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { QueryId } from './query_id_type'; -// Mark import as potentially unused -declare type __keep_QueryId = QueryId; -import { SubscribeRows } from './subscribe_rows_type'; -// Mark import as potentially unused -declare type __keep_SubscribeRows = SubscribeRows; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import QueryId from './query_id_type'; +import SubscribeRows from './subscribe_rows_type'; -export type SubscribeApplied = { - requestId: number; - totalHostExecutionDurationMicros: bigint; - queryId: QueryId; - rows: SubscribeRows; -}; -let _cached_SubscribeApplied_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const SubscribeApplied = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_SubscribeApplied_type_value) - return _cached_SubscribeApplied_type_value; - _cached_SubscribeApplied_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_SubscribeApplied_type_value.value.elements.push( - { name: 'requestId', algebraicType: __AlgebraicTypeValue.U32 }, - { - name: 'totalHostExecutionDurationMicros', - algebraicType: __AlgebraicTypeValue.U64, - }, - { name: 'queryId', algebraicType: QueryId.getTypeScriptAlgebraicType() }, - { - name: 'rows', - algebraicType: SubscribeRows.getTypeScriptAlgebraicType(), - } - ); - return _cached_SubscribeApplied_type_value; +export default __t.object('SubscribeApplied', { + requestId: __t.u32(), + totalHostExecutionDurationMicros: __t.u64(), + get queryId() { + return QueryId; }, - - serialize(writer: __BinaryWriter, value: SubscribeApplied): void { - __AlgebraicTypeValue.serializeValue( - writer, - SubscribeApplied.getTypeScriptAlgebraicType(), - value - ); + get rows() { + return SubscribeRows; }, - - deserialize(reader: __BinaryReader): SubscribeApplied { - return __AlgebraicTypeValue.deserializeValue( - reader, - SubscribeApplied.getTypeScriptAlgebraicType() - ); - }, -}; - -export default SubscribeApplied; +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/subscribe_multi_applied_type.ts b/crates/bindings-typescript/src/sdk/client_api/subscribe_multi_applied_type.ts index c068eada2a5..dedef69e1b5 100644 --- a/crates/bindings-typescript/src/sdk/client_api/subscribe_multi_applied_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/subscribe_multi_applied_type.ts @@ -4,87 +4,21 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { QueryId } from './query_id_type'; -// Mark import as potentially unused -declare type __keep_QueryId = QueryId; -import { DatabaseUpdate } from './database_update_type'; -// Mark import as potentially unused -declare type __keep_DatabaseUpdate = DatabaseUpdate; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import QueryId from './query_id_type'; +import DatabaseUpdate from './database_update_type'; -export type SubscribeMultiApplied = { - requestId: number; - totalHostExecutionDurationMicros: bigint; - queryId: QueryId; - update: DatabaseUpdate; -}; -let _cached_SubscribeMultiApplied_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const SubscribeMultiApplied = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_SubscribeMultiApplied_type_value) - return _cached_SubscribeMultiApplied_type_value; - _cached_SubscribeMultiApplied_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_SubscribeMultiApplied_type_value.value.elements.push( - { name: 'requestId', algebraicType: __AlgebraicTypeValue.U32 }, - { - name: 'totalHostExecutionDurationMicros', - algebraicType: __AlgebraicTypeValue.U64, - }, - { name: 'queryId', algebraicType: QueryId.getTypeScriptAlgebraicType() }, - { - name: 'update', - algebraicType: DatabaseUpdate.getTypeScriptAlgebraicType(), - } - ); - return _cached_SubscribeMultiApplied_type_value; +export default __t.object('SubscribeMultiApplied', { + requestId: __t.u32(), + totalHostExecutionDurationMicros: __t.u64(), + get queryId() { + return QueryId; }, - - serialize(writer: __BinaryWriter, value: SubscribeMultiApplied): void { - __AlgebraicTypeValue.serializeValue( - writer, - SubscribeMultiApplied.getTypeScriptAlgebraicType(), - value - ); + get update() { + return DatabaseUpdate; }, - - deserialize(reader: __BinaryReader): SubscribeMultiApplied { - return __AlgebraicTypeValue.deserializeValue( - reader, - SubscribeMultiApplied.getTypeScriptAlgebraicType() - ); - }, -}; - -export default SubscribeMultiApplied; +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/subscribe_multi_type.ts b/crates/bindings-typescript/src/sdk/client_api/subscribe_multi_type.ts index 34aad33a9a6..f57c6cdc3ba 100644 --- a/crates/bindings-typescript/src/sdk/client_api/subscribe_multi_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/subscribe_multi_type.ts @@ -4,79 +4,17 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { QueryId } from './query_id_type'; -// Mark import as potentially unused -declare type __keep_QueryId = QueryId; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import QueryId from './query_id_type'; -export type SubscribeMulti = { - queryStrings: string[]; - requestId: number; - queryId: QueryId; -}; -let _cached_SubscribeMulti_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const SubscribeMulti = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_SubscribeMulti_type_value) - return _cached_SubscribeMulti_type_value; - _cached_SubscribeMulti_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_SubscribeMulti_type_value.value.elements.push( - { - name: 'queryStrings', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.String), - }, - { name: 'requestId', algebraicType: __AlgebraicTypeValue.U32 }, - { name: 'queryId', algebraicType: QueryId.getTypeScriptAlgebraicType() } - ); - return _cached_SubscribeMulti_type_value; - }, - - serialize(writer: __BinaryWriter, value: SubscribeMulti): void { - __AlgebraicTypeValue.serializeValue( - writer, - SubscribeMulti.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('SubscribeMulti', { + queryStrings: __t.array(__t.string()), + requestId: __t.u32(), + get queryId() { + return QueryId; }, - - deserialize(reader: __BinaryReader): SubscribeMulti { - return __AlgebraicTypeValue.deserializeValue( - reader, - SubscribeMulti.getTypeScriptAlgebraicType() - ); - }, -}; - -export default SubscribeMulti; +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/subscribe_rows_type.ts b/crates/bindings-typescript/src/sdk/client_api/subscribe_rows_type.ts index ceb20dff46a..9bb71d3e9c8 100644 --- a/crates/bindings-typescript/src/sdk/client_api/subscribe_rows_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/subscribe_rows_type.ts @@ -4,79 +4,17 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { TableUpdate } from './table_update_type'; -// Mark import as potentially unused -declare type __keep_TableUpdate = TableUpdate; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import TableUpdate from './table_update_type'; -export type SubscribeRows = { - tableId: number; - tableName: string; - tableRows: TableUpdate; -}; -let _cached_SubscribeRows_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const SubscribeRows = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_SubscribeRows_type_value) - return _cached_SubscribeRows_type_value; - _cached_SubscribeRows_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_SubscribeRows_type_value.value.elements.push( - { name: 'tableId', algebraicType: __AlgebraicTypeValue.U32 }, - { name: 'tableName', algebraicType: __AlgebraicTypeValue.String }, - { - name: 'tableRows', - algebraicType: TableUpdate.getTypeScriptAlgebraicType(), - } - ); - return _cached_SubscribeRows_type_value; - }, - - serialize(writer: __BinaryWriter, value: SubscribeRows): void { - __AlgebraicTypeValue.serializeValue( - writer, - SubscribeRows.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('SubscribeRows', { + tableId: __t.u32(), + tableName: __t.string(), + get tableRows() { + return TableUpdate; }, - - deserialize(reader: __BinaryReader): SubscribeRows { - return __AlgebraicTypeValue.deserializeValue( - reader, - SubscribeRows.getTypeScriptAlgebraicType() - ); - }, -}; - -export default SubscribeRows; +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/subscribe_single_type.ts b/crates/bindings-typescript/src/sdk/client_api/subscribe_single_type.ts index cb72b19fe54..24f95da4ead 100644 --- a/crates/bindings-typescript/src/sdk/client_api/subscribe_single_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/subscribe_single_type.ts @@ -4,76 +4,17 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { QueryId } from './query_id_type'; -// Mark import as potentially unused -declare type __keep_QueryId = QueryId; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import QueryId from './query_id_type'; -export type SubscribeSingle = { - query: string; - requestId: number; - queryId: QueryId; -}; -let _cached_SubscribeSingle_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const SubscribeSingle = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_SubscribeSingle_type_value) - return _cached_SubscribeSingle_type_value; - _cached_SubscribeSingle_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_SubscribeSingle_type_value.value.elements.push( - { name: 'query', algebraicType: __AlgebraicTypeValue.String }, - { name: 'requestId', algebraicType: __AlgebraicTypeValue.U32 }, - { name: 'queryId', algebraicType: QueryId.getTypeScriptAlgebraicType() } - ); - return _cached_SubscribeSingle_type_value; - }, - - serialize(writer: __BinaryWriter, value: SubscribeSingle): void { - __AlgebraicTypeValue.serializeValue( - writer, - SubscribeSingle.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('SubscribeSingle', { + query: __t.string(), + requestId: __t.u32(), + get queryId() { + return QueryId; }, - - deserialize(reader: __BinaryReader): SubscribeSingle { - return __AlgebraicTypeValue.deserializeValue( - reader, - SubscribeSingle.getTypeScriptAlgebraicType() - ); - }, -}; - -export default SubscribeSingle; +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/subscribe_type.ts b/crates/bindings-typescript/src/sdk/client_api/subscribe_type.ts index da3b45b269d..12dd03b70e9 100644 --- a/crates/bindings-typescript/src/sdk/client_api/subscribe_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/subscribe_type.ts @@ -4,73 +4,13 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; -export type Subscribe = { - queryStrings: string[]; - requestId: number; -}; -let _cached_Subscribe_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const Subscribe = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_Subscribe_type_value) return _cached_Subscribe_type_value; - _cached_Subscribe_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_Subscribe_type_value.value.elements.push( - { - name: 'queryStrings', - algebraicType: __AlgebraicTypeValue.Array(__AlgebraicTypeValue.String), - }, - { name: 'requestId', algebraicType: __AlgebraicTypeValue.U32 } - ); - return _cached_Subscribe_type_value; - }, - - serialize(writer: __BinaryWriter, value: Subscribe): void { - __AlgebraicTypeValue.serializeValue( - writer, - Subscribe.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): Subscribe { - return __AlgebraicTypeValue.deserializeValue( - reader, - Subscribe.getTypeScriptAlgebraicType() - ); - }, -}; - -export default Subscribe; +export default __t.object('Subscribe', { + queryStrings: __t.array(__t.string()), + requestId: __t.u32(), +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/subscription_error_type.ts b/crates/bindings-typescript/src/sdk/client_api/subscription_error_type.ts index 2c1d3325dfd..6e6c706d762 100644 --- a/crates/bindings-typescript/src/sdk/client_api/subscription_error_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/subscription_error_type.ts @@ -4,95 +4,16 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; -export type SubscriptionError = { - totalHostExecutionDurationMicros: bigint; - requestId: number | undefined; - queryId: number | undefined; - tableId: number | undefined; - error: string; -}; -let _cached_SubscriptionError_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const SubscriptionError = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_SubscriptionError_type_value) - return _cached_SubscriptionError_type_value; - _cached_SubscriptionError_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_SubscriptionError_type_value.value.elements.push( - { - name: 'totalHostExecutionDurationMicros', - algebraicType: __AlgebraicTypeValue.U64, - }, - { - name: 'requestId', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.U32 - ), - }, - { - name: 'queryId', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.U32 - ), - }, - { - name: 'tableId', - algebraicType: __AlgebraicTypeValue.createOptionType( - __AlgebraicTypeValue.U32 - ), - }, - { name: 'error', algebraicType: __AlgebraicTypeValue.String } - ); - return _cached_SubscriptionError_type_value; - }, - - serialize(writer: __BinaryWriter, value: SubscriptionError): void { - __AlgebraicTypeValue.serializeValue( - writer, - SubscriptionError.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): SubscriptionError { - return __AlgebraicTypeValue.deserializeValue( - reader, - SubscriptionError.getTypeScriptAlgebraicType() - ); - }, -}; - -export default SubscriptionError; +export default __t.object('SubscriptionError', { + totalHostExecutionDurationMicros: __t.u64(), + requestId: __t.option(__t.u32()), + queryId: __t.option(__t.u32()), + tableId: __t.option(__t.u32()), + error: __t.string(), +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/table_update_type.ts b/crates/bindings-typescript/src/sdk/client_api/table_update_type.ts index 1c195641522..3af80ec50ce 100644 --- a/crates/bindings-typescript/src/sdk/client_api/table_update_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/table_update_type.ts @@ -4,82 +4,18 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { CompressableQueryUpdate } from './compressable_query_update_type'; -// Mark import as potentially unused -declare type __keep_CompressableQueryUpdate = CompressableQueryUpdate; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import CompressableQueryUpdate from './compressable_query_update_type'; -export type TableUpdate = { - tableId: number; - tableName: string; - numRows: bigint; - updates: CompressableQueryUpdate[]; -}; -let _cached_TableUpdate_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const TableUpdate = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_TableUpdate_type_value) return _cached_TableUpdate_type_value; - _cached_TableUpdate_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_TableUpdate_type_value.value.elements.push( - { name: 'tableId', algebraicType: __AlgebraicTypeValue.U32 }, - { name: 'tableName', algebraicType: __AlgebraicTypeValue.String }, - { name: 'numRows', algebraicType: __AlgebraicTypeValue.U64 }, - { - name: 'updates', - algebraicType: __AlgebraicTypeValue.Array( - CompressableQueryUpdate.getTypeScriptAlgebraicType() - ), - } - ); - return _cached_TableUpdate_type_value; - }, - - serialize(writer: __BinaryWriter, value: TableUpdate): void { - __AlgebraicTypeValue.serializeValue( - writer, - TableUpdate.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('TableUpdate', { + tableId: __t.u32(), + tableName: __t.string(), + numRows: __t.u64(), + get updates() { + return __t.array(CompressableQueryUpdate); }, - - deserialize(reader: __BinaryReader): TableUpdate { - return __AlgebraicTypeValue.deserializeValue( - reader, - TableUpdate.getTypeScriptAlgebraicType() - ); - }, -}; - -export default TableUpdate; +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/transaction_update_light_type.ts b/crates/bindings-typescript/src/sdk/client_api/transaction_update_light_type.ts index 24765e2b063..749059e6301 100644 --- a/crates/bindings-typescript/src/sdk/client_api/transaction_update_light_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/transaction_update_light_type.ts @@ -4,78 +4,16 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { DatabaseUpdate } from './database_update_type'; -// Mark import as potentially unused -declare type __keep_DatabaseUpdate = DatabaseUpdate; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import DatabaseUpdate from './database_update_type'; -export type TransactionUpdateLight = { - requestId: number; - update: DatabaseUpdate; -}; -let _cached_TransactionUpdateLight_type_value: __AlgebraicTypeType | null = - null; - -/** - * An object for generated helper functions. - */ -export const TransactionUpdateLight = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_TransactionUpdateLight_type_value) - return _cached_TransactionUpdateLight_type_value; - _cached_TransactionUpdateLight_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_TransactionUpdateLight_type_value.value.elements.push( - { name: 'requestId', algebraicType: __AlgebraicTypeValue.U32 }, - { - name: 'update', - algebraicType: DatabaseUpdate.getTypeScriptAlgebraicType(), - } - ); - return _cached_TransactionUpdateLight_type_value; - }, - - serialize(writer: __BinaryWriter, value: TransactionUpdateLight): void { - __AlgebraicTypeValue.serializeValue( - writer, - TransactionUpdateLight.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('TransactionUpdateLight', { + requestId: __t.u32(), + get update() { + return DatabaseUpdate; }, - - deserialize(reader: __BinaryReader): TransactionUpdateLight { - return __AlgebraicTypeValue.deserializeValue( - reader, - TransactionUpdateLight.getTypeScriptAlgebraicType() - ); - }, -}; - -export default TransactionUpdateLight; +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/transaction_update_type.ts b/crates/bindings-typescript/src/sdk/client_api/transaction_update_type.ts index 8e8c08c5206..b95ae7cf008 100644 --- a/crates/bindings-typescript/src/sdk/client_api/transaction_update_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/transaction_update_type.ts @@ -4,111 +4,27 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { UpdateStatus } from './update_status_type'; -// Mark import as potentially unused -declare type __keep_UpdateStatus = UpdateStatus; -import { ReducerCallInfo } from './reducer_call_info_type'; -// Mark import as potentially unused -declare type __keep_ReducerCallInfo = ReducerCallInfo; -import { EnergyQuanta } from './energy_quanta_type'; -// Mark import as potentially unused -declare type __keep_EnergyQuanta = EnergyQuanta; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import UpdateStatus from './update_status_type'; +import ReducerCallInfo from './reducer_call_info_type'; +import EnergyQuanta from './energy_quanta_type'; -export type TransactionUpdate = { - status: UpdateStatus; - timestamp: __Timestamp; - callerIdentity: __Identity; - callerConnectionId: __ConnectionId; - reducerCall: ReducerCallInfo; - energyQuantaUsed: EnergyQuanta; - totalHostExecutionDuration: __TimeDuration; -}; -let _cached_TransactionUpdate_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const TransactionUpdate = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_TransactionUpdate_type_value) - return _cached_TransactionUpdate_type_value; - _cached_TransactionUpdate_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_TransactionUpdate_type_value.value.elements.push( - { - name: 'status', - algebraicType: UpdateStatus.getTypeScriptAlgebraicType(), - }, - { - name: 'timestamp', - algebraicType: __AlgebraicTypeValue.createTimestampType(), - }, - { - name: 'callerIdentity', - algebraicType: __AlgebraicTypeValue.createIdentityType(), - }, - { - name: 'callerConnectionId', - algebraicType: __AlgebraicTypeValue.createConnectionIdType(), - }, - { - name: 'reducerCall', - algebraicType: ReducerCallInfo.getTypeScriptAlgebraicType(), - }, - { - name: 'energyQuantaUsed', - algebraicType: EnergyQuanta.getTypeScriptAlgebraicType(), - }, - { - name: 'totalHostExecutionDuration', - algebraicType: __AlgebraicTypeValue.createTimeDurationType(), - } - ); - return _cached_TransactionUpdate_type_value; +export default __t.object('TransactionUpdate', { + get status() { + return UpdateStatus; }, - - serialize(writer: __BinaryWriter, value: TransactionUpdate): void { - __AlgebraicTypeValue.serializeValue( - writer, - TransactionUpdate.getTypeScriptAlgebraicType(), - value - ); + timestamp: __t.timestamp(), + callerIdentity: __t.identity(), + callerConnectionId: __t.connectionId(), + get reducerCall() { + return ReducerCallInfo; }, - - deserialize(reader: __BinaryReader): TransactionUpdate { - return __AlgebraicTypeValue.deserializeValue( - reader, - TransactionUpdate.getTypeScriptAlgebraicType() - ); + get energyQuantaUsed() { + return EnergyQuanta; }, -}; - -export default TransactionUpdate; + totalHostExecutionDuration: __t.timeDuration(), +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/unsubscribe_applied_type.ts b/crates/bindings-typescript/src/sdk/client_api/unsubscribe_applied_type.ts index e40f9d5ecf6..bf921d16cc0 100644 --- a/crates/bindings-typescript/src/sdk/client_api/unsubscribe_applied_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/unsubscribe_applied_type.ts @@ -4,87 +4,21 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { QueryId } from './query_id_type'; -// Mark import as potentially unused -declare type __keep_QueryId = QueryId; -import { SubscribeRows } from './subscribe_rows_type'; -// Mark import as potentially unused -declare type __keep_SubscribeRows = SubscribeRows; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import QueryId from './query_id_type'; +import SubscribeRows from './subscribe_rows_type'; -export type UnsubscribeApplied = { - requestId: number; - totalHostExecutionDurationMicros: bigint; - queryId: QueryId; - rows: SubscribeRows; -}; -let _cached_UnsubscribeApplied_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const UnsubscribeApplied = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_UnsubscribeApplied_type_value) - return _cached_UnsubscribeApplied_type_value; - _cached_UnsubscribeApplied_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_UnsubscribeApplied_type_value.value.elements.push( - { name: 'requestId', algebraicType: __AlgebraicTypeValue.U32 }, - { - name: 'totalHostExecutionDurationMicros', - algebraicType: __AlgebraicTypeValue.U64, - }, - { name: 'queryId', algebraicType: QueryId.getTypeScriptAlgebraicType() }, - { - name: 'rows', - algebraicType: SubscribeRows.getTypeScriptAlgebraicType(), - } - ); - return _cached_UnsubscribeApplied_type_value; +export default __t.object('UnsubscribeApplied', { + requestId: __t.u32(), + totalHostExecutionDurationMicros: __t.u64(), + get queryId() { + return QueryId; }, - - serialize(writer: __BinaryWriter, value: UnsubscribeApplied): void { - __AlgebraicTypeValue.serializeValue( - writer, - UnsubscribeApplied.getTypeScriptAlgebraicType(), - value - ); + get rows() { + return SubscribeRows; }, - - deserialize(reader: __BinaryReader): UnsubscribeApplied { - return __AlgebraicTypeValue.deserializeValue( - reader, - UnsubscribeApplied.getTypeScriptAlgebraicType() - ); - }, -}; - -export default UnsubscribeApplied; +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/unsubscribe_multi_applied_type.ts b/crates/bindings-typescript/src/sdk/client_api/unsubscribe_multi_applied_type.ts index d3cc7eba1f1..a7c4c54fcf6 100644 --- a/crates/bindings-typescript/src/sdk/client_api/unsubscribe_multi_applied_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/unsubscribe_multi_applied_type.ts @@ -4,88 +4,21 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { QueryId } from './query_id_type'; -// Mark import as potentially unused -declare type __keep_QueryId = QueryId; -import { DatabaseUpdate } from './database_update_type'; -// Mark import as potentially unused -declare type __keep_DatabaseUpdate = DatabaseUpdate; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import QueryId from './query_id_type'; +import DatabaseUpdate from './database_update_type'; -export type UnsubscribeMultiApplied = { - requestId: number; - totalHostExecutionDurationMicros: bigint; - queryId: QueryId; - update: DatabaseUpdate; -}; -let _cached_UnsubscribeMultiApplied_type_value: __AlgebraicTypeType | null = - null; - -/** - * An object for generated helper functions. - */ -export const UnsubscribeMultiApplied = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_UnsubscribeMultiApplied_type_value) - return _cached_UnsubscribeMultiApplied_type_value; - _cached_UnsubscribeMultiApplied_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_UnsubscribeMultiApplied_type_value.value.elements.push( - { name: 'requestId', algebraicType: __AlgebraicTypeValue.U32 }, - { - name: 'totalHostExecutionDurationMicros', - algebraicType: __AlgebraicTypeValue.U64, - }, - { name: 'queryId', algebraicType: QueryId.getTypeScriptAlgebraicType() }, - { - name: 'update', - algebraicType: DatabaseUpdate.getTypeScriptAlgebraicType(), - } - ); - return _cached_UnsubscribeMultiApplied_type_value; +export default __t.object('UnsubscribeMultiApplied', { + requestId: __t.u32(), + totalHostExecutionDurationMicros: __t.u64(), + get queryId() { + return QueryId; }, - - serialize(writer: __BinaryWriter, value: UnsubscribeMultiApplied): void { - __AlgebraicTypeValue.serializeValue( - writer, - UnsubscribeMultiApplied.getTypeScriptAlgebraicType(), - value - ); + get update() { + return DatabaseUpdate; }, - - deserialize(reader: __BinaryReader): UnsubscribeMultiApplied { - return __AlgebraicTypeValue.deserializeValue( - reader, - UnsubscribeMultiApplied.getTypeScriptAlgebraicType() - ); - }, -}; - -export default UnsubscribeMultiApplied; +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/unsubscribe_multi_type.ts b/crates/bindings-typescript/src/sdk/client_api/unsubscribe_multi_type.ts index 64279e511ff..e70eca30320 100644 --- a/crates/bindings-typescript/src/sdk/client_api/unsubscribe_multi_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/unsubscribe_multi_type.ts @@ -4,74 +4,16 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { QueryId } from './query_id_type'; -// Mark import as potentially unused -declare type __keep_QueryId = QueryId; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import QueryId from './query_id_type'; -export type UnsubscribeMulti = { - requestId: number; - queryId: QueryId; -}; -let _cached_UnsubscribeMulti_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const UnsubscribeMulti = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_UnsubscribeMulti_type_value) - return _cached_UnsubscribeMulti_type_value; - _cached_UnsubscribeMulti_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_UnsubscribeMulti_type_value.value.elements.push( - { name: 'requestId', algebraicType: __AlgebraicTypeValue.U32 }, - { name: 'queryId', algebraicType: QueryId.getTypeScriptAlgebraicType() } - ); - return _cached_UnsubscribeMulti_type_value; - }, - - serialize(writer: __BinaryWriter, value: UnsubscribeMulti): void { - __AlgebraicTypeValue.serializeValue( - writer, - UnsubscribeMulti.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('UnsubscribeMulti', { + requestId: __t.u32(), + get queryId() { + return QueryId; }, - - deserialize(reader: __BinaryReader): UnsubscribeMulti { - return __AlgebraicTypeValue.deserializeValue( - reader, - UnsubscribeMulti.getTypeScriptAlgebraicType() - ); - }, -}; - -export default UnsubscribeMulti; +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/unsubscribe_type.ts b/crates/bindings-typescript/src/sdk/client_api/unsubscribe_type.ts index d8d55cfd897..fecc55d3c7b 100644 --- a/crates/bindings-typescript/src/sdk/client_api/unsubscribe_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/unsubscribe_type.ts @@ -4,73 +4,16 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { QueryId } from './query_id_type'; -// Mark import as potentially unused -declare type __keep_QueryId = QueryId; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import QueryId from './query_id_type'; -export type Unsubscribe = { - requestId: number; - queryId: QueryId; -}; -let _cached_Unsubscribe_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const Unsubscribe = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_Unsubscribe_type_value) return _cached_Unsubscribe_type_value; - _cached_Unsubscribe_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_Unsubscribe_type_value.value.elements.push( - { name: 'requestId', algebraicType: __AlgebraicTypeValue.U32 }, - { name: 'queryId', algebraicType: QueryId.getTypeScriptAlgebraicType() } - ); - return _cached_Unsubscribe_type_value; - }, - - serialize(writer: __BinaryWriter, value: Unsubscribe): void { - __AlgebraicTypeValue.serializeValue( - writer, - Unsubscribe.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('Unsubscribe', { + requestId: __t.u32(), + get queryId() { + return QueryId; }, - - deserialize(reader: __BinaryReader): Unsubscribe { - return __AlgebraicTypeValue.deserializeValue( - reader, - Unsubscribe.getTypeScriptAlgebraicType() - ); - }, -}; - -export default Unsubscribe; +}); diff --git a/crates/bindings-typescript/src/sdk/client_api/update_status_type.ts b/crates/bindings-typescript/src/sdk/client_api/update_status_type.ts index ca9022ea5db..e5db16fc2e8 100644 --- a/crates/bindings-typescript/src/sdk/client_api/update_status_type.ts +++ b/crates/bindings-typescript/src/sdk/client_api/update_status_type.ts @@ -4,94 +4,20 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { DatabaseUpdate } from './database_update_type'; -// Mark import as potentially unused -declare type __keep_DatabaseUpdate = DatabaseUpdate; - -import * as UpdateStatusVariants from './update_status_variants'; + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from '../../lib/type_builders'; +import DatabaseUpdate from './database_update_type'; // The tagged union or sum type for the algebraic type `UpdateStatus`. -export type UpdateStatus = - | UpdateStatusVariants.Committed - | UpdateStatusVariants.Failed - | UpdateStatusVariants.OutOfEnergy; - -let _cached_UpdateStatus_type_value: __AlgebraicTypeType | null = null; - -// A value with helper functions to construct the type. -export const UpdateStatus = { - // Helper functions for constructing each variant of the tagged union. - // ``` - // const foo = Foo.A(42); - // assert!(foo.tag === "A"); - // assert!(foo.value === 42); - // ``` - Committed: (value: DatabaseUpdate): UpdateStatusVariants.Committed => ({ - tag: 'Committed', - value, - }), - Failed: (value: string): UpdateStatusVariants.Failed => ({ - tag: 'Failed', - value, - }), - OutOfEnergy: { tag: 'OutOfEnergy' } as const, - - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_UpdateStatus_type_value) return _cached_UpdateStatus_type_value; - _cached_UpdateStatus_type_value = __AlgebraicTypeValue.Sum({ - variants: [], - }); - _cached_UpdateStatus_type_value.value.variants.push( - { - name: 'Committed', - algebraicType: DatabaseUpdate.getTypeScriptAlgebraicType(), - }, - { name: 'Failed', algebraicType: __AlgebraicTypeValue.String }, - { - name: 'OutOfEnergy', - algebraicType: __AlgebraicTypeValue.Product({ elements: [] }), - } - ); - return _cached_UpdateStatus_type_value; - }, - - serialize(writer: __BinaryWriter, value: UpdateStatus): void { - __AlgebraicTypeValue.serializeValue( - writer, - UpdateStatus.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): UpdateStatus { - return __AlgebraicTypeValue.deserializeValue( - reader, - UpdateStatus.getTypeScriptAlgebraicType() - ); +const UpdateStatus = __t.enum('UpdateStatus', { + get Committed() { + return DatabaseUpdate; }, -}; + Failed: __t.string(), + OutOfEnergy: __t.unit(), +}); export default UpdateStatus; diff --git a/crates/bindings-typescript/src/sdk/client_api/update_status_variants.ts b/crates/bindings-typescript/src/sdk/client_api/update_status_variants.ts deleted file mode 100644 index 2a0f3231faa..00000000000 --- a/crates/bindings-typescript/src/sdk/client_api/update_status_variants.ts +++ /dev/null @@ -1,36 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -/* eslint-disable */ -/* tslint:disable */ -import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, -} from '../../index'; -import { DatabaseUpdate as DatabaseUpdateType } from './database_update_type'; -// Mark import as potentially unused -declare type __keep_DatabaseUpdateType = DatabaseUpdateType; - -export type Committed = { tag: 'Committed'; value: DatabaseUpdateType }; -export type Failed = { tag: 'Failed'; value: string }; -export type OutOfEnergy = { tag: 'OutOfEnergy' }; diff --git a/crates/bindings-typescript/src/sdk/client_cache.ts b/crates/bindings-typescript/src/sdk/client_cache.ts index 81beec64ba5..33c7bca6aa7 100644 --- a/crates/bindings-typescript/src/sdk/client_cache.ts +++ b/crates/bindings-typescript/src/sdk/client_cache.ts @@ -1,47 +1,126 @@ -import type { TableRuntimeTypeInfo } from './spacetime_module.ts'; +import type { TableNamesOf, UntypedSchemaDef } from '../lib/schema.ts'; +import type { UntypedTableDef } from '../lib/table.ts'; +import type { UntypedRemoteModule } from './spacetime_module.ts'; import { TableCache } from './table_cache.ts'; -export class ClientCache { +type TableName = [SchemaDef] extends [UntypedSchemaDef] + ? TableNamesOf + : string; + +export type TableDefForTableName< + SchemaDef extends UntypedSchemaDef, + N extends TableName, +> = [SchemaDef] extends [UntypedSchemaDef] + ? SchemaDef['tables'][number] & { name: N } + : UntypedTableDef; + +type TableCacheForTableName< + RemoteModule extends UntypedRemoteModule, + TableName extends TableNamesOf, +> = TableCache; + +/** + * This is a helper class that provides a mapping from table names to their corresponding TableCache instances + * while preserving the correspondence between the key and value type. + */ +class TableMap { + private readonly map: Map< + string, + TableCacheForTableName> + > = new Map(); + + get>( + key: K + ): TableCacheForTableName | undefined { + // Cast required: a Map can't refine the union to the exact K-specific member on get(key: K). + return this.map.get(key) as + | TableCacheForTableName + | undefined; + } + + set>( + key: K, + value: TableCacheForTableName + ): this { + this.map.set(key, value); + return this; + } + + has(key: TableName): boolean { + return this.map.has(key); + } + + delete(key: TableName): boolean { + return this.map.delete(key); + } + + // optional: iteration stays broadly typed (cannot express per-key relation here) + keys(): IterableIterator { + return this.map.keys(); + } + values(): IterableIterator< + TableCacheForTableName> + > { + return this.map.values(); + } + entries(): IterableIterator< + [string, TableCacheForTableName>] + > { + return this.map.entries(); + } + [Symbol.iterator]() { + return this.entries(); + } +} + +/** + * ClientCache maintains a cache of TableCache instances for each table in the database. + * It provides methods to get or create TableCache instances by table name, + * ensuring type safety based on the provided SchemaDef. + */ +export class ClientCache { /** * The tables in the database. */ - tables: Map>; - - constructor() { - this.tables = new Map(); - } + readonly tables = new TableMap(); /** * Returns the table with the given name. - * @param name The name of the table. - * @returns The table + * - If SchemaDef is a concrete schema, `name` is constrained to known table names, + * and the return type matches that table. + * - If SchemaDef is undefined, `name` is string and the return type is untyped. */ - getTable>( - name: string - ): TableCache { + getTable>( + name: N + ): TableCacheForTableName { const table = this.tables.get(name); - - // ! This should not happen as the table should be available but an exception is thrown just in case. if (!table) { console.error( 'The table has not been registered for this client. Please register the table before using it. If you have registered global tables using the SpacetimeDBClient.registerTables() or `registerTable()` method, please make sure that is executed first!' ); - throw new Error(`Table ${name} does not exist`); + throw new Error(`Table ${String(name)} does not exist`); } - return table; } - getOrCreateTable>( - tableTypeInfo: TableRuntimeTypeInfo - ): TableCache { - let table: TableCache; - if (!this.tables.has(tableTypeInfo.tableName)) { - table = new TableCache(tableTypeInfo); - this.tables.set(tableTypeInfo.tableName, table); - } else { - table = this.tables.get(tableTypeInfo.tableName)!; + /** + * Returns the table with the given name, creating it if needed. + * - Typed mode: `tableTypeInfo.tableName` is constrained to known names and + * the return type matches that table. + * - Untyped mode: accepts any string and returns an untyped TableCache. + */ + getOrCreateTable>( + tableDef: TableDefForTableName + ): TableCacheForTableName { + const name = tableDef.name as N; + + const table = this.tables.get(name); + if (table) { + return table; } - return table; + + const newTable = new TableCache(tableDef); + this.tables.set(name, newTable); + return newTable; } } diff --git a/crates/bindings-typescript/src/sdk/client_table.ts b/crates/bindings-typescript/src/sdk/client_table.ts new file mode 100644 index 00000000000..ac20b83decf --- /dev/null +++ b/crates/bindings-typescript/src/sdk/client_table.ts @@ -0,0 +1,154 @@ +import type { ReadonlyIndexes } from '../lib/indexes'; +import type { TableNamesOf } from '../lib/schema'; +import type { + ReadonlyTableMethods, + RowType, + TableIndexes, + UntypedTableDef, +} from '../lib/table'; +import type { ColumnBuilder } from '../lib/type_builders'; +import type { Prettify } from '../lib/type_util'; +import type { TableDefForTableName } from './client_cache'; +import type { EventContextInterface } from './event_context'; +import type { UntypedRemoteModule } from './spacetime_module'; + +export type ClientTablePrimaryKeyMethods< + RemoteModule extends UntypedRemoteModule, + TableName extends TableNamesOf, +> = { + /** + * Registers a callback to be invoked when a row is updated in the table. + * Requires that the table has a primary key defined. + * @param cb The callback to invoke when a row is updated. + */ + onUpdate( + cb: ( + ctx: EventContextInterface, + oldRow: RowType>, + newRow: RowType> + ) => void + ): void; + + /** + * Removes a previously registered update event listener. + * @param cb The callback to remove from the update event listeners. + */ + removeOnUpdate( + cb: ( + ctx: EventContextInterface, + oldRow: RowType>, + newRow: RowType> + ) => void + ): void; +}; + +export type ClientTableMethods< + RemoteModule extends UntypedRemoteModule, + TableName extends TableNamesOf, +> = { + /** + * Registers a callback to be invoked when a row is inserted into the table. + */ + onInsert( + cb: ( + ctx: EventContextInterface, + row: RowType> + ) => void + ): void; + + /** + * Removes a previously registered insert event listener. + * @param cb The callback to remove from the insert event listeners. + */ + removeOnInsert( + cb: ( + ctx: EventContextInterface, + row: RowType> + ) => void + ): void; + + /** + * Registers a callback to be invoked when a row is deleted from the table. + */ + onDelete( + cb: ( + ctx: EventContextInterface, + row: RowType> + ) => void + ): void; + + /** + * Removes a previously registered delete event listener. + * @param cb The callback to remove from the delete event listeners. + */ + removeOnDelete( + cb: ( + ctx: EventContextInterface, + row: RowType> + ) => void + ): void; +}; + +/** + * Table + * + * - Row: row shape + * - UCV: unique-constraint violation error type (never if none) + * - AIO: auto-increment overflow error type (never if none) + */ +export type ClientTable< + RemoteModule extends UntypedRemoteModule, + TableName extends TableNamesOf, +> = Prettify< + ClientTableCore & + ReadonlyIndexes< + TableDefForTableName, + TableIndexes> + > +>; + +type HasPrimaryKey = ColumnsHavePrimaryKey< + TableDef['columns'] +>; + +type ColumnsHavePrimaryKey< + Cs extends Record>, +> = { + [K in keyof Cs]: Cs[K] extends ColumnBuilder + ? M extends { isPrimaryKey: true } + ? true + : never + : never; +}[keyof Cs] extends true + ? true + : false; + +type MaybePKMethods< + RemoteModule extends UntypedRemoteModule, + TableName extends TableNamesOf, +> = Partial>; + +/** + * A variant of ClientTableCore where the primary key methods are always optional, + * allowing for classes like TableCache to implement this interface + */ +export type ClientTableCoreImplementable< + RemoteModule extends UntypedRemoteModule, + TableName extends TableNamesOf, +> = ReadonlyTableMethods> & + ClientTableMethods & + // always present but optional -> statically known member set + MaybePKMethods; + +/** + * Core methods of ClientTable, without the indexes mixed in. + * Includes only staticly known methods. + */ +export type ClientTableCore< + RemoteModule extends UntypedRemoteModule, + TableName extends TableNamesOf, +> = ReadonlyTableMethods> & + ClientTableMethods & + (HasPrimaryKey> extends true + ? ClientTablePrimaryKeyMethods + : {}); diff --git a/crates/bindings-typescript/src/sdk/db_connection_builder.ts b/crates/bindings-typescript/src/sdk/db_connection_builder.ts index a891dd3cb6b..efc32059ae9 100644 --- a/crates/bindings-typescript/src/sdk/db_connection_builder.ts +++ b/crates/bindings-typescript/src/sdk/db_connection_builder.ts @@ -1,18 +1,23 @@ import { DbConnectionImpl, type ConnectionEvent } from './db_connection_impl'; import { EventEmitter } from './event_emitter'; -import type { Identity } from '../'; -import type RemoteModule from './spacetime_module'; +import type { + DbConnectionConfig, + ErrorContextInterface, + Identity, + RemoteModuleOf, +} from '../'; import { ensureMinimumVersionOrThrow } from './version'; import { WebsocketDecompressAdapter } from './websocket_decompress_adapter'; /** * The database client connection to a SpacetimeDB server. + * NOTE: DbConnectionImpl is used here because UntypedRemoteModule causes + * variance issues with function paramters, and the end user will never be + * constructing a DbConnectionBuilder directly since it's code generated. We will + * always have a concrete RemoteModule type in those cases. Even if they user + * did do this, they would just lose type safety on the RemoteModule. */ -export class DbConnectionBuilder< - DbConnection, - ErrorContext, - _SubscriptionEventContext, -> { +export class DbConnectionBuilder> { #uri?: URL; #nameOrAddress?: string; #identity?: Identity; @@ -32,8 +37,10 @@ export class DbConnectionBuilder< * @param dbConnectionConstructor The constructor to use to create a new `DbConnection`. */ constructor( - private remoteModule: RemoteModule, - private dbConnectionConstructor: (imp: DbConnectionImpl) => DbConnection + private remoteModule: RemoteModuleOf, + private dbConnectionCtor: ( + config: DbConnectionConfig> + ) => DbConnection ) { this.#createWSFn = WebsocketDecompressAdapter.createWebSocketFn; } @@ -179,7 +186,12 @@ export class DbConnectionBuilder< * }); * ``` */ - onConnectError(callback: (ctx: ErrorContext, error: Error) => void): this { + onConnectError( + callback: ( + ctx: ErrorContextInterface>, + error: Error + ) => void + ): this { this.#emitter.on('connectError', callback); return this; } @@ -211,7 +223,10 @@ export class DbConnectionBuilder< * @throws {Error} Throws an error if called multiple times on the same `DbConnectionBuilder`. */ onDisconnect( - callback: (ctx: ErrorContext, error?: Error | undefined) => void + callback: ( + ctx: ErrorContextInterface>, + error?: Error | undefined + ) => void ): this { this.#emitter.on('disconnect', callback); return this; @@ -245,19 +260,17 @@ export class DbConnectionBuilder< // Ideally, it would be a compile time error, but I'm not sure how to accomplish that. ensureMinimumVersionOrThrow(this.remoteModule.versionInfo?.cliVersion); - return this.dbConnectionConstructor( - new DbConnectionImpl({ - uri: this.#uri, - nameOrAddress: this.#nameOrAddress, - identity: this.#identity, - token: this.#token, - emitter: this.#emitter, - compression: this.#compression, - lightMode: this.#lightMode, - confirmedReads: this.#confirmedReads, - createWSFn: this.#createWSFn, - remoteModule: this.remoteModule, - }) - ); + return this.dbConnectionCtor({ + uri: this.#uri, + nameOrAddress: this.#nameOrAddress, + identity: this.#identity, + token: this.#token, + emitter: this.#emitter, + compression: this.#compression, + lightMode: this.#lightMode, + confirmedReads: this.#confirmedReads, + createWSFn: this.#createWSFn, + remoteModule: this.remoteModule, + }); } } diff --git a/crates/bindings-typescript/src/sdk/db_connection_impl.ts b/crates/bindings-typescript/src/sdk/db_connection_impl.ts index 2dc3a144275..7a6daf50324 100644 --- a/crates/bindings-typescript/src/sdk/db_connection_impl.ts +++ b/crates/bindings-typescript/src/sdk/db_connection_impl.ts @@ -1,18 +1,13 @@ -import { ConnectionId } from '../'; -import { - AlgebraicType, - type AlgebraicTypeVariants, - type ComparablePrimitive, -} from '../'; -import { parseValue } from '../'; +import { ConnectionId, ProductType } from '../'; +import { AlgebraicType, type ComparablePrimitive } from '../'; import { BinaryReader } from '../'; import { BinaryWriter } from '../'; -import { BsatnRowList } from './client_api/bsatn_row_list_type.ts'; -import { ClientMessage } from './client_api/client_message_type.ts'; -import { DatabaseUpdate } from './client_api/database_update_type.ts'; -import { QueryUpdate } from './client_api/query_update_type.ts'; -import { ServerMessage } from './client_api/server_message_type.ts'; -import { TableUpdate as RawTableUpdate } from './client_api/table_update_type.ts'; +import BsatnRowList from './client_api/bsatn_row_list_type.ts'; +import ClientMessage from './client_api/client_message_type.ts'; +import DatabaseUpdate from './client_api/database_update_type.ts'; +import QueryUpdate from './client_api/query_update_type.ts'; +import ServerMessage from './client_api/server_message_type.ts'; +import RawTableUpdate from './client_api/table_update_type.ts'; import { ClientCache } from './client_cache.ts'; import { DbConnectionBuilder } from './db_connection_builder.ts'; import { type DbContext } from './db_context.ts'; @@ -25,7 +20,7 @@ import { } from './event_context.ts'; import { EventEmitter } from './event_emitter.ts'; import { decompress } from './decompress.ts'; -import type { Identity } from '../'; +import type { Identity, Infer, InferTypeOfRow } from '../'; import type { IdentityTokenMessage, Message, @@ -33,7 +28,7 @@ import type { UnsubscribeAppliedMessage, } from './message_types.ts'; import type { ReducerEvent } from './reducer_event.ts'; -import type RemoteModule from './spacetime_module.ts'; +import { type UntypedRemoteModule } from './spacetime_module.ts'; import { TableCache, type Operation, @@ -49,11 +44,21 @@ import { type SubscribeEvent, } from './subscription_builder_impl.ts'; import { stdbLogger } from './logger.ts'; -import { type ReducerRuntimeTypeInfo } from './spacetime_module.ts'; import { fromByteArray } from 'base64-js'; +import type { + ReducerEventInfo, + ReducersView, + SetReducerFlags, +} from './reducers.ts'; +import type { ClientDbView } from './db_view.ts'; +import type { UntypedTableDef } from '../lib/table.ts'; +import { toCamelCase } from '../lib/util.ts'; export { DbConnectionBuilder, SubscriptionBuilderImpl, TableCache, type Event }; +export type RemoteModuleOf = + C extends DbConnectionImpl ? RM : never; + export type { DbContext, EventContextInterface, @@ -66,12 +71,16 @@ export type { export type ConnectionEvent = 'connect' | 'disconnect' | 'connectError'; export type CallReducerFlags = 'FullUpdate' | 'NoSuccessNotify'; -type ReducerEventCallback = ( - ctx: ReducerEventContextInterface, +type ReducerEventCallback< + RemoteModule extends UntypedRemoteModule, + ReducerArgs extends any[] = any[], +> = ( + ctx: ReducerEventContextInterface, ...args: ReducerArgs ) => void; -type SubscriptionEventCallback = ( - ctx: SubscriptionEventContextInterface + +type SubscriptionEventCallback = ( + ctx: SubscriptionEventContextInterface ) => void; function callReducerFlagsToNumber(flags: CallReducerFlags): number { @@ -83,24 +92,21 @@ function callReducerFlagsToNumber(flags: CallReducerFlags): number { } } -type DbConnectionConfig = { +export type DbConnectionConfig = { uri: URL; nameOrAddress: string; identity?: Identity; token?: string; emitter: EventEmitter; - remoteModule: RemoteModule; createWSFn: typeof WebsocketDecompressAdapter.createWebSocketFn; compression: 'gzip' | 'none'; lightMode: boolean; confirmedReads?: boolean; + remoteModule: RemoteModule; }; -export class DbConnectionImpl< - DBView = any, - Reducers = any, - SetReducerFlags = any, -> implements DbContext +export class DbConnectionImpl + implements DbContext { /** * Whether or not the connection is active. @@ -121,20 +127,20 @@ export class DbConnectionImpl< * The accessor field to access the tables in the database and associated * callback functions. */ - db: DBView; + db: ClientDbView; /** * The accessor field to access the reducers in the database and associated * callback functions. */ - reducers: Reducers; + reducers: ReducersView; /** * The accessor field to access functions related to setting flags on * reducers regarding how the server should handle the reducer call and * the events that it sends back to the client. */ - setReducerFlags: SetReducerFlags; + setReducerFlags: SetReducerFlags; /** * The `ConnectionId` of the connection to to the database. @@ -144,18 +150,19 @@ export class DbConnectionImpl< // These fields are meant to be strictly private. #queryId = 0; #emitter: EventEmitter; - #reducerEmitter: EventEmitter = + #reducerEmitter: EventEmitter> = new EventEmitter(); - #onApplied?: SubscriptionEventCallback; - #remoteModule: RemoteModule; + #onApplied?: SubscriptionEventCallback; #messageQueue = Promise.resolve(); - #subscriptionManager = new SubscriptionManager(); + #subscriptionManager = new SubscriptionManager(); + #remoteModule: RemoteModule; + #callReducerFlags = new Map(); // These fields are not part of the public API, but in a pinch you // could use JavaScript to access them by bypassing TypeScript's // private fields. // We use them in testing. - private clientCache: ClientCache; + private clientCache: ClientCache; private ws?: WebsocketDecompressAdapter | WebsocketTestAdapter; private wsPromise: Promise< WebsocketDecompressAdapter | WebsocketTestAdapter | undefined @@ -172,7 +179,7 @@ export class DbConnectionImpl< compression, lightMode, confirmedReads, - }: DbConnectionConfig) { + }: DbConnectionConfig) { stdbLogger('info', 'Connecting to SpacetimeDB WS...'); // We use .toString() here because some versions of React Native contain a bug where the URL constructor @@ -192,13 +199,10 @@ export class DbConnectionImpl< const connectionId = this.connectionId.toHexString(); url.searchParams.set('connection_id', connectionId); - this.clientCache = new ClientCache(); - this.db = this.#remoteModule.dbViewConstructor(this); - this.setReducerFlags = this.#remoteModule.setReducerFlagsConstructor(); - this.reducers = this.#remoteModule.reducersConstructor( - this, - this.setReducerFlags - ); + this.clientCache = new ClientCache(); + this.db = this.#makeDbView(remoteModule); + this.reducers = this.#makeReducers(remoteModule); + this.setReducerFlags = this.#makeSetReducerFlags(remoteModule); this.wsPromise = createWSFn({ url, @@ -236,6 +240,78 @@ export class DbConnectionImpl< return queryId; }; + #makeDbView(def: RemoteModule): ClientDbView { + const view = Object.create(null) as ClientDbView; + + for (const tbl of def.tables) { + // ClientDbView uses this name verbatim + const key = tbl.accessorName; + Object.defineProperty(view, key, { + enumerable: true, + configurable: false, + get: () => { + return this.clientCache.getOrCreateTable(tbl); + }, + }); + } + + return view; + } + + #makeReducers(def: RemoteModule): ReducersView { + const out: Record = {}; + + for (const reducer of def.reducers) { + const key = toCamelCase(reducer.name); + + (out as any)[key] = (params: InferTypeOfRow) => { + const flags = this.#callReducerFlags.get(reducer.name) ?? 'FullUpdate'; + this.callReducerWithParams( + reducer.name, + reducer.paramsType, + params, + flags + ); + }; + } + + return out as ReducersView; + } + + #makeSetReducerFlags(defs: RemoteModule): SetReducerFlags { + const out = Object.create(null) as SetReducerFlags; + for (const r of defs.reducers) { + const key = toCamelCase(r.name); + Object.defineProperty(out, key, { + enumerable: true, + configurable: false, + value: (flags: CallReducerFlags) => { + this.#callReducerFlags.set(r.name, flags); + }, + }); + } + return out; + } + + #makeEventContext( + event: Event< + ReducerEventInfo< + InferTypeOfRow + > + > + ): EventContextInterface { + // Bind methods to preserve `this` (#private fields safe) + return { + db: this.db, + reducers: this.reducers, + setReducerFlags: this.setReducerFlags, + isActive: this.isActive, + subscriptionBuilder: this.subscriptionBuilder.bind(this), + disconnect: this.disconnect.bind(this), + event, + }; + } + // NOTE: This is very important!!! This is the actual function that // gets called when you call `connection.subscriptionBuilder()`. // The `subscriptionBuilder` function which is generated, just shadows @@ -243,13 +319,16 @@ export class DbConnectionImpl< // Do not remove this function, or shoot yourself in the foot please. // It's not clear what would be a better way to do this at this exact // moment. - subscriptionBuilder = (): SubscriptionBuilderImpl => { + subscriptionBuilder = (): SubscriptionBuilderImpl => { return new SubscriptionBuilderImpl(this); }; registerSubscription( - handle: SubscriptionHandleImpl, - handleEmitter: EventEmitter, + handle: SubscriptionHandleImpl, + handleEmitter: EventEmitter< + SubscribeEvent, + SubscriptionEventCallback + >, querySql: string[] ): number { const queryId = this.#getNextQueryId(); @@ -282,27 +361,35 @@ export class DbConnectionImpl< // This function is async because we decompress the message async async #processParsedMessage( - message: ServerMessage + message: Infer ): Promise { const parseRowList = ( type: 'insert' | 'delete', tableName: string, - rowList: BsatnRowList + rowList: Infer ): Operation[] => { const buffer = rowList.rowsData; const reader = new BinaryReader(buffer); const rows: Operation[] = []; - const rowType = this.#remoteModule.tables[tableName]!.rowType; + + // TODO: performance + const table = this.#remoteModule.tables.find(t => t.name === tableName); + const rowType = table!.rowType; + const columnsArray = Object.entries(table!.columns); + const primaryKeyColumnEntry = columnsArray.find( + col => col[1].columnMetadata.isPrimaryKey + ); let previousOffset = 0; - const primaryKeyInfo = - this.#remoteModule.tables[tableName]!.primaryKeyInfo; while (reader.remaining > 0) { - const row = AlgebraicType.deserializeValue(reader, rowType); + const row = ProductType.deserializeValue(reader, rowType); let rowId: ComparablePrimitive | undefined = undefined; - if (primaryKeyInfo !== undefined) { + if (primaryKeyColumnEntry !== undefined) { + const primaryKeyColName = primaryKeyColumnEntry[0]; + const primaryKeyColType = + primaryKeyColumnEntry[1].typeBuilder.algebraicType; rowId = AlgebraicType.intoMapKey( - primaryKeyInfo.colType, - row[primaryKeyInfo.colName] + primaryKeyColType, + row[primaryKeyColName] ); } else { // Get a view of the bytes for this row. @@ -323,16 +410,17 @@ export class DbConnectionImpl< }; const parseTableUpdate = async ( - rawTableUpdate: RawTableUpdate - ): Promise => { + rawTableUpdate: Infer + ): Promise> => { const tableName = rawTableUpdate.tableName; let operations: Operation[] = []; for (const update of rawTableUpdate.updates) { - let decompressed: QueryUpdate; + let decompressed: Infer; if (update.tag === 'Gzip') { const decompressedBuffer = await decompress(update.value, 'gzip'); - decompressed = QueryUpdate.deserialize( - new BinaryReader(decompressedBuffer) + decompressed = AlgebraicType.deserializeValue( + new BinaryReader(decompressedBuffer), + QueryUpdate.algebraicType ); } else if (update.tag === 'Brotli') { throw new Error( @@ -355,9 +443,9 @@ export class DbConnectionImpl< }; const parseDatabaseUpdate = async ( - dbUpdate: DatabaseUpdate - ): Promise => { - const tableUpdates: CacheTableUpdate[] = []; + dbUpdate: Infer + ): Promise[]> => { + const tableUpdates: CacheTableUpdate[] = []; for (const rawTableUpdate of dbUpdate.tables) { tableUpdates.push(await parseTableUpdate(rawTableUpdate)); } @@ -395,7 +483,7 @@ export class DbConnectionImpl< const args = txUpdate.reducerCall.args; const energyQuantaUsed = txUpdate.energyQuantaUsed; - let tableUpdates: CacheTableUpdate[] = []; + let tableUpdates: CacheTableUpdate[] = []; let errMessage = ''; switch (txUpdate.status.tag) { case 'Committed': @@ -465,9 +553,7 @@ export class DbConnectionImpl< const parsedTableUpdates = await parseDatabaseUpdate( message.value.update ); - const subscribeAppliedMessage: SubscribeAppliedMessage< - Record - > = { + const subscribeAppliedMessage: SubscribeAppliedMessage = { tag: 'SubscribeApplied', queryId: message.value.queryId.id, tableUpdates: parsedTableUpdates, @@ -479,9 +565,7 @@ export class DbConnectionImpl< const parsedTableUpdates = await parseDatabaseUpdate( message.value.update ); - const unsubscribeAppliedMessage: UnsubscribeAppliedMessage< - Record - > = { + const unsubscribeAppliedMessage: UnsubscribeAppliedMessage = { tag: 'UnsubscribeApplied', queryId: message.value.queryId.id, tableUpdates: parsedTableUpdates, @@ -499,11 +583,15 @@ export class DbConnectionImpl< } } - #sendMessage(message: ClientMessage): void { + #sendMessage(message: Infer): void { this.wsPromise.then(wsResolved => { if (wsResolved) { const writer = new BinaryWriter(1024); - ClientMessage.serialize(writer, message); + AlgebraicType.serializeValue( + writer, + ClientMessage.algebraicType, + message + ); const encoded = writer.getBuffer(); wsResolved.send(encoded); } @@ -518,15 +606,18 @@ export class DbConnectionImpl< } #applyTableUpdates( - tableUpdates: CacheTableUpdate[], - eventContext: EventContextInterface + tableUpdates: CacheTableUpdate[], + eventContext: EventContextInterface ): PendingCallback[] { const pendingCallbacks: PendingCallback[] = []; for (const tableUpdate of tableUpdates) { // Get table information for the table being updated const tableName = tableUpdate.tableName; - const tableTypeInfo = this.#remoteModule.tables[tableName]!; - const table = this.clientCache.getOrCreateTable(tableTypeInfo); + // TODO: performance + const tableDef = this.#remoteModule.tables.find( + t => t.name === tableName + )!; + const table = this.clientCache.getOrCreateTable(tableDef); const newCallbacks = table.applyOperations( tableUpdate.operations, eventContext @@ -539,7 +630,10 @@ export class DbConnectionImpl< } async #processMessage(data: Uint8Array): Promise { - const serverMessage = parseValue(ServerMessage, data); + const serverMessage = AlgebraicType.deserializeValue( + new BinaryReader(data), + ServerMessage.algebraicType + ); const message = await this.#processParsedMessage(serverMessage); if (!message) { return; @@ -547,11 +641,7 @@ export class DbConnectionImpl< switch (message.tag) { case 'InitialSubscription': { const event: Event = { tag: 'SubscribeApplied' }; - - const eventContext = this.#remoteModule.eventContextConstructor( - this, - event - ); + const eventContext = this.#makeEventContext(event); // Remove the event from the subscription event context // It is not a field in the type narrowed SubscriptionEventContext const { event: _, ...subscriptionEventContext } = eventContext; @@ -570,10 +660,7 @@ export class DbConnectionImpl< } case 'TransactionUpdateLight': { const event: Event = { tag: 'UnknownTransaction' }; - const eventContext = this.#remoteModule.eventContextConstructor( - this, - event - ); + const eventContext = this.#makeEventContext(event); const callbacks = this.#applyTableUpdates( message.tableUpdates, eventContext @@ -586,18 +673,19 @@ export class DbConnectionImpl< case 'TransactionUpdate': { let reducerInfo = message.reducerInfo; let unknownTransaction = false; - let reducerArgs: any | undefined; - let reducerTypeInfo: ReducerRuntimeTypeInfo | undefined; + let reducerArgs: InferTypeOfRow | undefined; + const reducer = this.#remoteModule.reducers.find( + t => t.name === reducerInfo!.reducerName + )!; if (!reducerInfo) { unknownTransaction = true; } else { - reducerTypeInfo = - this.#remoteModule.reducers[reducerInfo.reducerName]; + // TODO: performance try { const reader = new BinaryReader(reducerInfo.args as Uint8Array); - reducerArgs = AlgebraicType.deserializeValue( + reducerArgs = ProductType.deserializeValue( reader, - reducerTypeInfo.argsType + reducer?.paramsType ); } catch { // This should only be printed in development, since it's @@ -610,10 +698,7 @@ export class DbConnectionImpl< if (unknownTransaction) { const event: Event = { tag: 'UnknownTransaction' }; - const eventContext = this.#remoteModule.eventContextConstructor( - this, - event - ); + const eventContext = this.#makeEventContext(event); const callbacks = this.#applyTableUpdates( message.tableUpdates, eventContext @@ -628,7 +713,7 @@ export class DbConnectionImpl< // At this point, we know that `reducerInfo` is not null because // we return if `unknownTransaction` is true. reducerInfo = reducerInfo!; - reducerTypeInfo = reducerTypeInfo!; + reducerArgs = reducerArgs!; // Thus this must be a reducer event create it and emit it. const reducerEvent = { @@ -646,10 +731,7 @@ export class DbConnectionImpl< tag: 'Reducer', value: reducerEvent, }; - const eventContext = this.#remoteModule.eventContextConstructor( - this, - event - ); + const eventContext = this.#makeEventContext(event); const reducerEventContext = { ...eventContext, event: reducerEvent, @@ -661,9 +743,7 @@ export class DbConnectionImpl< ); const argsArray: any[] = []; - ( - reducerTypeInfo.argsType as AlgebraicTypeVariants.Product - ).value.elements.forEach(element => { + reducer.paramsType.elements.forEach(element => { argsArray.push(reducerArgs[element.name!]); }); this.#reducerEmitter.emit( @@ -698,10 +778,7 @@ export class DbConnectionImpl< break; } const event: Event = { tag: 'SubscribeApplied' }; - const eventContext = this.#remoteModule.eventContextConstructor( - this, - event - ); + const eventContext = this.#makeEventContext(event); const { event: _, ...subscriptionEventContext } = eventContext; const callbacks = this.#applyTableUpdates( message.tableUpdates, @@ -726,10 +803,7 @@ export class DbConnectionImpl< break; } const event: Event = { tag: 'UnsubscribeApplied' }; - const eventContext = this.#remoteModule.eventContextConstructor( - this, - event - ); + const eventContext = this.#makeEventContext(event); const { event: _, ...subscriptionEventContext } = eventContext; const callbacks = this.#applyTableUpdates( message.tableUpdates, @@ -745,10 +819,7 @@ export class DbConnectionImpl< case 'SubscriptionError': { const error = Error(message.error); const event: Event = { tag: 'Error', value: error }; - const eventContext = this.#remoteModule.eventContextConstructor( - this, - event - ); + const eventContext = this.#makeEventContext(event); const errorContext = { ...eventContext, event: error, @@ -809,6 +880,24 @@ export class DbConnectionImpl< this.#sendMessage(message); } + /** + * Call a reducer on your SpacetimeDB module with typed arguments. + * @param reducerSchema The schema of the reducer to call + * @param callReducerFlags The flags for the reducer call + * @param params The arguments to pass to the reducer + */ + callReducerWithParams( + reducerName: string, + paramsType: ProductType, + params: object, + flags: CallReducerFlags + ) { + const writer = new BinaryWriter(1024); + ProductType.serializeValue(writer, paramsType, params); + const argsBuffer = writer.getBuffer(); + this.callReducer(reducerName, argsBuffer, flags); + } + /** * Close the current connection. * @@ -829,63 +918,69 @@ export class DbConnectionImpl< private on( eventName: ConnectionEvent, - callback: (ctx: DbConnectionImpl, ...args: any[]) => void + callback: (ctx: DbConnectionImpl, ...args: any[]) => void ): void { this.#emitter.on(eventName, callback); } private off( eventName: ConnectionEvent, - callback: (ctx: DbConnectionImpl, ...args: any[]) => void + callback: (ctx: DbConnectionImpl, ...args: any[]) => void ): void { this.#emitter.off(eventName, callback); } private onConnect( - callback: (ctx: DbConnectionImpl, ...args: any[]) => void + callback: (ctx: DbConnectionImpl, ...args: any[]) => void ): void { this.#emitter.on('connect', callback); } private onDisconnect( - callback: (ctx: DbConnectionImpl, ...args: any[]) => void + callback: (ctx: DbConnectionImpl, ...args: any[]) => void ): void { this.#emitter.on('disconnect', callback); } private onConnectError( - callback: (ctx: DbConnectionImpl, ...args: any[]) => void + callback: (ctx: DbConnectionImpl, ...args: any[]) => void ): void { this.#emitter.on('connectError', callback); } - private removeOnConnect( - callback: (ctx: DbConnectionImpl, ...args: any[]) => void + removeOnConnect( + callback: (ctx: DbConnectionImpl, ...args: any[]) => void ): void { this.#emitter.off('connect', callback); } - private removeOnDisconnect( - callback: (ctx: DbConnectionImpl, ...args: any[]) => void + removeOnDisconnect( + callback: (ctx: DbConnectionImpl, ...args: any[]) => void ): void { this.#emitter.off('disconnect', callback); } - private removeOnConnectError( - callback: (ctx: DbConnectionImpl, ...args: any[]) => void + removeOnConnectError( + callback: (ctx: DbConnectionImpl, ...args: any[]) => void ): void { this.#emitter.off('connectError', callback); } // Note: This is required to be public because it needs to be // called from the `RemoteReducers` class. - onReducer(reducerName: string, callback: ReducerEventCallback): void { + onReducer( + reducerName: string, + callback: ReducerEventCallback + ): void { this.#reducerEmitter.on(reducerName, callback); } // Note: This is required to be public because it needs to be // called from the `RemoteReducers` class. - offReducer(reducerName: string, callback: ReducerEventCallback): void { + offReducer( + reducerName: string, + callback: ReducerEventCallback + ): void { this.#reducerEmitter.off(reducerName, callback); } } diff --git a/crates/bindings-typescript/src/sdk/db_context.ts b/crates/bindings-typescript/src/sdk/db_context.ts index 533ce32e923..f34bf4a95ed 100644 --- a/crates/bindings-typescript/src/sdk/db_context.ts +++ b/crates/bindings-typescript/src/sdk/db_context.ts @@ -1,20 +1,19 @@ +import type { ClientDbView } from './db_view'; +import type { ReducersView, SetReducerFlags } from './reducers'; +import type { UntypedRemoteModule } from './spacetime_module'; import type { SubscriptionBuilderImpl } from './subscription_builder_impl'; /** * Interface representing a database context. * - * @template DBView - Type representing the database view. - * @template Reducers - Type representing the reducers. + * @template DbView - Type representing the database view. + * @template ReducersDef - Type representing the reducers. * @template SetReducerFlags - Type representing the reducer flags collection. */ -export interface DbContext< - DBView = any, - Reducers = any, - SetReducerFlags = any, -> { - db: DBView; - reducers: Reducers; - setReducerFlags: SetReducerFlags; +export interface DbContext { + db: ClientDbView; + reducers: ReducersView; + setReducerFlags: SetReducerFlags; isActive: boolean; /** @@ -22,11 +21,7 @@ export interface DbContext< * * @returns The subscription builder. */ - subscriptionBuilder(): SubscriptionBuilderImpl< - DBView, - Reducers, - SetReducerFlags - >; + subscriptionBuilder(): SubscriptionBuilderImpl; /** * Disconnects from the database. diff --git a/crates/bindings-typescript/src/sdk/db_view.ts b/crates/bindings-typescript/src/sdk/db_view.ts new file mode 100644 index 00000000000..dcfd6b13517 --- /dev/null +++ b/crates/bindings-typescript/src/sdk/db_view.ts @@ -0,0 +1,12 @@ +import type { UntypedRemoteModule } from './spacetime_module'; +import type { ClientTable } from './client_table'; + +/** + * A type representing a client-side database view, mapping table names to their corresponding client Table handles. + */ +export type ClientDbView = { + readonly [Tbl in RemoteModule['tables'][number] as Tbl['accessorName']]: ClientTable< + RemoteModule, + Tbl['name'] + >; +}; diff --git a/crates/bindings-typescript/src/sdk/event.ts b/crates/bindings-typescript/src/sdk/event.ts index 8be677e47ab..b3d07405d37 100644 --- a/crates/bindings-typescript/src/sdk/event.ts +++ b/crates/bindings-typescript/src/sdk/event.ts @@ -1,6 +1,7 @@ -import type { ReducerEvent, ReducerInfoType } from './reducer_event'; +import type { ReducerEvent } from './reducer_event'; +import type { ReducerEventInfo } from './reducers'; -export type Event = +export type Event = | { tag: 'Reducer'; value: ReducerEvent } | { tag: 'SubscribeApplied' } | { tag: 'UnsubscribeApplied' } diff --git a/crates/bindings-typescript/src/sdk/event_context.ts b/crates/bindings-typescript/src/sdk/event_context.ts index 2ed7112d431..677adcac90d 100644 --- a/crates/bindings-typescript/src/sdk/event_context.ts +++ b/crates/bindings-typescript/src/sdk/event_context.ts @@ -1,41 +1,38 @@ +import type { InferTypeOfRow } from '../lib/type_builders.ts'; import type { DbContext } from './db_context'; import type { Event } from './event.ts'; -import type { ReducerEvent, ReducerInfoType } from './reducer_event.ts'; +import type { ReducerEvent } from './reducer_event.ts'; +import type { ReducerEventInfo } from './reducers.ts'; +import type { UntypedRemoteModule } from './spacetime_module.ts'; -export interface EventContextInterface< - DBView = any, - Reducers = any, - SetReducerFlags = any, - Reducer extends ReducerInfoType = never, -> extends DbContext { +export type UntypedEventContext = EventContextInterface; + +export interface EventContextInterface + extends DbContext { /** Enum with variants for all possible events. */ - event: Event; + event: Event< + ReducerEventInfo> + >; } export interface ReducerEventContextInterface< - DBView = any, - Reducers = any, - SetReducerFlags = any, - Reducer extends ReducerInfoType = never, -> extends DbContext { + RemoteModule extends UntypedRemoteModule, +> extends DbContext { /** Enum with variants for all possible events. */ - event: ReducerEvent; + event: ReducerEvent< + ReducerEventInfo> + >; } // eslint-disable-next-line @typescript-eslint/no-empty-object-type export interface SubscriptionEventContextInterface< - DBView = any, - Reducers = any, - SetReducerFlags = any, -> extends DbContext { + RemoteModule extends UntypedRemoteModule, +> extends DbContext { /** No event is provided **/ } -export interface ErrorContextInterface< - DBView = any, - Reducers = any, - SetReducerFlags = any, -> extends DbContext { +export interface ErrorContextInterface + extends DbContext { /** Enum with variants for all possible events. */ event?: Error; } diff --git a/crates/bindings-typescript/src/sdk/index.ts b/crates/bindings-typescript/src/sdk/index.ts index 814bc67a54e..30f7b0e90cd 100644 --- a/crates/bindings-typescript/src/sdk/index.ts +++ b/crates/bindings-typescript/src/sdk/index.ts @@ -2,4 +2,10 @@ export * from './db_connection_impl.ts'; export * from './client_cache.ts'; export * from './message_types.ts'; -export { type TableHandle } from './table_handle.ts'; +export { type ClientTable } from './client_table.ts'; +export { type RemoteModule } from './spacetime_module.ts'; +export { type SetReducerFlags } from './reducers.ts'; +export * from '../lib/type_builders.ts'; +export { schema, convertToAccessorMap } from '../lib/schema.ts'; +export { table } from '../lib/table.ts'; +export { reducerSchema, reducers } from '../lib/reducers.ts'; diff --git a/crates/bindings-typescript/src/sdk/message_types.ts b/crates/bindings-typescript/src/sdk/message_types.ts index ee7842019c0..6a7bdaa4dec 100644 --- a/crates/bindings-typescript/src/sdk/message_types.ts +++ b/crates/bindings-typescript/src/sdk/message_types.ts @@ -1,34 +1,34 @@ -import { ConnectionId } from '../'; -import type { UpdateStatus } from './client_api/index.ts'; +import { ConnectionId, type Infer } from '../'; import { Identity } from '../'; import type { TableUpdate } from './table_cache.ts'; import { Timestamp } from '../'; +import type { UntypedTableDef } from '../lib/table.ts'; +import type UpdateStatus from './client_api/update_status_type.ts'; -export type InitialSubscriptionMessage> = { +export type InitialSubscriptionMessage = { tag: 'InitialSubscription'; - tableUpdates: TableUpdate[]; + tableUpdates: TableUpdate[]; }; -export type TransactionUpdateMessage> = { +export type TransactionUpdateMessage = { tag: 'TransactionUpdate'; - tableUpdates: TableUpdate[]; + tableUpdates: TableUpdate[]; identity: Identity; connectionId: ConnectionId | null; reducerInfo?: { reducerName: string; args: Uint8Array; }; - status: UpdateStatus; + status: Infer; message: string; timestamp: Timestamp; energyConsumed: bigint; }; -export type TransactionUpdateLightMessage> = - { - tag: 'TransactionUpdateLight'; - tableUpdates: TableUpdate[]; - }; +export type TransactionUpdateLightMessage = { + tag: 'TransactionUpdateLight'; + tableUpdates: TableUpdate[]; +}; export type IdentityTokenMessage = { tag: 'IdentityToken'; @@ -37,16 +37,16 @@ export type IdentityTokenMessage = { connectionId: ConnectionId; }; -export type SubscribeAppliedMessage> = { +export type SubscribeAppliedMessage = { tag: 'SubscribeApplied'; queryId: number; - tableUpdates: TableUpdate[]; + tableUpdates: TableUpdate[]; }; -export type UnsubscribeAppliedMessage> = { +export type UnsubscribeAppliedMessage = { tag: 'UnsubscribeApplied'; queryId: number; - tableUpdates: TableUpdate[]; + tableUpdates: TableUpdate[]; }; export type SubscriptionError = { @@ -55,12 +55,11 @@ export type SubscriptionError = { error: string; }; -export type Message = Record> = - - | InitialSubscriptionMessage - | TransactionUpdateMessage - | TransactionUpdateLightMessage - | IdentityTokenMessage - | SubscribeAppliedMessage - | UnsubscribeAppliedMessage - | SubscriptionError; +export type Message = + | InitialSubscriptionMessage + | TransactionUpdateMessage + | TransactionUpdateLightMessage + | IdentityTokenMessage + | SubscribeAppliedMessage + | UnsubscribeAppliedMessage + | SubscriptionError; diff --git a/crates/bindings-typescript/src/sdk/reducer_event.ts b/crates/bindings-typescript/src/sdk/reducer_event.ts index aaebd27fabb..884f083118d 100644 --- a/crates/bindings-typescript/src/sdk/reducer_event.ts +++ b/crates/bindings-typescript/src/sdk/reducer_event.ts @@ -1,11 +1,10 @@ -import { ConnectionId } from '../'; +import { ConnectionId, type Infer } from '../'; import { Timestamp } from '../'; -import type { UpdateStatus } from './client_api/index.ts'; import { Identity } from '../'; +import type UpdateStatus from './client_api/update_status_type.ts'; +import type { ReducerEventInfo } from './reducers.ts'; -export type ReducerInfoType = { name: string; args?: any } | never; - -export type ReducerEvent = { +export type ReducerEvent = { /** * The time when the reducer started running. * @@ -17,7 +16,7 @@ export type ReducerEvent = { /** * Whether the reducer committed, was aborted due to insufficient energy, or failed with an error message. */ - status: UpdateStatus; + status: Infer; /** * The identity of the caller. diff --git a/crates/bindings-typescript/src/sdk/reducer_handle.ts b/crates/bindings-typescript/src/sdk/reducer_handle.ts new file mode 100644 index 00000000000..17a80e72000 --- /dev/null +++ b/crates/bindings-typescript/src/sdk/reducer_handle.ts @@ -0,0 +1,12 @@ +export type ReducerHandle = { + /** Phantom reducer name */ + readonly reducerName?: ReducerName; +}; + +export type ReducerNamesFromReducers = R extends object + ? { + [K in keyof R]: R[K] extends ReducerHandle + ? ReducerName + : never; + }[keyof R] + : never; diff --git a/crates/bindings-typescript/src/sdk/reducers.ts b/crates/bindings-typescript/src/sdk/reducers.ts new file mode 100644 index 00000000000..e8bf048e868 --- /dev/null +++ b/crates/bindings-typescript/src/sdk/reducers.ts @@ -0,0 +1,34 @@ +import type { ProductType } from '../lib/algebraic_type'; +import type { ParamsObj } from '../lib/reducers'; +import type { CoerceRow } from '../lib/table'; +import type { InferTypeOfRow } from '../lib/type_builders'; +import type { CamelCase } from '../lib/type_util'; +import type { CallReducerFlags } from './db_connection_impl'; + +export type ReducersView = { + [I in keyof R['reducers'] as CamelCase< + R['reducers'][number]['accessorName'] + >]: (params: InferTypeOfRow) => void; +}; + +export type ReducerEventInfo = { + name: string; + args: Args; +}; + +export type UntypedReducerDef = { + name: string; + accessorName: string; + params: CoerceRow; + paramsType: ProductType; +}; + +export type UntypedReducersDef = { + reducers: readonly UntypedReducerDef[]; +}; + +export type SetReducerFlags = { + [K in keyof R['reducers'] as CamelCase]: ( + flags: CallReducerFlags + ) => void; +}; diff --git a/crates/bindings-typescript/src/sdk/set_reducer_flags.ts b/crates/bindings-typescript/src/sdk/set_reducer_flags.ts new file mode 100644 index 00000000000..35fdf3a1c39 --- /dev/null +++ b/crates/bindings-typescript/src/sdk/set_reducer_flags.ts @@ -0,0 +1,6 @@ +import type { CallReducerFlags } from './db_connection_impl'; + +export type UntypedSetReducerFlags = Record< + string, + (flags: CallReducerFlags) => void +>; diff --git a/crates/bindings-typescript/src/sdk/spacetime_module.ts b/crates/bindings-typescript/src/sdk/spacetime_module.ts index 4a76006f93f..bf37b798d2f 100644 --- a/crates/bindings-typescript/src/sdk/spacetime_module.ts +++ b/crates/bindings-typescript/src/sdk/spacetime_module.ts @@ -1,33 +1,24 @@ -import type { AlgebraicType } from '../'; -import type { DbConnectionImpl } from './db_connection_impl'; +import type { UntypedSchemaDef } from '../lib/schema'; +import type { UntypedReducersDef } from './reducers'; -export interface TableRuntimeTypeInfo { - tableName: string; - rowType: AlgebraicType; - primaryKeyInfo?: PrimaryKeyInfo; -} +export type RemoteModule< + SchemaDef extends UntypedSchemaDef, + ReducersDef extends UntypedReducersDef, + CLI extends string = string, +> = SchemaDef & + ReducersDef & { + versionInfo: { + cliVersion: CLI; + }; + }; -export interface PrimaryKeyInfo { - colName: string; - colType: AlgebraicType; -} +export type UntypedRemoteModule = RemoteModule< + UntypedSchemaDef, + UntypedReducersDef +>; -export interface ReducerRuntimeTypeInfo { - reducerName: string; - argsType: AlgebraicType; -} +export type SchemaDef = + RemoteModule['tables']; -export default interface RemoteModule { - tables: { [name: string]: TableRuntimeTypeInfo }; - reducers: { [name: string]: ReducerRuntimeTypeInfo }; - eventContextConstructor: (imp: DbConnectionImpl, event: any) => any; - dbViewConstructor: (connection: DbConnectionImpl) => any; - reducersConstructor: ( - connection: DbConnectionImpl, - setReducerFlags: any - ) => any; - setReducerFlagsConstructor: () => any; - versionInfo?: { - cliVersion: string; - }; -} +export type ReducersDef = + RemoteModule['reducers']; diff --git a/crates/bindings-typescript/src/sdk/subscription_builder_impl.ts b/crates/bindings-typescript/src/sdk/subscription_builder_impl.ts index 5fffd581237..851b6baffe0 100644 --- a/crates/bindings-typescript/src/sdk/subscription_builder_impl.ts +++ b/crates/bindings-typescript/src/sdk/subscription_builder_impl.ts @@ -4,21 +4,13 @@ import type { SubscriptionEventContextInterface, } from './event_context'; import { EventEmitter } from './event_emitter'; +import type { UntypedRemoteModule } from './spacetime_module'; -export class SubscriptionBuilderImpl< - DBView = any, - Reducers = any, - SetReducerFlags = any, -> { - #onApplied?: ( - ctx: SubscriptionEventContextInterface - ) => void = undefined; - #onError?: ( - ctx: ErrorContextInterface - ) => void = undefined; - constructor( - private db: DbConnectionImpl - ) {} +export class SubscriptionBuilderImpl { + #onApplied?: (ctx: SubscriptionEventContextInterface) => void = + undefined; + #onError?: (ctx: ErrorContextInterface) => void = undefined; + constructor(private db: DbConnectionImpl) {} /** * Registers `callback` to run when this query is successfully added to our subscribed set, @@ -36,10 +28,8 @@ export class SubscriptionBuilderImpl< * @returns The current `SubscriptionBuilder` instance. */ onApplied( - cb: ( - ctx: SubscriptionEventContextInterface - ) => void - ): SubscriptionBuilderImpl { + cb: (ctx: SubscriptionEventContextInterface) => void + ): SubscriptionBuilderImpl { this.#onApplied = cb; return this; } @@ -65,8 +55,8 @@ export class SubscriptionBuilderImpl< * @returns The current `SubscriptionBuilder` instance. */ onError( - cb: (ctx: ErrorContextInterface) => void - ): SubscriptionBuilderImpl { + cb: (ctx: ErrorContextInterface) => void + ): SubscriptionBuilderImpl { this.#onError = cb; return this; } @@ -89,7 +79,7 @@ export class SubscriptionBuilderImpl< */ subscribe( query_sql: string | string[] - ): SubscriptionHandleImpl { + ): SubscriptionHandleImpl { const queries = Array.isArray(query_sql) ? query_sql : [query_sql]; if (queries.length === 0) { throw new Error('Subscriptions must have at least one query'); @@ -126,18 +116,17 @@ export class SubscriptionBuilderImpl< export type SubscribeEvent = 'applied' | 'error' | 'end'; -export class SubscriptionManager { +export class SubscriptionManager { subscriptions: Map< number, - { handle: SubscriptionHandleImpl; emitter: EventEmitter } + { + handle: SubscriptionHandleImpl; + emitter: EventEmitter; + } > = new Map(); } -export class SubscriptionHandleImpl< - DBView = any, - Reducers = any, - SetReducerFlags = any, -> { +export class SubscriptionHandleImpl { #queryId: number; #unsubscribeCalled: boolean = false; #endedState: boolean = false; @@ -146,25 +135,14 @@ export class SubscriptionHandleImpl< new EventEmitter(); constructor( - private db: DbConnectionImpl, + private db: DbConnectionImpl, querySql: string[], - onApplied?: ( - ctx: SubscriptionEventContextInterface - ) => void, - onError?: ( - ctx: ErrorContextInterface, - error: Error - ) => void + onApplied?: (ctx: SubscriptionEventContextInterface) => void, + onError?: (ctx: ErrorContextInterface, error: Error) => void ) { this.#emitter.on( 'applied', - ( - ctx: SubscriptionEventContextInterface< - DBView, - Reducers, - SetReducerFlags - > - ) => { + (ctx: SubscriptionEventContextInterface) => { this.#activeState = true; if (onApplied) { onApplied(ctx); @@ -173,10 +151,7 @@ export class SubscriptionHandleImpl< ); this.#emitter.on( 'error', - ( - ctx: ErrorContextInterface, - error: Error - ) => { + (ctx: ErrorContextInterface, error: Error) => { this.#activeState = false; this.#endedState = true; if (onError) { @@ -200,13 +175,7 @@ export class SubscriptionHandleImpl< this.db.unregisterSubscription(this.#queryId); this.#emitter.on( 'end', - ( - _ctx: SubscriptionEventContextInterface< - DBView, - Reducers, - SetReducerFlags - > - ) => { + (_ctx: SubscriptionEventContextInterface) => { this.#endedState = true; this.#activeState = false; } @@ -224,9 +193,7 @@ export class SubscriptionHandleImpl< * @param onEnd - Callback to run upon successful unsubscribe. */ unsubscribeThen( - onEnd: ( - ctx: SubscriptionEventContextInterface - ) => void + onEnd: (ctx: SubscriptionEventContextInterface) => void ): void { if (this.#endedState) { throw new Error('Subscription has already ended'); @@ -238,13 +205,7 @@ export class SubscriptionHandleImpl< this.db.unregisterSubscription(this.#queryId); this.#emitter.on( 'end', - ( - ctx: SubscriptionEventContextInterface< - DBView, - Reducers, - SetReducerFlags - > - ) => { + (ctx: SubscriptionEventContextInterface) => { this.#endedState = true; this.#activeState = false; onEnd(ctx); diff --git a/crates/bindings-typescript/src/sdk/table_cache.ts b/crates/bindings-typescript/src/sdk/table_cache.ts index dc9fce02431..abc4fb147d5 100644 --- a/crates/bindings-typescript/src/sdk/table_cache.ts +++ b/crates/bindings-typescript/src/sdk/table_cache.ts @@ -1,9 +1,12 @@ import { EventEmitter } from './event_emitter.ts'; -import type { TableRuntimeTypeInfo } from './spacetime_module.ts'; import { stdbLogger } from './logger.ts'; import type { ComparablePrimitive } from '../'; -import type { EventContextInterface } from './index.ts'; +import type { EventContextInterface, TableDefForTableName } from './index.ts'; +import type { RowType, UntypedTableDef } from '../lib/table.ts'; +import type { ClientTableCoreImplementable } from './client_table.ts'; +import type { UntypedRemoteModule } from './spacetime_module.ts'; +import type { TableNamesOf } from '../lib/schema.ts'; export type Operation< RowType extends Record = Record, @@ -15,11 +18,9 @@ export type Operation< row: RowType; }; -export type TableUpdate< - RowType extends Record = Record, -> = { +export type TableUpdate = { tableName: string; - operations: Operation[]; + operations: Operation>[]; }; export type PendingCallback = { @@ -27,14 +28,20 @@ export type PendingCallback = { table: string; cb: () => void; }; + /** * Builder to generate calls to query a `table` in the database */ export class TableCache< - RowType extends Record = Record, -> { - private rows: Map; - private tableTypeInfo: TableRuntimeTypeInfo; + RemoteModule extends UntypedRemoteModule, + TableName extends TableNamesOf, +> implements ClientTableCoreImplementable +{ + private rows: Map< + ComparablePrimitive, + [RowType>, number] + >; + private tableDef: TableDefForTableName; private emitter: EventEmitter<'insert' | 'delete' | 'update'>; /** @@ -43,8 +50,8 @@ export class TableCache< * @param primaryKey column name designated as `#[primarykey]` * @param entityClass the entityClass */ - constructor(tableTypeInfo: TableRuntimeTypeInfo) { - this.tableTypeInfo = tableTypeInfo; + constructor(tableDef: TableDefForTableName) { + this.tableDef = tableDef; this.rows = new Map(); this.emitter = new EventEmitter(); } @@ -52,30 +59,66 @@ export class TableCache< /** * @returns number of rows in the table */ - count(): number { - return this.rows.size; + count(): bigint { + return BigInt(this.rows.size); } /** * @returns The values of the rows in the table */ - iter(): RowType[] { - return Array.from(this.rows.values()).map(([row]) => row); + iter(): IterableIterator< + RowType> + > { + function* generator( + rows: Map< + ComparablePrimitive, + [RowType>, number] + > + ): IterableIterator< + RowType> + > { + for (const [row] of rows.values()) { + yield row; + } + } + return generator(this.rows); + } + + /** + * Allows iteration over the rows in the table + * @returns An iterator over the rows in the table + */ + [Symbol.iterator](): IterableIterator< + RowType> + > { + return this.iter(); } applyOperations = ( - operations: Operation[], - ctx: EventContextInterface + operations: Operation< + RowType> + >[], + ctx: EventContextInterface ): PendingCallback[] => { const pendingCallbacks: PendingCallback[] = []; - if (this.tableTypeInfo.primaryKeyInfo !== undefined) { + // TODO: performance + const hasPrimaryKey = Object.values(this.tableDef.columns).some( + col => col.columnMetadata.isPrimaryKey === true + ); + if (hasPrimaryKey) { const insertMap = new Map< ComparablePrimitive, - [Operation, number] + [ + Operation>>, + number, + ] >(); const deleteMap = new Map< ComparablePrimitive, - [Operation, number] + [ + Operation>>, + number, + ] >(); for (const op of operations) { if (op.type === 'insert') { @@ -136,9 +179,9 @@ export class TableCache< }; update = ( - ctx: EventContextInterface, + ctx: EventContextInterface, rowId: ComparablePrimitive, - newRow: RowType, + newRow: RowType>, refCountDelta: number = 0 ): PendingCallback | undefined => { const existingEntry = this.rows.get(rowId); @@ -146,7 +189,7 @@ export class TableCache< // TODO: this should throw an error and kill the connection. stdbLogger( 'error', - `Updating a row that was not present in the cache. Table: ${this.tableTypeInfo.tableName}, RowId: ${rowId}` + `Updating a row that was not present in the cache. Table: ${this.tableDef.name}, RowId: ${rowId}` ); return undefined; } @@ -155,7 +198,7 @@ export class TableCache< if (previousCount + refCountDelta <= 0) { stdbLogger( 'error', - `Negative reference count for in table ${this.tableTypeInfo.tableName} row ${rowId} (${previousCount} + ${refCountDelta})` + `Negative reference count for in table ${this.tableDef.name} row ${rowId} (${previousCount} + ${refCountDelta})` ); return undefined; } @@ -164,11 +207,11 @@ export class TableCache< if (previousCount === 0) { stdbLogger( 'error', - `Updating a row id in table ${this.tableTypeInfo.tableName} which was not present in the cache (rowId: ${rowId})` + `Updating a row id in table ${this.tableDef.name} which was not present in the cache (rowId: ${rowId})` ); return { type: 'insert', - table: this.tableTypeInfo.tableName, + table: this.tableDef.name, cb: () => { this.emitter.emit('insert', ctx, newRow); }, @@ -176,7 +219,7 @@ export class TableCache< } return { type: 'update', - table: this.tableTypeInfo.tableName, + table: this.tableDef.name, cb: () => { this.emitter.emit('update', ctx, oldRow, newRow); }, @@ -184,8 +227,10 @@ export class TableCache< }; insert = ( - ctx: EventContextInterface, - operation: Operation, + ctx: EventContextInterface, + operation: Operation< + RowType> + >, count: number = 1 ): PendingCallback | undefined => { const [_, previousCount] = this.rows.get(operation.rowId) || [ @@ -196,7 +241,7 @@ export class TableCache< if (previousCount === 0) { return { type: 'insert', - table: this.tableTypeInfo.tableName, + table: this.tableDef.name, cb: () => { this.emitter.emit('insert', ctx, operation.row); }, @@ -207,8 +252,10 @@ export class TableCache< }; delete = ( - ctx: EventContextInterface, - operation: Operation, + ctx: EventContextInterface, + operation: Operation< + RowType> + >, count: number = 1 ): PendingCallback | undefined => { const [_, previousCount] = this.rows.get(operation.rowId) || [ @@ -226,7 +273,7 @@ export class TableCache< this.rows.delete(operation.rowId); return { type: 'delete', - table: this.tableTypeInfo.tableName, + table: this.tableDef.name, cb: () => { this.emitter.emit('delete', ctx, operation.row); }, @@ -240,7 +287,7 @@ export class TableCache< * Register a callback for when a row is newly inserted into the database. * * ```ts - * User.onInsert((user, reducerEvent) => { + * ctx.db.user.onInsert((reducerEvent, user) => { * if (reducerEvent) { * console.log("New user on reducer", reducerEvent, user); * } else { @@ -251,8 +298,11 @@ export class TableCache< * * @param cb Callback to be called when a new row is inserted */ - onInsert = ( - cb: (ctx: EventContext, row: RowType) => void + onInsert = ( + cb: ( + ctx: EventContextInterface, + row: RowType> + ) => void ): void => { this.emitter.on('insert', cb); }; @@ -261,7 +311,7 @@ export class TableCache< * Register a callback for when a row is deleted from the database. * * ```ts - * User.onDelete((user, reducerEvent) => { + * ctx.db.user.onDelete((reducerEvent, user) => { * if (reducerEvent) { * console.log("Deleted user on reducer", reducerEvent, user); * } else { @@ -272,8 +322,11 @@ export class TableCache< * * @param cb Callback to be called when a new row is inserted */ - onDelete = ( - cb: (ctx: EventContext, row: RowType) => void + onDelete = ( + cb: ( + ctx: EventContextInterface, + row: RowType> + ) => void ): void => { this.emitter.on('delete', cb); }; @@ -282,7 +335,7 @@ export class TableCache< * Register a callback for when a row is updated into the database. * * ```ts - * User.onInsert((user, reducerEvent) => { + * ctx.db.user.onInsert((reducerEvent, oldUser, user) => { * if (reducerEvent) { * console.log("Updated user on reducer", reducerEvent, user); * } else { @@ -293,8 +346,12 @@ export class TableCache< * * @param cb Callback to be called when a new row is inserted */ - onUpdate = ( - cb: (ctx: EventContext, oldRow: RowType, row: RowType) => void + onUpdate = ( + cb: ( + ctx: EventContextInterface, + oldRow: RowType>, + row: RowType> + ) => void ): void => { this.emitter.on('update', cb); }; @@ -304,8 +361,11 @@ export class TableCache< * * @param cb Callback to be removed */ - removeOnInsert = ( - cb: (ctx: EventContext, row: RowType) => void + removeOnInsert = ( + cb: ( + ctx: EventContextInterface, + row: RowType> + ) => void ): void => { this.emitter.off('insert', cb); }; @@ -315,8 +375,11 @@ export class TableCache< * * @param cb Callback to be removed */ - removeOnDelete = ( - cb: (ctx: EventContext, row: RowType) => void + removeOnDelete = ( + cb: ( + ctx: EventContextInterface, + row: RowType> + ) => void ): void => { this.emitter.off('delete', cb); }; @@ -326,8 +389,12 @@ export class TableCache< * * @param cb Callback to be removed */ - removeOnUpdate = ( - cb: (ctx: EventContext, oldRow: RowType, row: RowType) => void + removeOnUpdate = ( + cb: ( + ctx: EventContextInterface, + oldRow: RowType>, + row: RowType> + ) => void ): void => { this.emitter.off('update', cb); }; diff --git a/crates/bindings-typescript/src/sdk/table_handle.ts b/crates/bindings-typescript/src/sdk/table_handle.ts deleted file mode 100644 index a648be11325..00000000000 --- a/crates/bindings-typescript/src/sdk/table_handle.ts +++ /dev/null @@ -1,12 +0,0 @@ -export type TableHandle = { - /** Phantom table name */ - readonly tableName?: TableName; -}; - -export type TableNamesFromDb = Db extends object - ? { - [K in keyof Db]: Db[K] extends TableHandle - ? TableName - : never; - }[keyof Db] - : never; diff --git a/crates/bindings-typescript/src/sdk/websocket_test_adapter.ts b/crates/bindings-typescript/src/sdk/websocket_test_adapter.ts index fc5a7255d93..58f1861603a 100644 --- a/crates/bindings-typescript/src/sdk/websocket_test_adapter.ts +++ b/crates/bindings-typescript/src/sdk/websocket_test_adapter.ts @@ -1,5 +1,5 @@ -import { AlgebraicType, BinaryWriter } from '../'; -import { ServerMessage } from './client_api/index.ts'; +import { AlgebraicType, BinaryWriter, type Infer } from '../'; +import ServerMessage from './client_api/server_message_type'; class WebsocketTestAdapter { onclose: any; @@ -28,13 +28,9 @@ class WebsocketTestAdapter { this.onopen(); } - sendToClient(message: ServerMessage): void { + sendToClient(message: Infer): void { const writer = new BinaryWriter(1024); - AlgebraicType.serializeValue( - writer, - ServerMessage.getTypeScriptAlgebraicType(), - message - ); + AlgebraicType.serializeValue(writer, ServerMessage.algebraicType, message); const rawBytes = writer.getBuffer(); // The brotli library's `compress` is somehow broken: it returns `null` for some inputs. // See https://github.com/foliojs/brotli.js/issues/36, which is closed but not actually fixed. diff --git a/crates/bindings-typescript/src/server/db_view.ts b/crates/bindings-typescript/src/server/db_view.ts new file mode 100644 index 00000000000..25e3978c288 --- /dev/null +++ b/crates/bindings-typescript/src/server/db_view.ts @@ -0,0 +1,16 @@ +import type { UntypedSchemaDef } from '../lib/schema'; +import type { ReadonlyTable, Table } from '../lib/table'; + +/** + * A type representing a read-only database view, mapping table names to their corresponding read-only Table handles. + */ +export type ReadonlyDbView = { + readonly [Tbl in SchemaDef['tables'][number] as Tbl['accessorName']]: ReadonlyTable; +}; + +/** + * A type representing the database view, mapping table names to their corresponding Table handles. + */ +export type DbView = { + readonly [Tbl in SchemaDef['tables'][number] as Tbl['accessorName']]: Table; +}; diff --git a/crates/bindings-typescript/src/server/index.ts b/crates/bindings-typescript/src/server/index.ts index c602d704184..903bb80ec73 100644 --- a/crates/bindings-typescript/src/server/index.ts +++ b/crates/bindings-typescript/src/server/index.ts @@ -1,9 +1,11 @@ -export * from './type_builders'; -export { schema, type InferSchema } from './schema'; -export { table } from './table'; +export * from '../lib/type_builders'; +export { schema, type InferSchema } from '../lib/schema'; +export { table } from '../lib/table'; +export { reducers } from '../lib/reducers'; export * as errors from './errors'; export { SenderError } from './errors'; -export { type Reducer, type ReducerCtx } from './reducers'; +export { type Reducer, type ReducerCtx } from '../lib/reducers'; +export { type DbView } from './db_view'; import './polyfills'; // Ensure polyfills are loaded import './register_hooks'; // Ensure module hooks are registered diff --git a/crates/bindings-typescript/src/server/runtime.ts b/crates/bindings-typescript/src/server/runtime.ts index f39e6bdb034..bb364994f4d 100644 --- a/crates/bindings-typescript/src/server/runtime.ts +++ b/crates/bindings-typescript/src/server/runtime.ts @@ -15,27 +15,24 @@ import { type IndexVal, type UniqueIndex, type RangedIndex, -} from './indexes'; -import { type RowType, type Table, type TableMethods } from './table'; +} from '../lib/indexes'; +import { type RowType, type Table, type TableMethods } from '../lib/table'; import { - type DbView, type ReducerCtx, REDUCERS, type JwtClaims, type AuthCtx, type JsonObject, -} from './reducers'; -import { MODULE_DEF } from './schema'; +} from '../lib/reducers'; +import { MODULE_DEF } from '../lib/schema'; import * as _syscalls from 'spacetime:sys@1.0'; import type { u16, u32, ModuleHooks } from 'spacetime:sys@1.0'; -import { - ANON_VIEWS, - VIEWS, - type AnonymousViewCtx, - type ViewCtx, -} from './views'; -import { bsatnBaseSize } from './util'; +import type { DbView } from './db_view'; +import { toCamelCase } from '../lib/util'; +import type { Infer } from '../lib/type_builders'; +import { bsatnBaseSize } from '../lib/util'; +import { ANON_VIEWS, VIEWS, type AnonymousViewCtx, type ViewCtx } from '../lib/views'; const { freeze } = Object; @@ -182,7 +179,11 @@ class AuthCtxImpl implements AuthCtx { export const hooks: ModuleHooks = { __describe_module__() { const writer = new BinaryWriter(128); - RawModuleDef.serialize(writer, RawModuleDef.V9(MODULE_DEF)); + AlgebraicType.serializeValue( + writer, + RawModuleDef.algebraicType, + RawModuleDef.V9(MODULE_DEF) + ); return writer.getBuffer(); }, __call_reducer__(reducerId, sender, connId, timestamp, argsBuf) { @@ -265,21 +266,26 @@ function getDbView() { return DB_VIEW; } -function makeDbView(module_def: RawModuleDefV9): DbView { +function makeDbView(moduleDef: Infer): DbView { return freeze( Object.fromEntries( - module_def.tables.map(table => [ - table.name, - makeTableView(module_def.typespace, table), + moduleDef.tables.map(table => [ + toCamelCase(table.name), + makeTableView(moduleDef.typespace, table), ]) ) ); } -function makeTableView(typespace: Typespace, table: RawTableDefV9): Table { +function makeTableView( + typespace: Infer, + table: Infer +): Table { const table_id = sys.table_id_from_name(table.name); const rowType = typespace.types[table.productTypeRef]; - if (rowType.tag !== 'Product') throw 'impossible'; + if (rowType.tag !== 'Product') { + throw 'impossible'; + } const baseSize = bsatnBaseSize(typespace, rowType); @@ -386,19 +392,19 @@ function makeTableView(typespace: Typespace, table: RawTableDefV9): Table { let index: Index; if (isUnique) { - const serializeBound = (col_val: any[]): IndexScanArgs => { - if (col_val.length !== numColumns) + const serializeBound = (colVal: any[]): IndexScanArgs => { + if (colVal.length !== numColumns) throw new TypeError('wrong number of elements'); const writer = new BinaryWriter(baseSize + 1); const prefix_elems = numColumns - 1; - serializePrefix(writer, col_val, prefix_elems); + serializePrefix(writer, colVal, prefix_elems); const rstartOffset = writer.offset; writer.writeU8(0); AlgebraicType.serializeValue( writer, indexType.value.elements[numColumns - 1].algebraicType, - col_val[numColumns - 1], + colVal[numColumns - 1], typespace ); const buffer = writer.getBuffer(); @@ -407,9 +413,9 @@ function makeTableView(typespace: Typespace, table: RawTableDefV9): Table { return [prefix, prefix_elems, rstart, rstart]; }; index = { - find: (col_val: IndexVal): RowType | null => { - if (numColumns === 1) col_val = [col_val]; - const args = serializeBound(col_val); + find: (colVal: IndexVal): RowType | null => { + if (numColumns === 1) colVal = [colVal]; + const args = serializeBound(colVal); const iter = new TableIterator( sys.datastore_index_scan_range_bsatn(index_id, ...args), rowType @@ -422,9 +428,9 @@ function makeTableView(typespace: Typespace, table: RawTableDefV9): Table { ); return value; }, - delete: (col_val: IndexVal): boolean => { - if (numColumns === 1) col_val = [col_val]; - const args = serializeBound(col_val); + delete: (colVal: IndexVal): boolean => { + if (numColumns === 1) colVal = [colVal]; + const args = serializeBound(colVal); const num = sys.datastore_delete_by_index_scan_range_bsatn( index_id, ...args diff --git a/crates/bindings-typescript/src/server/schema.test-d.ts b/crates/bindings-typescript/src/server/schema.test-d.ts index 8ffc6f50656..c1846ca1716 100644 --- a/crates/bindings-typescript/src/server/schema.test-d.ts +++ b/crates/bindings-typescript/src/server/schema.test-d.ts @@ -1,6 +1,6 @@ -import { schema } from './schema'; -import { table } from './table'; -import t from './type_builders'; +import { schema } from '../lib/schema'; +import { table } from '../lib/table'; +import t from '../lib/type_builders'; const person = table( { diff --git a/crates/bindings-typescript/src/server/type_util.ts b/crates/bindings-typescript/src/server/type_util.ts deleted file mode 100644 index 4febb2c11c8..00000000000 --- a/crates/bindings-typescript/src/server/type_util.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Utility to make TS show cleaner types by flattening intersections. - */ -export type Prettify = { [K in keyof T]: T[K] } & {}; - -/** - * Helper function to sets a field in an object - */ -export type Set = Prettify< - Omit & { [K in F]: V } ->; - -/** - * Sets a field in an object - * @param x The original object - * @param t The object containing the field to set - * @returns A new object with the field set - */ -export function set( - x: T, - t: { [k in F]: V } -): Set { - return { ...x, ...t }; -} - -/** - * Helper to extract the value types from an object type - */ -export type Values = T[keyof T]; - -/** - * A helper type to collapse a tuple into a single type if it has only one element. - */ -export type CollapseTuple = A extends [infer T] ? T : A; diff --git a/crates/bindings-typescript/src/server/util.ts b/crates/bindings-typescript/src/server/util.ts deleted file mode 100644 index 78e72ec405e..00000000000 --- a/crates/bindings-typescript/src/server/util.ts +++ /dev/null @@ -1,43 +0,0 @@ -import type { AlgebraicType } from '../lib/algebraic_type'; -import type Typespace from '../lib/autogen/typespace_type'; - -export function bsatnBaseSize(typespace: Typespace, ty: AlgebraicType): number { - const assumedArrayLength = 4; - while (ty.tag === 'Ref') ty = typespace.types[ty.value]; - if (ty.tag === 'Product') { - let sum = 0; - for (const { algebraicType: elem } of ty.value.elements) { - sum += bsatnBaseSize(typespace, elem); - } - return sum; - } else if (ty.tag === 'Sum') { - let min = Infinity; - for (const { algebraicType: vari } of ty.value.variants) { - const vSize = bsatnBaseSize(typespace, vari); - if (vSize < min) min = vSize; - } - if (min === Infinity) min = 0; - return 4 + min; - } else if (ty.tag == 'Array') { - return 4 + assumedArrayLength * bsatnBaseSize(typespace, ty.value); - } - return { - String: 4 + assumedArrayLength, - Sum: 1, - Bool: 1, - I8: 1, - U8: 1, - I16: 2, - U16: 2, - I32: 4, - U32: 4, - F32: 4, - I64: 8, - U64: 8, - F64: 8, - I128: 16, - U128: 16, - I256: 32, - U256: 32, - }[ty.tag]; -} diff --git a/crates/bindings-typescript/test-app/server/src/lib.rs b/crates/bindings-typescript/test-app/server/src/lib.rs index 4fbd2086d21..853c91632e1 100644 --- a/crates/bindings-typescript/test-app/server/src/lib.rs +++ b/crates/bindings-typescript/test-app/server/src/lib.rs @@ -3,7 +3,9 @@ use spacetimedb::{reducer, table, Identity, ReducerContext, SpacetimeType, Table #[table(name = player, public)] pub struct Player { #[primary_key] - owner_id: String, + #[auto_inc] + id: u32, + user_id: Identity, name: String, location: Point, } @@ -23,15 +25,23 @@ pub struct User { #[table(name = unindexed_player, public)] pub struct UnindexedPlayer { - owner_id: String, + #[primary_key] + #[auto_inc] + id: u32, + owner_id: Identity, name: String, location: Point, } #[reducer] pub fn create_player(ctx: &ReducerContext, name: String, location: Point) { + ctx.db.user().insert(User { + identity: ctx.sender, + username: name.clone(), + }); ctx.db.player().insert(Player { - owner_id: ctx.sender.to_hex().to_string(), + id: 0, + user_id: ctx.sender, name, location, }); diff --git a/crates/bindings-typescript/test-app/src/App.tsx b/crates/bindings-typescript/test-app/src/App.tsx index b8ee5f08b50..720504f78d8 100644 --- a/crates/bindings-typescript/test-app/src/App.tsx +++ b/crates/bindings-typescript/test-app/src/App.tsx @@ -1,21 +1,32 @@ -import { DbConnection, Player } from './module_bindings'; +import { tables, reducers } from './module_bindings'; import { useEffect } from 'react'; import './App.css'; -import { useSpacetimeDB, useTable } from '../../src/react'; +import { + eq, + useReducer, + useSpacetimeDB, + useTable, + where, +} from '../../src/react'; + +function getRandomInt(max: number) { + return Math.floor(Math.random() * max); +} function App() { - const connection = useSpacetimeDB(); - const players = useTable('player', { - onInsert: player => { - console.log(player); + const connection = useSpacetimeDB(); + const players = useTable(tables.player, where(eq('name', 'Hello')), { + onInsert: row => { + console.log('Player inserted:', row); }, }); + const createPlayer = useReducer(reducers.createPlayer); useEffect(() => { setTimeout(() => { - console.log(Array.from(players.rows)); + console.log(Array.from(players)); }, 5000); - }, [connection, players.rows]); + }, [connection, players]); return (
@@ -23,12 +34,24 @@ function App() {

{connection.identity?.toHexString()}

+
+ {Array.from(players).map((player, i) => ( +
+ {player.name} - ({player.location.x}, {player.location.y}) +
+ ))} +
); } diff --git a/crates/bindings-typescript/test-app/src/main.tsx b/crates/bindings-typescript/test-app/src/main.tsx index fcb7271984b..028148b3eb7 100644 --- a/crates/bindings-typescript/test-app/src/main.tsx +++ b/crates/bindings-typescript/test-app/src/main.tsx @@ -12,8 +12,8 @@ const connectionBuilder = DbConnection.builder() .onDisconnect(() => { console.log('disconnected'); }) - .onConnectError(() => { - console.log('client_error'); + .onConnectError((ctx, err) => { + console.log('client_error: ', err); }) .onConnect((conn, identity, _token) => { console.log( @@ -22,10 +22,7 @@ const connectionBuilder = DbConnection.builder() ); conn.subscriptionBuilder().subscribe('SELECT * FROM player'); - }) - .withToken( - 'eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIwMUpCQTBYRzRESFpIWUdQQk5GRFk5RDQ2SiIsImlzcyI6Imh0dHBzOi8vYXV0aC5zdGFnaW5nLnNwYWNldGltZWRiLmNvbSIsImlhdCI6MTczMDgwODUwNSwiZXhwIjoxNzkzODgwNTA1fQ.kGM4HGX0c0twL8NJoSQowzSZa8dc2Ogc-fsvaDK7otUrcdGFsZ3KsNON2eNkFh73FER0hl55_eJStr2tgoPwfTyl_v_TqkY45iUOUlLmHfB-X42cMzpE7PXbR_PKYcp-P-Wa4jGtVl4oF7CvdGKxlhIYEk3e0ElQlA9ThnZN4IEciYV0vwAXGqbaO9SOG8jbrmlmfN7oKgl02EgpodEAHTrnB2mD1qf1YyOw7_9n_EkxJxWLkJf9-nFCVRrbfSLqSJBeE6OKNAu2VLLYrSFE7GkVXNCFVugoCDM2oVJogX75AgzWimrp75QRmLsXbvB-YvvRkQ8Gfb2RZnqCj9kiYg' - ); + }); ReactDOM.createRoot(document.getElementById('root')!).render( diff --git a/crates/bindings-typescript/test-app/src/module_bindings/create_player_reducer.ts b/crates/bindings-typescript/test-app/src/module_bindings/create_player_reducer.ts index 494f9eb5d1e..368f9ad64f8 100644 --- a/crates/bindings-typescript/test-app/src/module_bindings/create_player_reducer.ts +++ b/crates/bindings-typescript/test-app/src/module_bindings/create_player_reducer.ts @@ -4,74 +4,17 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -import { Point } from './point_type'; -// Mark import as potentially unused -declare type __keep_Point = Point; +import Point from './point_type'; -export type CreatePlayer = { - name: string; - location: Point; -}; -let _cached_CreatePlayer_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const CreatePlayer = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_CreatePlayer_type_value) return _cached_CreatePlayer_type_value; - _cached_CreatePlayer_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_CreatePlayer_type_value.value.elements.push( - { name: 'name', algebraicType: __AlgebraicTypeValue.String }, - { name: 'location', algebraicType: Point.getTypeScriptAlgebraicType() } - ); - return _cached_CreatePlayer_type_value; - }, - - serialize(writer: __BinaryWriter, value: CreatePlayer): void { - __AlgebraicTypeValue.serializeValue( - writer, - CreatePlayer.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): CreatePlayer { - return __AlgebraicTypeValue.deserializeValue( - reader, - CreatePlayer.getTypeScriptAlgebraicType() - ); +export default { + name: __t.string(), + get location() { + return Point; }, }; - -export default CreatePlayer; diff --git a/crates/bindings-typescript/test-app/src/module_bindings/index.ts b/crates/bindings-typescript/test-app/src/module_bindings/index.ts index 104b8f6c14c..24ce38c5708 100644 --- a/crates/bindings-typescript/test-app/src/module_bindings/index.ts +++ b/crates/bindings-typescript/test-app/src/module_bindings/index.ts @@ -1,245 +1,122 @@ // THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE // WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. -// This was generated using ../../../src/index cli version 1.5.0 (commit 5bfc84351742a6a8dc717b6c0011946f2d1b632d). +// This was generated using ../../../src/index cli version 1.7.0 (commit cb16789be729954a7c47b87fb40b35baa0bd1029). /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, DbConnectionBuilder as __DbConnectionBuilder, DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, + TypeBuilder as __TypeBuilder, + convertToAccessorMap as __convertToAccessorMap, + reducerSchema as __reducerSchema, + reducers as __reducers, + schema as __schema, + t as __t, + table as __table, + type AlgebraicTypeType as __AlgebraicTypeType, + type DbConnectionConfig as __DbConnectionConfig, type ErrorContextInterface as __ErrorContextInterface, type Event as __Event, type EventContextInterface as __EventContextInterface, + type Infer as __Infer, type ReducerEventContextInterface as __ReducerEventContextInterface, + type RemoteModule as __RemoteModule, type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, } from '../../../src/index'; // Import and reexport all reducer arg types -import { CreatePlayer } from './create_player_reducer.ts'; +import CreatePlayer from './create_player_reducer'; export { CreatePlayer }; // Import and reexport all table handle types -import { PlayerTableHandle } from './player_table.ts'; -export { PlayerTableHandle }; -import { UnindexedPlayerTableHandle } from './unindexed_player_table.ts'; -export { UnindexedPlayerTableHandle }; -import { UserTableHandle } from './user_table.ts'; -export { UserTableHandle }; +import PlayerRow from './player_table'; +export { PlayerRow }; +import UnindexedPlayerRow from './unindexed_player_table'; +export { UnindexedPlayerRow }; +import UserRow from './user_table'; +export { UserRow }; // Import and reexport all types -import { Player } from './player_type.ts'; +import Player from './player_type'; export { Player }; -import { Point } from './point_type.ts'; +import Point from './point_type'; export { Point }; -import { UnindexedPlayer } from './unindexed_player_type.ts'; +import UnindexedPlayer from './unindexed_player_type'; export { UnindexedPlayer }; -import { User } from './user_type.ts'; +import User from './user_type'; export { User }; -const REMOTE_MODULE = { - tables: { - player: { - tableName: 'player' as const, - rowType: Player.getTypeScriptAlgebraicType(), - primaryKey: 'ownerId', - primaryKeyInfo: { - colName: 'ownerId', - colType: ( - Player.getTypeScriptAlgebraicType() as __AlgebraicTypeVariants.Product - ).value.elements[0].algebraicType, - }, - }, - unindexed_player: { - tableName: 'unindexed_player' as const, - rowType: UnindexedPlayer.getTypeScriptAlgebraicType(), +const tablesSchema = __schema( + __table( + { + name: 'player', + indexes: [], }, - user: { - tableName: 'user' as const, - rowType: User.getTypeScriptAlgebraicType(), - primaryKey: 'identity', - primaryKeyInfo: { - colName: 'identity', - colType: ( - User.getTypeScriptAlgebraicType() as __AlgebraicTypeVariants.Product - ).value.elements[0].algebraicType, - }, + PlayerRow + ), + __table( + { + name: 'unindexed_player', + indexes: [], }, - }, - reducers: { - create_player: { - reducerName: 'create_player', - argsType: CreatePlayer.getTypeScriptAlgebraicType(), + UnindexedPlayerRow + ), + __table( + { + name: 'user', + indexes: [], }, - }, - versionInfo: { - cliVersion: '1.5.0', - }, - // Constructors which are used by the DbConnectionImpl to - // extract type information from the generated RemoteModule. - // - // NOTE: This is not strictly necessary for `eventContextConstructor` because - // all we do is build a TypeScript object which we could have done inside the - // SDK, but if in the future we wanted to create a class this would be - // necessary because classes have methods, so we'll keep it. - eventContextConstructor: ( - imp: __DbConnectionImpl, - event: __Event - ) => { - return { - ...(imp as DbConnection), - event, - }; - }, - dbViewConstructor: (imp: __DbConnectionImpl) => { - return new RemoteTables(imp); - }, - reducersConstructor: ( - imp: __DbConnectionImpl, - setReducerFlags: SetReducerFlags - ) => { - return new RemoteReducers(imp, setReducerFlags); - }, - setReducerFlagsConstructor: () => { - return new SetReducerFlags(); - }, -}; + UserRow + ) +); -// A type representing all the possible variants of a reducer. -export type Reducer = never | { name: 'CreatePlayer'; args: CreatePlayer }; +const reducersSchema = __reducers( + __reducerSchema('create_player', CreatePlayer) +); -export class RemoteReducers { - constructor( - private connection: __DbConnectionImpl, - private setCallReducerFlags: SetReducerFlags - ) {} - - createPlayer(name: string, location: Point) { - const __args = { name, location }; - let __writer = new __BinaryWriter(1024); - CreatePlayer.serialize(__writer, __args); - let __argsBuffer = __writer.getBuffer(); - this.connection.callReducer( - 'create_player', - __argsBuffer, - this.setCallReducerFlags.createPlayerFlags - ); - } - - onCreatePlayer( - callback: (ctx: ReducerEventContext, name: string, location: Point) => void - ) { - this.connection.onReducer('create_player', callback); - } - - removeOnCreatePlayer( - callback: (ctx: ReducerEventContext, name: string, location: Point) => void - ) { - this.connection.offReducer('create_player', callback); - } -} - -export class SetReducerFlags { - createPlayerFlags: __CallReducerFlags = 'FullUpdate'; - createPlayer(flags: __CallReducerFlags) { - this.createPlayerFlags = flags; - } -} - -export class RemoteTables { - constructor(private connection: __DbConnectionImpl) {} - - get player(): PlayerTableHandle<'player'> { - // clientCache is a private property - return new PlayerTableHandle( - ( - this.connection as unknown as { clientCache: __ClientCache } - ).clientCache.getOrCreateTable(REMOTE_MODULE.tables.player) - ); - } +const REMOTE_MODULE = { + versionInfo: { + cliVersion: '1.7.0' as const, + }, + tables: tablesSchema.schemaType.tables, + reducers: reducersSchema.reducersType.reducers, +} satisfies __RemoteModule< + typeof tablesSchema.schemaType, + typeof reducersSchema.reducersType +>; - get unindexedPlayer(): UnindexedPlayerTableHandle<'unindexed_player'> { - // clientCache is a private property - return new UnindexedPlayerTableHandle( - ( - this.connection as unknown as { clientCache: __ClientCache } - ).clientCache.getOrCreateTable( - REMOTE_MODULE.tables.unindexed_player - ) - ); - } +export const tables = __convertToAccessorMap(tablesSchema.schemaType.tables); +export const reducers = __convertToAccessorMap( + reducersSchema.reducersType.reducers +); - get user(): UserTableHandle<'user'> { - // clientCache is a private property - return new UserTableHandle( - ( - this.connection as unknown as { clientCache: __ClientCache } - ).clientCache.getOrCreateTable(REMOTE_MODULE.tables.user) - ); - } -} +export type EventContext = __EventContextInterface; +export type ReducerEventContext = __ReducerEventContextInterface< + typeof REMOTE_MODULE +>; +export type SubscriptionEventContext = __SubscriptionEventContextInterface< + typeof REMOTE_MODULE +>; +export type ErrorContext = __ErrorContextInterface; export class SubscriptionBuilder extends __SubscriptionBuilderImpl< - RemoteTables, - RemoteReducers, - SetReducerFlags + typeof REMOTE_MODULE > {} -export class DbConnection extends __DbConnectionImpl< - RemoteTables, - RemoteReducers, - SetReducerFlags -> { - static builder = (): __DbConnectionBuilder< - DbConnection, - ErrorContext, - SubscriptionEventContext - > => { - return new __DbConnectionBuilder< - DbConnection, - ErrorContext, - SubscriptionEventContext - >(REMOTE_MODULE, (imp: __DbConnectionImpl) => imp as DbConnection); +export class DbConnectionBuilder extends __DbConnectionBuilder {} + +export class DbConnection extends __DbConnectionImpl { + static builder = (): DbConnectionBuilder => { + return new DbConnectionBuilder( + REMOTE_MODULE, + (config: __DbConnectionConfig) => + new DbConnection(config) + ); }; subscriptionBuilder = (): SubscriptionBuilder => { return new SubscriptionBuilder(this); }; } - -export type EventContext = __EventContextInterface< - RemoteTables, - RemoteReducers, - SetReducerFlags, - Reducer ->; -export type ReducerEventContext = __ReducerEventContextInterface< - RemoteTables, - RemoteReducers, - SetReducerFlags, - Reducer ->; -export type SubscriptionEventContext = __SubscriptionEventContextInterface< - RemoteTables, - RemoteReducers, - SetReducerFlags ->; -export type ErrorContext = __ErrorContextInterface< - RemoteTables, - RemoteReducers, - SetReducerFlags ->; diff --git a/crates/bindings-typescript/test-app/src/module_bindings/player_table.ts b/crates/bindings-typescript/test-app/src/module_bindings/player_table.ts index 63a846fa7f6..ee98682e78b 100644 --- a/crates/bindings-typescript/test-app/src/module_bindings/player_table.ts +++ b/crates/bindings-typescript/test-app/src/module_bindings/player_table.ts @@ -4,119 +4,18 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -import { Player } from './player_type'; -import { Point } from './point_type'; -// Mark import as potentially unused -declare type __keep_Point = Point; - -import { - type EventContext, - type Reducer, - RemoteReducers, - RemoteTables, -} from '.'; -declare type __keep = [EventContext, Reducer, RemoteReducers, RemoteTables]; - -/** - * Table handle for the table `player`. - * - * Obtain a handle from the [`player`] property on [`RemoteTables`], - * like `ctx.db.player`. - * - * Users are encouraged not to explicitly reference this type, - * but to directly chain method calls, - * like `ctx.db.player.on_insert(...)`. - */ -export class PlayerTableHandle - implements __TableHandle -{ - // phantom type to track the table name - readonly tableName!: TableName; - tableCache: __TableCache; - - constructor(tableCache: __TableCache) { - this.tableCache = tableCache; - } - - count(): number { - return this.tableCache.count(); - } - - iter(): Iterable { - return this.tableCache.iter(); - } - /** - * Access to the `ownerId` unique index on the table `player`, - * which allows point queries on the field of the same name - * via the [`PlayerOwnerIdUnique.find`] method. - * - * Users are encouraged not to explicitly reference this type, - * but to directly chain method calls, - * like `ctx.db.player.ownerId().find(...)`. - * - * Get a handle on the `ownerId` unique index on the table `player`. - */ - ownerId = { - // Find the subscribed row whose `ownerId` column value is equal to `col_val`, - // if such a row is present in the client cache. - find: (col_val: string): Player | undefined => { - for (let row of this.tableCache.iter()) { - if (__deepEqual(row.ownerId, col_val)) { - return row; - } - } - }, - }; - - onInsert = (cb: (ctx: EventContext, row: Player) => void) => { - return this.tableCache.onInsert(cb); - }; - - removeOnInsert = (cb: (ctx: EventContext, row: Player) => void) => { - return this.tableCache.removeOnInsert(cb); - }; - - onDelete = (cb: (ctx: EventContext, row: Player) => void) => { - return this.tableCache.onDelete(cb); - }; - - removeOnDelete = (cb: (ctx: EventContext, row: Player) => void) => { - return this.tableCache.removeOnDelete(cb); - }; - - // Updates are only defined for tables with primary keys. - onUpdate = ( - cb: (ctx: EventContext, oldRow: Player, newRow: Player) => void - ) => { - return this.tableCache.onUpdate(cb); - }; - - removeOnUpdate = ( - cb: (ctx: EventContext, onRow: Player, newRow: Player) => void - ) => { - return this.tableCache.removeOnUpdate(cb); - }; -} +import Point from './point_type'; + +export default __t.row({ + id: __t.u32(), + userId: __t.identity(), + name: __t.string(), + get location() { + return Point; + }, +}); diff --git a/crates/bindings-typescript/test-app/src/module_bindings/player_type.ts b/crates/bindings-typescript/test-app/src/module_bindings/player_type.ts index 4bafe1fb1e4..596b73f7d06 100644 --- a/crates/bindings-typescript/test-app/src/module_bindings/player_type.ts +++ b/crates/bindings-typescript/test-app/src/module_bindings/player_type.ts @@ -4,73 +4,18 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -import { Point } from './point_type'; -// Mark import as potentially unused -declare type __keep_Point = Point; +import Point from './point_type'; -export type Player = { - ownerId: string; - name: string; - location: Point; -}; -let _cached_Player_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const Player = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_Player_type_value) return _cached_Player_type_value; - _cached_Player_type_value = __AlgebraicTypeValue.Product({ elements: [] }); - _cached_Player_type_value.value.elements.push( - { name: 'ownerId', algebraicType: __AlgebraicTypeValue.String }, - { name: 'name', algebraicType: __AlgebraicTypeValue.String }, - { name: 'location', algebraicType: Point.getTypeScriptAlgebraicType() } - ); - return _cached_Player_type_value; - }, - - serialize(writer: __BinaryWriter, value: Player): void { - __AlgebraicTypeValue.serializeValue( - writer, - Player.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('Player', { + id: __t.u32(), + userId: __t.identity(), + name: __t.string(), + get location() { + return Point; }, - - deserialize(reader: __BinaryReader): Player { - return __AlgebraicTypeValue.deserializeValue( - reader, - Player.getTypeScriptAlgebraicType() - ); - }, -}; - -export default Player; +}); diff --git a/crates/bindings-typescript/test-app/src/module_bindings/point_type.ts b/crates/bindings-typescript/test-app/src/module_bindings/point_type.ts index 9bd08a301a1..e65bc722fff 100644 --- a/crates/bindings-typescript/test-app/src/module_bindings/point_type.ts +++ b/crates/bindings-typescript/test-app/src/module_bindings/point_type.ts @@ -4,68 +4,13 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -export type Point = { - x: number; - y: number; -}; -let _cached_Point_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const Point = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_Point_type_value) return _cached_Point_type_value; - _cached_Point_type_value = __AlgebraicTypeValue.Product({ elements: [] }); - _cached_Point_type_value.value.elements.push( - { name: 'x', algebraicType: __AlgebraicTypeValue.U16 }, - { name: 'y', algebraicType: __AlgebraicTypeValue.U16 } - ); - return _cached_Point_type_value; - }, - - serialize(writer: __BinaryWriter, value: Point): void { - __AlgebraicTypeValue.serializeValue( - writer, - Point.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): Point { - return __AlgebraicTypeValue.deserializeValue( - reader, - Point.getTypeScriptAlgebraicType() - ); - }, -}; - -export default Point; +export default __t.object('Point', { + x: __t.u16(), + y: __t.u16(), +}); diff --git a/crates/bindings-typescript/test-app/src/module_bindings/unindexed_player_table.ts b/crates/bindings-typescript/test-app/src/module_bindings/unindexed_player_table.ts index eaff291a344..96f056baeb7 100644 --- a/crates/bindings-typescript/test-app/src/module_bindings/unindexed_player_table.ts +++ b/crates/bindings-typescript/test-app/src/module_bindings/unindexed_player_table.ts @@ -4,84 +4,18 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -import { UnindexedPlayer } from './unindexed_player_type'; -import { Point } from './point_type'; -// Mark import as potentially unused -declare type __keep_Point = Point; - -import { - type EventContext, - type Reducer, - RemoteReducers, - RemoteTables, -} from '.'; -declare type __keep = [EventContext, Reducer, RemoteReducers, RemoteTables]; - -/** - * Table handle for the table `unindexed_player`. - * - * Obtain a handle from the [`unindexedPlayer`] property on [`RemoteTables`], - * like `ctx.db.unindexedPlayer`. - * - * Users are encouraged not to explicitly reference this type, - * but to directly chain method calls, - * like `ctx.db.unindexedPlayer.on_insert(...)`. - */ -export class UnindexedPlayerTableHandle - implements __TableHandle -{ - // phantom type to track the table name - readonly tableName!: TableName; - tableCache: __TableCache; - - constructor(tableCache: __TableCache) { - this.tableCache = tableCache; - } - - count(): number { - return this.tableCache.count(); - } - - iter(): Iterable { - return this.tableCache.iter(); - } - - onInsert = (cb: (ctx: EventContext, row: UnindexedPlayer) => void) => { - return this.tableCache.onInsert(cb); - }; - - removeOnInsert = (cb: (ctx: EventContext, row: UnindexedPlayer) => void) => { - return this.tableCache.removeOnInsert(cb); - }; - - onDelete = (cb: (ctx: EventContext, row: UnindexedPlayer) => void) => { - return this.tableCache.onDelete(cb); - }; - - removeOnDelete = (cb: (ctx: EventContext, row: UnindexedPlayer) => void) => { - return this.tableCache.removeOnDelete(cb); - }; -} +import Point from './point_type'; + +export default __t.row({ + id: __t.u32(), + ownerId: __t.identity(), + name: __t.string(), + get location() { + return Point; + }, +}); diff --git a/crates/bindings-typescript/test-app/src/module_bindings/unindexed_player_type.ts b/crates/bindings-typescript/test-app/src/module_bindings/unindexed_player_type.ts index 8f2545fa8be..5f717022485 100644 --- a/crates/bindings-typescript/test-app/src/module_bindings/unindexed_player_type.ts +++ b/crates/bindings-typescript/test-app/src/module_bindings/unindexed_player_type.ts @@ -4,76 +4,18 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -import { Point } from './point_type'; -// Mark import as potentially unused -declare type __keep_Point = Point; +import Point from './point_type'; -export type UnindexedPlayer = { - ownerId: string; - name: string; - location: Point; -}; -let _cached_UnindexedPlayer_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const UnindexedPlayer = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_UnindexedPlayer_type_value) - return _cached_UnindexedPlayer_type_value; - _cached_UnindexedPlayer_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_UnindexedPlayer_type_value.value.elements.push( - { name: 'ownerId', algebraicType: __AlgebraicTypeValue.String }, - { name: 'name', algebraicType: __AlgebraicTypeValue.String }, - { name: 'location', algebraicType: Point.getTypeScriptAlgebraicType() } - ); - return _cached_UnindexedPlayer_type_value; - }, - - serialize(writer: __BinaryWriter, value: UnindexedPlayer): void { - __AlgebraicTypeValue.serializeValue( - writer, - UnindexedPlayer.getTypeScriptAlgebraicType(), - value - ); +export default __t.object('UnindexedPlayer', { + id: __t.u32(), + ownerId: __t.identity(), + name: __t.string(), + get location() { + return Point; }, - - deserialize(reader: __BinaryReader): UnindexedPlayer { - return __AlgebraicTypeValue.deserializeValue( - reader, - UnindexedPlayer.getTypeScriptAlgebraicType() - ); - }, -}; - -export default UnindexedPlayer; +}); diff --git a/crates/bindings-typescript/test-app/src/module_bindings/user_table.ts b/crates/bindings-typescript/test-app/src/module_bindings/user_table.ts index 21275ac19c1..efa159d1988 100644 --- a/crates/bindings-typescript/test-app/src/module_bindings/user_table.ts +++ b/crates/bindings-typescript/test-app/src/module_bindings/user_table.ts @@ -4,113 +4,13 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -import { User } from './user_type'; -import { - type EventContext, - type Reducer, - RemoteReducers, - RemoteTables, -} from '.'; -declare type __keep = [EventContext, Reducer, RemoteReducers, RemoteTables]; - -/** - * Table handle for the table `user`. - * - * Obtain a handle from the [`user`] property on [`RemoteTables`], - * like `ctx.db.user`. - * - * Users are encouraged not to explicitly reference this type, - * but to directly chain method calls, - * like `ctx.db.user.on_insert(...)`. - */ -export class UserTableHandle - implements __TableHandle -{ - // phantom type to track the table name - readonly tableName!: TableName; - tableCache: __TableCache; - - constructor(tableCache: __TableCache) { - this.tableCache = tableCache; - } - - count(): number { - return this.tableCache.count(); - } - - iter(): Iterable { - return this.tableCache.iter(); - } - /** - * Access to the `identity` unique index on the table `user`, - * which allows point queries on the field of the same name - * via the [`UserIdentityUnique.find`] method. - * - * Users are encouraged not to explicitly reference this type, - * but to directly chain method calls, - * like `ctx.db.user.identity().find(...)`. - * - * Get a handle on the `identity` unique index on the table `user`. - */ - identity = { - // Find the subscribed row whose `identity` column value is equal to `col_val`, - // if such a row is present in the client cache. - find: (col_val: __Identity): User | undefined => { - for (let row of this.tableCache.iter()) { - if (__deepEqual(row.identity, col_val)) { - return row; - } - } - }, - }; - - onInsert = (cb: (ctx: EventContext, row: User) => void) => { - return this.tableCache.onInsert(cb); - }; - - removeOnInsert = (cb: (ctx: EventContext, row: User) => void) => { - return this.tableCache.removeOnInsert(cb); - }; - - onDelete = (cb: (ctx: EventContext, row: User) => void) => { - return this.tableCache.onDelete(cb); - }; - - removeOnDelete = (cb: (ctx: EventContext, row: User) => void) => { - return this.tableCache.removeOnDelete(cb); - }; - - // Updates are only defined for tables with primary keys. - onUpdate = (cb: (ctx: EventContext, oldRow: User, newRow: User) => void) => { - return this.tableCache.onUpdate(cb); - }; - removeOnUpdate = ( - cb: (ctx: EventContext, onRow: User, newRow: User) => void - ) => { - return this.tableCache.removeOnUpdate(cb); - }; -} +export default __t.row({ + identity: __t.identity(), + username: __t.string(), +}); diff --git a/crates/bindings-typescript/test-app/src/module_bindings/user_type.ts b/crates/bindings-typescript/test-app/src/module_bindings/user_type.ts index 6fa4066b314..be7f606145e 100644 --- a/crates/bindings-typescript/test-app/src/module_bindings/user_type.ts +++ b/crates/bindings-typescript/test-app/src/module_bindings/user_type.ts @@ -4,71 +4,13 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -export type User = { - identity: __Identity; - username: string; -}; -let _cached_User_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const User = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_User_type_value) return _cached_User_type_value; - _cached_User_type_value = __AlgebraicTypeValue.Product({ elements: [] }); - _cached_User_type_value.value.elements.push( - { - name: 'identity', - algebraicType: __AlgebraicTypeValue.createIdentityType(), - }, - { name: 'username', algebraicType: __AlgebraicTypeValue.String } - ); - return _cached_User_type_value; - }, - - serialize(writer: __BinaryWriter, value: User): void { - __AlgebraicTypeValue.serializeValue( - writer, - User.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): User { - return __AlgebraicTypeValue.deserializeValue( - reader, - User.getTypeScriptAlgebraicType() - ); - }, -}; - -export default User; +export default __t.object('User', { + identity: __t.identity(), + username: __t.string(), +}); diff --git a/crates/bindings-typescript/test-react-router-app/package.json b/crates/bindings-typescript/test-react-router-app/package.json index babf93f8200..235f719db0e 100644 --- a/crates/bindings-typescript/test-react-router-app/package.json +++ b/crates/bindings-typescript/test-react-router-app/package.json @@ -26,6 +26,7 @@ "devDependencies": { "@types/react": "^18.3.3", "@types/react-dom": "^18.3.0", + "@types/react-router-dom": "^5.3.3", "@vitejs/plugin-react": "^4.3.1", "typescript": "^5.2.2", "vite": "^7.1.5" diff --git a/crates/bindings-typescript/test-react-router-app/server/src/lib.rs b/crates/bindings-typescript/test-react-router-app/server/src/lib.rs index 799eb5f91f3..520e68eeaec 100644 --- a/crates/bindings-typescript/test-react-router-app/server/src/lib.rs +++ b/crates/bindings-typescript/test-react-router-app/server/src/lib.rs @@ -59,6 +59,7 @@ fn increment_counter(ctx: &ReducerContext) -> Result<(), String> { fn clear_counter(ctx: &ReducerContext) { for row in ctx.db.counter().iter() { ctx.db.counter().id().delete(row.id); + ctx.db.counter().insert(Counter { id: 0, count: 0 }); } for row in ctx.db.user().iter() { diff --git a/crates/bindings-typescript/test-react-router-app/src/module_bindings/clear_counter_reducer.ts b/crates/bindings-typescript/test-react-router-app/src/module_bindings/clear_counter_reducer.ts index b05311785e6..2454b459929 100644 --- a/crates/bindings-typescript/test-react-router-app/src/module_bindings/clear_counter_reducer.ts +++ b/crates/bindings-typescript/test-react-router-app/src/module_bindings/clear_counter_reducer.ts @@ -4,64 +4,10 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -export type ClearCounter = {}; -let _cached_ClearCounter_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const ClearCounter = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_ClearCounter_type_value) return _cached_ClearCounter_type_value; - _cached_ClearCounter_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_ClearCounter_type_value.value.elements.push(); - return _cached_ClearCounter_type_value; - }, - - serialize(writer: __BinaryWriter, value: ClearCounter): void { - __AlgebraicTypeValue.serializeValue( - writer, - ClearCounter.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): ClearCounter { - return __AlgebraicTypeValue.deserializeValue( - reader, - ClearCounter.getTypeScriptAlgebraicType() - ); - }, -}; - -export default ClearCounter; +export default {}; diff --git a/crates/bindings-typescript/test-react-router-app/src/module_bindings/client_connected_reducer.ts b/crates/bindings-typescript/test-react-router-app/src/module_bindings/client_connected_reducer.ts index ac7a7e2b90d..2454b459929 100644 --- a/crates/bindings-typescript/test-react-router-app/src/module_bindings/client_connected_reducer.ts +++ b/crates/bindings-typescript/test-react-router-app/src/module_bindings/client_connected_reducer.ts @@ -4,65 +4,10 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -export type ClientConnected = {}; -let _cached_ClientConnected_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const ClientConnected = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_ClientConnected_type_value) - return _cached_ClientConnected_type_value; - _cached_ClientConnected_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_ClientConnected_type_value.value.elements.push(); - return _cached_ClientConnected_type_value; - }, - - serialize(writer: __BinaryWriter, value: ClientConnected): void { - __AlgebraicTypeValue.serializeValue( - writer, - ClientConnected.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): ClientConnected { - return __AlgebraicTypeValue.deserializeValue( - reader, - ClientConnected.getTypeScriptAlgebraicType() - ); - }, -}; - -export default ClientConnected; +export default {}; diff --git a/crates/bindings-typescript/test-react-router-app/src/module_bindings/client_disconnected_reducer.ts b/crates/bindings-typescript/test-react-router-app/src/module_bindings/client_disconnected_reducer.ts index d4369a3e513..2454b459929 100644 --- a/crates/bindings-typescript/test-react-router-app/src/module_bindings/client_disconnected_reducer.ts +++ b/crates/bindings-typescript/test-react-router-app/src/module_bindings/client_disconnected_reducer.ts @@ -4,65 +4,10 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -export type ClientDisconnected = {}; -let _cached_ClientDisconnected_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const ClientDisconnected = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_ClientDisconnected_type_value) - return _cached_ClientDisconnected_type_value; - _cached_ClientDisconnected_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_ClientDisconnected_type_value.value.elements.push(); - return _cached_ClientDisconnected_type_value; - }, - - serialize(writer: __BinaryWriter, value: ClientDisconnected): void { - __AlgebraicTypeValue.serializeValue( - writer, - ClientDisconnected.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): ClientDisconnected { - return __AlgebraicTypeValue.deserializeValue( - reader, - ClientDisconnected.getTypeScriptAlgebraicType() - ); - }, -}; - -export default ClientDisconnected; +export default {}; diff --git a/crates/bindings-typescript/test-react-router-app/src/module_bindings/counter_table.ts b/crates/bindings-typescript/test-react-router-app/src/module_bindings/counter_table.ts index 6d99cb4b7c6..d492e387b23 100644 --- a/crates/bindings-typescript/test-react-router-app/src/module_bindings/counter_table.ts +++ b/crates/bindings-typescript/test-react-router-app/src/module_bindings/counter_table.ts @@ -4,115 +4,13 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -import { Counter } from './counter_type'; -import { - type EventContext, - type Reducer, - RemoteReducers, - RemoteTables, -} from '.'; -declare type __keep = [EventContext, Reducer, RemoteReducers, RemoteTables]; - -/** - * Table handle for the table `counter`. - * - * Obtain a handle from the [`counter`] property on [`RemoteTables`], - * like `ctx.db.counter`. - * - * Users are encouraged not to explicitly reference this type, - * but to directly chain method calls, - * like `ctx.db.counter.on_insert(...)`. - */ -export class CounterTableHandle - implements __TableHandle -{ - // phantom type to track the table name - readonly tableName!: TableName; - tableCache: __TableCache; - - constructor(tableCache: __TableCache) { - this.tableCache = tableCache; - } - - count(): number { - return this.tableCache.count(); - } - - iter(): Iterable { - return this.tableCache.iter(); - } - /** - * Access to the `id` unique index on the table `counter`, - * which allows point queries on the field of the same name - * via the [`CounterIdUnique.find`] method. - * - * Users are encouraged not to explicitly reference this type, - * but to directly chain method calls, - * like `ctx.db.counter.id().find(...)`. - * - * Get a handle on the `id` unique index on the table `counter`. - */ - id = { - // Find the subscribed row whose `id` column value is equal to `col_val`, - // if such a row is present in the client cache. - find: (col_val: number): Counter | undefined => { - for (let row of this.tableCache.iter()) { - if (__deepEqual(row.id, col_val)) { - return row; - } - } - }, - }; - - onInsert = (cb: (ctx: EventContext, row: Counter) => void) => { - return this.tableCache.onInsert(cb); - }; - - removeOnInsert = (cb: (ctx: EventContext, row: Counter) => void) => { - return this.tableCache.removeOnInsert(cb); - }; - - onDelete = (cb: (ctx: EventContext, row: Counter) => void) => { - return this.tableCache.onDelete(cb); - }; - - removeOnDelete = (cb: (ctx: EventContext, row: Counter) => void) => { - return this.tableCache.removeOnDelete(cb); - }; - - // Updates are only defined for tables with primary keys. - onUpdate = ( - cb: (ctx: EventContext, oldRow: Counter, newRow: Counter) => void - ) => { - return this.tableCache.onUpdate(cb); - }; - removeOnUpdate = ( - cb: (ctx: EventContext, onRow: Counter, newRow: Counter) => void - ) => { - return this.tableCache.removeOnUpdate(cb); - }; -} +export default __t.row({ + id: __t.u32(), + count: __t.u32(), +}); diff --git a/crates/bindings-typescript/test-react-router-app/src/module_bindings/counter_type.ts b/crates/bindings-typescript/test-react-router-app/src/module_bindings/counter_type.ts index 9819fbb63e3..419b8dbfe5b 100644 --- a/crates/bindings-typescript/test-react-router-app/src/module_bindings/counter_type.ts +++ b/crates/bindings-typescript/test-react-router-app/src/module_bindings/counter_type.ts @@ -4,68 +4,13 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -export type Counter = { - id: number; - count: number; -}; -let _cached_Counter_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const Counter = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_Counter_type_value) return _cached_Counter_type_value; - _cached_Counter_type_value = __AlgebraicTypeValue.Product({ elements: [] }); - _cached_Counter_type_value.value.elements.push( - { name: 'id', algebraicType: __AlgebraicTypeValue.U32 }, - { name: 'count', algebraicType: __AlgebraicTypeValue.U32 } - ); - return _cached_Counter_type_value; - }, - - serialize(writer: __BinaryWriter, value: Counter): void { - __AlgebraicTypeValue.serializeValue( - writer, - Counter.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): Counter { - return __AlgebraicTypeValue.deserializeValue( - reader, - Counter.getTypeScriptAlgebraicType() - ); - }, -}; - -export default Counter; +export default __t.object('Counter', { + id: __t.u32(), + count: __t.u32(), +}); diff --git a/crates/bindings-typescript/test-react-router-app/src/module_bindings/increment_counter_reducer.ts b/crates/bindings-typescript/test-react-router-app/src/module_bindings/increment_counter_reducer.ts index 6fe15b551af..2454b459929 100644 --- a/crates/bindings-typescript/test-react-router-app/src/module_bindings/increment_counter_reducer.ts +++ b/crates/bindings-typescript/test-react-router-app/src/module_bindings/increment_counter_reducer.ts @@ -4,65 +4,10 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -export type IncrementCounter = {}; -let _cached_IncrementCounter_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const IncrementCounter = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_IncrementCounter_type_value) - return _cached_IncrementCounter_type_value; - _cached_IncrementCounter_type_value = __AlgebraicTypeValue.Product({ - elements: [], - }); - _cached_IncrementCounter_type_value.value.elements.push(); - return _cached_IncrementCounter_type_value; - }, - - serialize(writer: __BinaryWriter, value: IncrementCounter): void { - __AlgebraicTypeValue.serializeValue( - writer, - IncrementCounter.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): IncrementCounter { - return __AlgebraicTypeValue.deserializeValue( - reader, - IncrementCounter.getTypeScriptAlgebraicType() - ); - }, -}; - -export default IncrementCounter; +export default {}; diff --git a/crates/bindings-typescript/test-react-router-app/src/module_bindings/index.ts b/crates/bindings-typescript/test-react-router-app/src/module_bindings/index.ts index 07472dc2cf0..fa3f793bdb5 100644 --- a/crates/bindings-typescript/test-react-router-app/src/module_bindings/index.ts +++ b/crates/bindings-typescript/test-react-router-app/src/module_bindings/index.ts @@ -1,298 +1,125 @@ // THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE // WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. -// This was generated using ../../../src/index cli version 1.6.0 (commit 542d26d7ffecafe93e40ac1a991c2ef2b4e4d0cb). +// This was generated using ../../../src/index cli version 1.6.0 (commit 0b0b06d5f67fecff50eb7b1c79bff5dad686f5d2). /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, DbConnectionBuilder as __DbConnectionBuilder, DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, + TypeBuilder as __TypeBuilder, + convertToAccessorMap as __convertToAccessorMap, + reducerSchema as __reducerSchema, + reducers as __reducers, + schema as __schema, + t as __t, + table as __table, + type AlgebraicTypeType as __AlgebraicTypeType, + type DbConnectionConfig as __DbConnectionConfig, type ErrorContextInterface as __ErrorContextInterface, type Event as __Event, type EventContextInterface as __EventContextInterface, + type Infer as __Infer, type ReducerEventContextInterface as __ReducerEventContextInterface, + type RemoteModule as __RemoteModule, type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, } from '../../../src/index'; // Import and reexport all reducer arg types -import { ClearCounter } from './clear_counter_reducer.ts'; +import ClearCounter from './clear_counter_reducer'; export { ClearCounter }; -import { ClientConnected } from './client_connected_reducer.ts'; +import ClientConnected from './client_connected_reducer'; export { ClientConnected }; -import { ClientDisconnected } from './client_disconnected_reducer.ts'; +import ClientDisconnected from './client_disconnected_reducer'; export { ClientDisconnected }; -import { IncrementCounter } from './increment_counter_reducer.ts'; +import IncrementCounter from './increment_counter_reducer'; export { IncrementCounter }; // Import and reexport all table handle types -import { CounterTableHandle } from './counter_table.ts'; -export { CounterTableHandle }; -import { OfflineUserTableHandle } from './offline_user_table.ts'; -export { OfflineUserTableHandle }; -import { UserTableHandle } from './user_table.ts'; -export { UserTableHandle }; +import CounterRow from './counter_table'; +export { CounterRow }; +import OfflineUserRow from './offline_user_table'; +export { OfflineUserRow }; +import UserRow from './user_table'; +export { UserRow }; // Import and reexport all types -import { Counter } from './counter_type.ts'; +import Counter from './counter_type'; export { Counter }; -import { User } from './user_type.ts'; +import User from './user_type'; export { User }; -const REMOTE_MODULE = { - tables: { - counter: { - tableName: 'counter' as const, - rowType: Counter.getTypeScriptAlgebraicType(), - primaryKey: 'id', - primaryKeyInfo: { - colName: 'id', - colType: ( - Counter.getTypeScriptAlgebraicType() as __AlgebraicTypeVariants.Product - ).value.elements[0].algebraicType, - }, - }, - offline_user: { - tableName: 'offline_user' as const, - rowType: User.getTypeScriptAlgebraicType(), - primaryKey: 'identity', - primaryKeyInfo: { - colName: 'identity', - colType: ( - User.getTypeScriptAlgebraicType() as __AlgebraicTypeVariants.Product - ).value.elements[0].algebraicType, - }, +const tablesSchema = __schema( + __table( + { + name: 'counter', + indexes: [], }, - user: { - tableName: 'user' as const, - rowType: User.getTypeScriptAlgebraicType(), - primaryKey: 'identity', - primaryKeyInfo: { - colName: 'identity', - colType: ( - User.getTypeScriptAlgebraicType() as __AlgebraicTypeVariants.Product - ).value.elements[0].algebraicType, - }, - }, - }, - reducers: { - clear_counter: { - reducerName: 'clear_counter', - argsType: ClearCounter.getTypeScriptAlgebraicType(), + CounterRow + ), + __table( + { + name: 'offline_user', + indexes: [], }, - client_connected: { - reducerName: 'client_connected', - argsType: ClientConnected.getTypeScriptAlgebraicType(), + UserRow + ), + __table( + { + name: 'user', + indexes: [], }, - client_disconnected: { - reducerName: 'client_disconnected', - argsType: ClientDisconnected.getTypeScriptAlgebraicType(), - }, - increment_counter: { - reducerName: 'increment_counter', - argsType: IncrementCounter.getTypeScriptAlgebraicType(), - }, - }, - versionInfo: { - cliVersion: '1.6.0', - }, - // Constructors which are used by the DbConnectionImpl to - // extract type information from the generated RemoteModule. - // - // NOTE: This is not strictly necessary for `eventContextConstructor` because - // all we do is build a TypeScript object which we could have done inside the - // SDK, but if in the future we wanted to create a class this would be - // necessary because classes have methods, so we'll keep it. - eventContextConstructor: ( - imp: __DbConnectionImpl, - event: __Event - ) => { - return { - ...(imp as DbConnection), - event, - }; - }, - dbViewConstructor: (imp: __DbConnectionImpl) => { - return new RemoteTables(imp); - }, - reducersConstructor: ( - imp: __DbConnectionImpl, - setReducerFlags: SetReducerFlags - ) => { - return new RemoteReducers(imp, setReducerFlags); - }, - setReducerFlagsConstructor: () => { - return new SetReducerFlags(); - }, -}; - -// A type representing all the possible variants of a reducer. -export type Reducer = - | never - | { name: 'ClearCounter'; args: ClearCounter } - | { name: 'ClientConnected'; args: ClientConnected } - | { name: 'ClientDisconnected'; args: ClientDisconnected } - | { name: 'IncrementCounter'; args: IncrementCounter }; - -export class RemoteReducers { - constructor( - private connection: __DbConnectionImpl, - private setCallReducerFlags: SetReducerFlags - ) {} - - clearCounter() { - this.connection.callReducer( - 'clear_counter', - new Uint8Array(0), - this.setCallReducerFlags.clearCounterFlags - ); - } - - onClearCounter(callback: (ctx: ReducerEventContext) => void) { - this.connection.onReducer('clear_counter', callback); - } - - removeOnClearCounter(callback: (ctx: ReducerEventContext) => void) { - this.connection.offReducer('clear_counter', callback); - } - - onClientConnected(callback: (ctx: ReducerEventContext) => void) { - this.connection.onReducer('client_connected', callback); - } - - removeOnClientConnected(callback: (ctx: ReducerEventContext) => void) { - this.connection.offReducer('client_connected', callback); - } - - onClientDisconnected(callback: (ctx: ReducerEventContext) => void) { - this.connection.onReducer('client_disconnected', callback); - } - - removeOnClientDisconnected(callback: (ctx: ReducerEventContext) => void) { - this.connection.offReducer('client_disconnected', callback); - } - - incrementCounter() { - this.connection.callReducer( - 'increment_counter', - new Uint8Array(0), - this.setCallReducerFlags.incrementCounterFlags - ); - } - - onIncrementCounter(callback: (ctx: ReducerEventContext) => void) { - this.connection.onReducer('increment_counter', callback); - } + UserRow + ) +); - removeOnIncrementCounter(callback: (ctx: ReducerEventContext) => void) { - this.connection.offReducer('increment_counter', callback); - } -} - -export class SetReducerFlags { - clearCounterFlags: __CallReducerFlags = 'FullUpdate'; - clearCounter(flags: __CallReducerFlags) { - this.clearCounterFlags = flags; - } - - incrementCounterFlags: __CallReducerFlags = 'FullUpdate'; - incrementCounter(flags: __CallReducerFlags) { - this.incrementCounterFlags = flags; - } -} +const reducersSchema = __reducers( + __reducerSchema('clear_counter', ClearCounter), + __reducerSchema('increment_counter', IncrementCounter) +); -export class RemoteTables { - constructor(private connection: __DbConnectionImpl) {} - - get counter(): CounterTableHandle<'counter'> { - // clientCache is a private property - return new CounterTableHandle( - ( - this.connection as unknown as { clientCache: __ClientCache } - ).clientCache.getOrCreateTable(REMOTE_MODULE.tables.counter) - ); - } +const REMOTE_MODULE = { + versionInfo: { + cliVersion: '1.6.0' as const, + }, + tables: tablesSchema.schemaType.tables, + reducers: reducersSchema.reducersType.reducers, +} satisfies __RemoteModule< + typeof tablesSchema.schemaType, + typeof reducersSchema.reducersType +>; - get offlineUser(): OfflineUserTableHandle<'offline_user'> { - // clientCache is a private property - return new OfflineUserTableHandle( - ( - this.connection as unknown as { clientCache: __ClientCache } - ).clientCache.getOrCreateTable(REMOTE_MODULE.tables.offline_user) - ); - } +export const tables = __convertToAccessorMap(tablesSchema.schemaType.tables); +export const reducers = __convertToAccessorMap( + reducersSchema.reducersType.reducers +); - get user(): UserTableHandle<'user'> { - // clientCache is a private property - return new UserTableHandle( - ( - this.connection as unknown as { clientCache: __ClientCache } - ).clientCache.getOrCreateTable(REMOTE_MODULE.tables.user) - ); - } -} +export type EventContext = __EventContextInterface; +export type ReducerEventContext = __ReducerEventContextInterface< + typeof REMOTE_MODULE +>; +export type SubscriptionEventContext = __SubscriptionEventContextInterface< + typeof REMOTE_MODULE +>; +export type ErrorContext = __ErrorContextInterface; export class SubscriptionBuilder extends __SubscriptionBuilderImpl< - RemoteTables, - RemoteReducers, - SetReducerFlags + typeof REMOTE_MODULE > {} -export class DbConnection extends __DbConnectionImpl< - RemoteTables, - RemoteReducers, - SetReducerFlags -> { - static builder = (): __DbConnectionBuilder< - DbConnection, - ErrorContext, - SubscriptionEventContext - > => { - return new __DbConnectionBuilder< - DbConnection, - ErrorContext, - SubscriptionEventContext - >(REMOTE_MODULE, (imp: __DbConnectionImpl) => imp as DbConnection); +export class DbConnectionBuilder extends __DbConnectionBuilder {} + +export class DbConnection extends __DbConnectionImpl { + static builder = (): DbConnectionBuilder => { + return new DbConnectionBuilder( + REMOTE_MODULE, + (config: __DbConnectionConfig) => + new DbConnection(config) + ); }; subscriptionBuilder = (): SubscriptionBuilder => { return new SubscriptionBuilder(this); }; } - -export type EventContext = __EventContextInterface< - RemoteTables, - RemoteReducers, - SetReducerFlags, - Reducer ->; -export type ReducerEventContext = __ReducerEventContextInterface< - RemoteTables, - RemoteReducers, - SetReducerFlags, - Reducer ->; -export type SubscriptionEventContext = __SubscriptionEventContextInterface< - RemoteTables, - RemoteReducers, - SetReducerFlags ->; -export type ErrorContext = __ErrorContextInterface< - RemoteTables, - RemoteReducers, - SetReducerFlags ->; diff --git a/crates/bindings-typescript/test-react-router-app/src/module_bindings/offline_user_table.ts b/crates/bindings-typescript/test-react-router-app/src/module_bindings/offline_user_table.ts index 47537ef2c6a..7a83afcebf0 100644 --- a/crates/bindings-typescript/test-react-router-app/src/module_bindings/offline_user_table.ts +++ b/crates/bindings-typescript/test-react-router-app/src/module_bindings/offline_user_table.ts @@ -4,113 +4,13 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -import { User } from './user_type'; -import { - type EventContext, - type Reducer, - RemoteReducers, - RemoteTables, -} from '.'; -declare type __keep = [EventContext, Reducer, RemoteReducers, RemoteTables]; - -/** - * Table handle for the table `offline_user`. - * - * Obtain a handle from the [`offlineUser`] property on [`RemoteTables`], - * like `ctx.db.offlineUser`. - * - * Users are encouraged not to explicitly reference this type, - * but to directly chain method calls, - * like `ctx.db.offlineUser.on_insert(...)`. - */ -export class OfflineUserTableHandle - implements __TableHandle -{ - // phantom type to track the table name - readonly tableName!: TableName; - tableCache: __TableCache; - - constructor(tableCache: __TableCache) { - this.tableCache = tableCache; - } - - count(): number { - return this.tableCache.count(); - } - - iter(): Iterable { - return this.tableCache.iter(); - } - /** - * Access to the `identity` unique index on the table `offline_user`, - * which allows point queries on the field of the same name - * via the [`OfflineUserIdentityUnique.find`] method. - * - * Users are encouraged not to explicitly reference this type, - * but to directly chain method calls, - * like `ctx.db.offlineUser.identity().find(...)`. - * - * Get a handle on the `identity` unique index on the table `offline_user`. - */ - identity = { - // Find the subscribed row whose `identity` column value is equal to `col_val`, - // if such a row is present in the client cache. - find: (col_val: __Identity): User | undefined => { - for (let row of this.tableCache.iter()) { - if (__deepEqual(row.identity, col_val)) { - return row; - } - } - }, - }; - - onInsert = (cb: (ctx: EventContext, row: User) => void) => { - return this.tableCache.onInsert(cb); - }; - - removeOnInsert = (cb: (ctx: EventContext, row: User) => void) => { - return this.tableCache.removeOnInsert(cb); - }; - - onDelete = (cb: (ctx: EventContext, row: User) => void) => { - return this.tableCache.onDelete(cb); - }; - - removeOnDelete = (cb: (ctx: EventContext, row: User) => void) => { - return this.tableCache.removeOnDelete(cb); - }; - - // Updates are only defined for tables with primary keys. - onUpdate = (cb: (ctx: EventContext, oldRow: User, newRow: User) => void) => { - return this.tableCache.onUpdate(cb); - }; - removeOnUpdate = ( - cb: (ctx: EventContext, onRow: User, newRow: User) => void - ) => { - return this.tableCache.removeOnUpdate(cb); - }; -} +export default __t.row({ + identity: __t.identity(), + hasIncrementedCount: __t.u32(), +}); diff --git a/crates/bindings-typescript/test-react-router-app/src/module_bindings/user_table.ts b/crates/bindings-typescript/test-react-router-app/src/module_bindings/user_table.ts index 21275ac19c1..7a83afcebf0 100644 --- a/crates/bindings-typescript/test-react-router-app/src/module_bindings/user_table.ts +++ b/crates/bindings-typescript/test-react-router-app/src/module_bindings/user_table.ts @@ -4,113 +4,13 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -import { User } from './user_type'; -import { - type EventContext, - type Reducer, - RemoteReducers, - RemoteTables, -} from '.'; -declare type __keep = [EventContext, Reducer, RemoteReducers, RemoteTables]; - -/** - * Table handle for the table `user`. - * - * Obtain a handle from the [`user`] property on [`RemoteTables`], - * like `ctx.db.user`. - * - * Users are encouraged not to explicitly reference this type, - * but to directly chain method calls, - * like `ctx.db.user.on_insert(...)`. - */ -export class UserTableHandle - implements __TableHandle -{ - // phantom type to track the table name - readonly tableName!: TableName; - tableCache: __TableCache; - - constructor(tableCache: __TableCache) { - this.tableCache = tableCache; - } - - count(): number { - return this.tableCache.count(); - } - - iter(): Iterable { - return this.tableCache.iter(); - } - /** - * Access to the `identity` unique index on the table `user`, - * which allows point queries on the field of the same name - * via the [`UserIdentityUnique.find`] method. - * - * Users are encouraged not to explicitly reference this type, - * but to directly chain method calls, - * like `ctx.db.user.identity().find(...)`. - * - * Get a handle on the `identity` unique index on the table `user`. - */ - identity = { - // Find the subscribed row whose `identity` column value is equal to `col_val`, - // if such a row is present in the client cache. - find: (col_val: __Identity): User | undefined => { - for (let row of this.tableCache.iter()) { - if (__deepEqual(row.identity, col_val)) { - return row; - } - } - }, - }; - - onInsert = (cb: (ctx: EventContext, row: User) => void) => { - return this.tableCache.onInsert(cb); - }; - - removeOnInsert = (cb: (ctx: EventContext, row: User) => void) => { - return this.tableCache.removeOnInsert(cb); - }; - - onDelete = (cb: (ctx: EventContext, row: User) => void) => { - return this.tableCache.onDelete(cb); - }; - - removeOnDelete = (cb: (ctx: EventContext, row: User) => void) => { - return this.tableCache.removeOnDelete(cb); - }; - - // Updates are only defined for tables with primary keys. - onUpdate = (cb: (ctx: EventContext, oldRow: User, newRow: User) => void) => { - return this.tableCache.onUpdate(cb); - }; - removeOnUpdate = ( - cb: (ctx: EventContext, onRow: User, newRow: User) => void - ) => { - return this.tableCache.removeOnUpdate(cb); - }; -} +export default __t.row({ + identity: __t.identity(), + hasIncrementedCount: __t.u32(), +}); diff --git a/crates/bindings-typescript/test-react-router-app/src/module_bindings/user_type.ts b/crates/bindings-typescript/test-react-router-app/src/module_bindings/user_type.ts index bd12911fa23..ad6fb447e3c 100644 --- a/crates/bindings-typescript/test-react-router-app/src/module_bindings/user_type.ts +++ b/crates/bindings-typescript/test-react-router-app/src/module_bindings/user_type.ts @@ -4,71 +4,13 @@ /* eslint-disable */ /* tslint:disable */ import { - AlgebraicType as __AlgebraicTypeValue, - BinaryReader as __BinaryReader, - BinaryWriter as __BinaryWriter, - ClientCache as __ClientCache, - ConnectionId as __ConnectionId, - DbConnectionBuilder as __DbConnectionBuilder, - DbConnectionImpl as __DbConnectionImpl, - Identity as __Identity, - SubscriptionBuilderImpl as __SubscriptionBuilderImpl, - TableCache as __TableCache, - TimeDuration as __TimeDuration, - Timestamp as __Timestamp, - deepEqual as __deepEqual, - type AlgebraicType as __AlgebraicTypeType, - type AlgebraicTypeVariants as __AlgebraicTypeVariants, - type CallReducerFlags as __CallReducerFlags, - type ErrorContextInterface as __ErrorContextInterface, - type Event as __Event, - type EventContextInterface as __EventContextInterface, - type ReducerEventContextInterface as __ReducerEventContextInterface, - type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, - type TableHandle as __TableHandle, + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, } from '../../../src/index'; -export type User = { - identity: __Identity; - hasIncrementedCount: number; -}; -let _cached_User_type_value: __AlgebraicTypeType | null = null; - -/** - * An object for generated helper functions. - */ -export const User = { - /** - * A function which returns this type represented as an AlgebraicType. - * This function is derived from the AlgebraicType used to generate this type. - */ - getTypeScriptAlgebraicType(): __AlgebraicTypeType { - if (_cached_User_type_value) return _cached_User_type_value; - _cached_User_type_value = __AlgebraicTypeValue.Product({ elements: [] }); - _cached_User_type_value.value.elements.push( - { - name: 'identity', - algebraicType: __AlgebraicTypeValue.createIdentityType(), - }, - { name: 'hasIncrementedCount', algebraicType: __AlgebraicTypeValue.U32 } - ); - return _cached_User_type_value; - }, - - serialize(writer: __BinaryWriter, value: User): void { - __AlgebraicTypeValue.serializeValue( - writer, - User.getTypeScriptAlgebraicType(), - value - ); - }, - - deserialize(reader: __BinaryReader): User { - return __AlgebraicTypeValue.deserializeValue( - reader, - User.getTypeScriptAlgebraicType() - ); - }, -}; - -export default User; +export default __t.object('User', { + identity: __t.identity(), + hasIncrementedCount: __t.u32(), +}); diff --git a/crates/bindings-typescript/test-react-router-app/src/pages/CounterPage.tsx b/crates/bindings-typescript/test-react-router-app/src/pages/CounterPage.tsx index bc7d5674131..034ba900866 100644 --- a/crates/bindings-typescript/test-react-router-app/src/pages/CounterPage.tsx +++ b/crates/bindings-typescript/test-react-router-app/src/pages/CounterPage.tsx @@ -1,9 +1,10 @@ -import { useSpacetimeDB, useTable } from '../../../src/react'; -import { DbConnection, Counter } from '../module_bindings'; +import { useReducer, useTable } from '../../../src/react'; +import { tables, reducers } from '../module_bindings'; export default function CounterPage() { - const stdb = useSpacetimeDB(); - const { rows: counter } = useTable('counter'); + const counter = useTable(tables.counter); + const incrementCounter = useReducer(reducers.incrementCounter); + const clearCounter = useReducer(reducers.clearCounter); console.log('Rendering CounterPage, current counter:', counter); @@ -11,15 +12,13 @@ export default function CounterPage() { <>

Counter

-

Click above to increment the count, click below to clear the count.

- +
); diff --git a/crates/bindings-typescript/test-react-router-app/src/pages/UserPage.tsx b/crates/bindings-typescript/test-react-router-app/src/pages/UserPage.tsx index 67eccc256e0..b73e004f791 100644 --- a/crates/bindings-typescript/test-react-router-app/src/pages/UserPage.tsx +++ b/crates/bindings-typescript/test-react-router-app/src/pages/UserPage.tsx @@ -1,28 +1,14 @@ -import { useEffect } from 'react'; import { useSpacetimeDB, useTable } from '../../../src/react'; -import { DbConnection, User } from '../module_bindings'; +import { tables, User } from '../module_bindings'; +import { Infer } from '../../../src'; export default function UserPage() { - const stdb = useSpacetimeDB(); - const { rows: users } = useTable('user'); + const connection = useSpacetimeDB(); + const users = useTable(tables.user); - useEffect(() => { - if (!stdb.isActive) return; - - const sub = stdb - .subscriptionBuilder() - .onError((err: any) => console.error('User subscription error:', err)) - .onApplied(() => console.log('User subscription applied')) - .subscribe('SELECT * FROM user'); - - return () => { - sub.unsubscribeThen(() => console.log('User subscription cleaned up')); - }; - }, [stdb.isActive]); - - const identityHex = stdb.identity?.toHexString(); + const identityHex = connection.identity?.toHexString(); const currentUser = users.find( - (u: User) => u.identity.toHexString() === identityHex + (u: Infer) => u.identity.toHexString() === identityHex ); return ( diff --git a/crates/bindings-typescript/tests/algebraic_type.test.ts b/crates/bindings-typescript/tests/algebraic_type.test.ts index 126b21a7a05..c993f1f0e5f 100644 --- a/crates/bindings-typescript/tests/algebraic_type.test.ts +++ b/crates/bindings-typescript/tests/algebraic_type.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from 'vitest'; -import { AlgebraicType } from '../src/index'; +import { AlgebraicType } from '../src/lib/algebraic_type'; describe('AlgebraicType', () => { test('intoMapKey handles all primitive types', () => { diff --git a/crates/bindings-typescript/tests/binary_read_write.test.ts b/crates/bindings-typescript/tests/binary_read_write.test.ts index ecf316b56b7..77a9b024f4c 100644 --- a/crates/bindings-typescript/tests/binary_read_write.test.ts +++ b/crates/bindings-typescript/tests/binary_read_write.test.ts @@ -1,13 +1,4 @@ import { describe, expect, test } from 'vitest'; -import { - AlgebraicType, - BinaryReader, - BinaryWriter, - ConnectionId, - TimeDuration, - Timestamp, -} from '../src/index'; -import * as ws from '../src/sdk/client_api'; import { anIdentity, bobIdentity, @@ -15,7 +6,16 @@ import { encodeUser, sallyIdentity, } from './utils'; -import { ServerMessage } from '../src/sdk/client_api'; +import ServerMessage from '../src/sdk/client_api/server_message_type'; +import UpdateStatus from '../src/sdk/client_api/update_status_type'; +import CompressableQueryUpdate from '../src/sdk/client_api/compressable_query_update_type'; +import RowSizeHint from '../src/sdk/client_api/row_size_hint_type'; +import BinaryReader from '../src/lib/binary_reader'; +import BinaryWriter from '../src/lib/binary_writer'; +import { Timestamp } from '../src/lib/timestamp'; +import { ConnectionId } from '../src/lib/connection_id'; +import { TimeDuration } from '../src/lib/time_duration'; +import { AlgebraicType } from '../src/lib/algebraic_type'; /* // Generated by the following Rust code: @@ -131,22 +131,22 @@ describe('BinaryReader/Writer', () => { username: 'sally', }; const binary = [...encodeUser(user1)].concat([...encodeUser(user2)]); - const transactionUpdate = ws.ServerMessage.TransactionUpdate({ - status: ws.UpdateStatus.Committed({ + const transactionUpdate = ServerMessage.create('TransactionUpdate', { + status: UpdateStatus.create('Committed', { tables: [ { tableId: 35, tableName: 'user', numRows: BigInt(1), updates: [ - ws.CompressableQueryUpdate.Uncompressed({ + CompressableQueryUpdate.create('Uncompressed', { deletes: { - sizeHint: ws.RowSizeHint.FixedSize(0), // not used + sizeHint: RowSizeHint.create('FixedSize', 0), // not used rowsData: new Uint8Array([]), }, // FIXME: this test is evil: an initial subscription can never contain deletes or updates. inserts: { - sizeHint: ws.RowSizeHint.FixedSize(0), // not used + sizeHint: RowSizeHint.create('FixedSize', 0), // not used rowsData: new Uint8Array(binary), }, }), @@ -169,14 +169,14 @@ describe('BinaryReader/Writer', () => { const writer = new BinaryWriter(1024); AlgebraicType.serializeValue( writer, - ServerMessage.getTypeScriptAlgebraicType(), + ServerMessage.algebraicType, transactionUpdate ); const rawBytes = writer.getBuffer(); const deserializedTransactionUpdate = AlgebraicType.deserializeValue( new BinaryReader(rawBytes), - ServerMessage.getTypeScriptAlgebraicType() + ServerMessage.algebraicType ); expect(deserializedTransactionUpdate).toEqual(transactionUpdate); }); diff --git a/crates/bindings-typescript/tests/index.test.ts b/crates/bindings-typescript/tests/index.test.ts index 570728769fb..9062b69b478 100644 --- a/crates/bindings-typescript/tests/index.test.ts +++ b/crates/bindings-typescript/tests/index.test.ts @@ -6,7 +6,7 @@ import { type IdentityTokenMessage, } from '../src/index'; import type { ColumnBuilder } from '../src/server'; -import { t } from '../src/server/type_builders'; +import { t } from '../src/lib/type_builders'; describe('TypeBuilder', () => { it('builds the correct algebraic type for a point', () => { @@ -15,7 +15,7 @@ describe('TypeBuilder', () => { y: t.f64(), z: t.f64(), }); - expect(point.resolveType()).toEqual({ + expect(point.algebraicType).toEqual({ tag: 'Product', value: { elements: [ @@ -32,7 +32,7 @@ describe('TypeBuilder', () => { a: t.string(), b: t.number(), }); - expect(sumType.resolveType()).toEqual({ + expect(sumType.algebraicType).toEqual({ tag: 'Sum', value: { variants: [ diff --git a/crates/bindings-typescript/tests/serde.test.ts b/crates/bindings-typescript/tests/serde.test.ts index cb9759c1b69..c740dd2ec8e 100644 --- a/crates/bindings-typescript/tests/serde.test.ts +++ b/crates/bindings-typescript/tests/serde.test.ts @@ -1,5 +1,12 @@ import { describe, expect, test } from 'vitest'; -import { AlgebraicType, BinaryReader, BinaryWriter } from 'spacetimedb'; +import { + AlgebraicType, + BinaryReader, + BinaryWriter, + ConnectionId, + Identity, + ScheduleAt, +} from 'spacetimedb'; describe('it correctly serializes and deserializes algebraic values', () => { test('when it serializes and deserializes with a product type', () => { @@ -52,7 +59,7 @@ describe('it correctly serializes and deserializes algebraic values', () => { __identity__: BigInt(1234567890123456789012345678901234567890n), }; - const algebraic_type = AlgebraicType.createIdentityType(); + const algebraic_type = Identity.getAlgebraicType(); const binaryWriter = new BinaryWriter(1024); AlgebraicType.serializeValue(binaryWriter, algebraic_type, value); @@ -82,7 +89,7 @@ describe('it correctly serializes and deserializes algebraic values', () => { }, }; - const algebraic_type = AlgebraicType.createScheduleAtType(); + const algebraic_type = ScheduleAt.getAlgebraicType(); const binaryWriter = new BinaryWriter(1024); AlgebraicType.serializeValue(binaryWriter, algebraic_type, value); @@ -107,7 +114,7 @@ describe('it correctly serializes and deserializes algebraic values', () => { }, }; - const algebraic_type = AlgebraicType.createScheduleAtType(); + const algebraic_type = ScheduleAt.getAlgebraicType(); const binaryWriter = new BinaryWriter(1024); AlgebraicType.serializeValue(binaryWriter, algebraic_type, value); @@ -130,7 +137,7 @@ describe('it correctly serializes and deserializes algebraic values', () => { __connection_id__: U128_MAX, }; - const algebraic_type = AlgebraicType.createConnectionIdType(); + const algebraic_type = ConnectionId.getAlgebraicType(); const binaryWriter = new BinaryWriter(1024); AlgebraicType.serializeValue(binaryWriter, algebraic_type, value); diff --git a/crates/bindings-typescript/tests/table_cache.test.ts b/crates/bindings-typescript/tests/table_cache.test.ts index eef948ba6be..5c7f0afb372 100644 --- a/crates/bindings-typescript/tests/table_cache.test.ts +++ b/crates/bindings-typescript/tests/table_cache.test.ts @@ -1,10 +1,8 @@ import { type Operation, TableCache } from '../src/sdk/table_cache'; -import type { TableRuntimeTypeInfo } from '../src/sdk/spacetime_module'; import { describe, expect, test } from 'vitest'; - -import { Player } from '../test-app/src/module_bindings/player_type.ts'; - -import { AlgebraicType, type AlgebraicTypeVariants } from 'spacetimedb'; +import Player from '../test-app/src/module_bindings/player_type.ts'; +import { AlgebraicType, Identity, type Infer } from 'spacetimedb'; +import { tables } from '../test-app/src/module_bindings/index.ts'; interface ApplyOperations { ops: Operation[]; @@ -45,7 +43,7 @@ function deleteEvent(row: any, ctx: any = {}): CallbackEvent { interface AssertionInput { // The state of the table cache. - tableCache: TableCache; + tableCache: TableCache; // The sequence of callbacks that were fired from the last applyOperations. callbackHistory: CallbackEvent[]; } @@ -59,7 +57,7 @@ interface TestStep { assertions: Assertion[]; } -function runTest(tableCache: TableCache, testSteps: TestStep[]) { +function runTest(tableCache: TableCache, testSteps: TestStep[]) { const callbackHistory: CallbackEvent[] = []; tableCache.onInsert((ctx, row) => { callbackHistory.push({ @@ -112,13 +110,9 @@ describe('TableCache', () => { { name: 'location', algebraicType: pointType }, ], }); - const tableTypeInfo: TableRuntimeTypeInfo = { - tableName: 'player', - rowType: playerType, - }; - const newTable = () => new TableCache(tableTypeInfo); - const mkOperation = (type: 'insert' | 'delete', row: Player) => { - const rowId = AlgebraicType.intoMapKey(tableTypeInfo.rowType, row); + const newTable = () => new TableCache(tables.unindexedPlayer); + const mkOperation = (type: 'insert' | 'delete', row: Infer) => { + const rowId = AlgebraicType.intoMapKey({ tag: 'Product', value: tables.unindexedPlayer.rowType }, row); return { type, rowId, @@ -130,7 +124,8 @@ describe('TableCache', () => { const tableCache = newTable(); const steps: TestStep[] = []; const player = { - ownerId: '1', + id: 1, + userId: Identity.zero(), name: 'Player 1', location: { x: 1, @@ -144,9 +139,9 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter().length).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter()).length).toBe(1); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory.length).toBe(1); expect(callbackHistory[0].type).toBe('insert'); expect(callbackHistory[0].row).toEqual(player); @@ -160,7 +155,8 @@ describe('TableCache', () => { const tableCache = newTable(); const steps: TestStep[] = []; const player = { - ownerId: '1', + id: 1, + userId: Identity.zero(), name: 'Player 1', location: { x: 1, @@ -174,9 +170,9 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter().length).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter()).length).toBe(1); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory.length).toBe(1); expect(callbackHistory[0].type).toBe('insert'); expect(callbackHistory[0].row).toEqual(player); @@ -190,7 +186,8 @@ describe('TableCache', () => { const tableCache = newTable(); const steps: TestStep[] = []; const player = { - ownerId: '1', + id: 1, + userId: Identity.zero(), name: 'Player 1', location: { x: 1, @@ -204,9 +201,9 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter().length).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter()).length).toBe(1); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory.length).toBe(1); expect(callbackHistory[0].type).toBe('insert'); expect(callbackHistory[0].row).toEqual(player); @@ -220,9 +217,9 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter().length).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter()).length).toBe(1); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory.length).toBe(0); }, ], @@ -234,7 +231,8 @@ describe('TableCache', () => { const tableCache = newTable(); const steps: TestStep[] = []; const player = { - ownerId: '1', + id: 1, + userId: Identity.zero(), name: 'Player 1', location: { x: 1, @@ -248,8 +246,8 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory.length).toBe(1); expect(callbackHistory[0].type).toBe('insert'); expect(callbackHistory[0].row).toEqual(player); @@ -277,7 +275,8 @@ describe('TableCache', () => { const tableCache = newTable(); const steps: TestStep[] = []; const mkPlayer = () => ({ - ownerId: '1', + id: 1, + userId: Identity.zero(), name: 'Player 1', location: { x: 1, @@ -285,7 +284,8 @@ describe('TableCache', () => { }, }); const player = { - ownerId: '1', + id: 1, + userId: Identity.zero(), name: 'Player 1', location: { x: 1, @@ -302,8 +302,8 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory.length).toBe(1); expect(callbackHistory[0].type).toBe('insert'); expect(callbackHistory[0].row).toEqual(player); @@ -318,8 +318,8 @@ describe('TableCache', () => { assertions: [ ({ tableCache, callbackHistory }) => { // We still have one reference left, so it isn't actually deleted. - expect(tableCache.count()).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory.length).toBe(0); }, ], @@ -347,8 +347,8 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory).toEqual([insertEvent(player)]); }, ], @@ -360,8 +360,8 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory).toEqual([]); }, ], @@ -384,7 +384,8 @@ describe('TableCache', () => { test('Insert one', () => { const tableCache = newTable(); const op = mkOperation('insert', { - ownerId: '1', + id: 1, + userId: Identity.zero(), name: 'Player 1', location: { x: 1, @@ -398,7 +399,7 @@ describe('TableCache', () => { expect(row).toEqual(op.row); }); expect(callbacks.length).toBe(1); - expect(tableCache.count()).toBe(1); + expect(tableCache.count()).toBe(1n); callbacks.forEach(cb => { cb.cb(); }); @@ -414,25 +415,17 @@ describe('TableCache', () => { }); const playerType: AlgebraicType = AlgebraicType.Product({ elements: [ - { name: 'ownerId', algebraicType: AlgebraicType.String }, + { name: 'id', algebraicType: AlgebraicType.U32 }, + { name: 'userId', algebraicType: AlgebraicType.Product({ elements: [{ name: '__identity__', algebraicType: AlgebraicType.U256 }] }) }, { name: 'name', algebraicType: AlgebraicType.String }, { name: 'location', algebraicType: pointType }, ], }); - const tableTypeInfo: TableRuntimeTypeInfo = { - tableName: 'player', - rowType: playerType, - primaryKeyInfo: { - colName: 'ownerId', - colType: (playerType as AlgebraicTypeVariants.Product).value.elements[0] - .algebraicType, - }, - }; - const newTable = () => new TableCache(tableTypeInfo); - const mkOperation = (type: 'insert' | 'delete', row: Player) => { + const newTable = () => new TableCache(tables.player); + const mkOperation = (type: 'insert' | 'delete', row: Infer) => { const rowId = AlgebraicType.intoMapKey( - tableTypeInfo.primaryKeyInfo!.colType, - row['ownerId'] + { tag: 'Product', value: tables.player.rowType }, + row['id'] ); return { type, @@ -445,7 +438,8 @@ describe('TableCache', () => { const tableCache = newTable(); const steps: TestStep[] = []; const player = { - ownerId: '1', + id: 1, + userId: Identity.zero(), name: 'Player 1', location: { x: 1, @@ -459,9 +453,9 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter().length).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter()).length).toBe(1); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory.length).toBe(1); expect(callbackHistory[0].type).toBe('insert'); expect(callbackHistory[0].row).toEqual(player); @@ -475,7 +469,8 @@ describe('TableCache', () => { const tableCache = newTable(); const steps: TestStep[] = []; const player = { - ownerId: '1', + id: 1, + userId: Identity.zero(), name: 'Player 1', location: { x: 1, @@ -489,9 +484,9 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter().length).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter()).length).toBe(1); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory.length).toBe(1); expect(callbackHistory[0].type).toBe('insert'); expect(callbackHistory[0].row).toEqual(player); @@ -505,7 +500,8 @@ describe('TableCache', () => { const tableCache = newTable(); const steps: TestStep[] = []; const player = { - ownerId: '1', + id: 1, + userId: Identity.zero(), name: 'Player 1', location: { x: 1, @@ -519,9 +515,9 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter().length).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter()).length).toBe(1); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory.length).toBe(1); expect(callbackHistory[0].type).toBe('insert'); expect(callbackHistory[0].row).toEqual(player); @@ -535,9 +531,9 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter().length).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter()).length).toBe(1); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory.length).toBe(0); }, ], @@ -549,7 +545,8 @@ describe('TableCache', () => { const tableCache = newTable(); const steps: TestStep[] = []; const player = { - ownerId: '1', + id: 1, + userId: Identity.zero(), name: 'Player 1', location: { x: 1, @@ -563,8 +560,8 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory.length).toBe(1); expect(callbackHistory[0].type).toBe('insert'); expect(callbackHistory[0].row).toEqual(player); @@ -592,7 +589,8 @@ describe('TableCache', () => { const tableCache = newTable(); const steps: TestStep[] = []; const mkPlayer = (name: string) => ({ - ownerId: '1', + id: 1, + userId: Identity.zero(), name: name, location: { x: 1, @@ -606,8 +604,8 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter()[0]).toEqual(mkPlayer('jeff')); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter())[0]).toEqual(mkPlayer('jeff')); expect(callbackHistory).toEqual([insertEvent(mkPlayer('jeff'))]); }, ], @@ -622,8 +620,8 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter()[0]).toEqual(mkPlayer('jeffv2')); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter())[0]).toEqual(mkPlayer('jeffv2')); expect(callbackHistory).toEqual([ updateEvent(mkPlayer('jeff'), mkPlayer('jeffv2')), ]); @@ -637,7 +635,8 @@ describe('TableCache', () => { const tableCache = newTable(); const steps: TestStep[] = []; const mkPlayer = () => ({ - ownerId: '1', + id: 1, + userId: Identity.zero(), name: 'Player 1', location: { x: 1, @@ -645,7 +644,8 @@ describe('TableCache', () => { }, }); const player = { - ownerId: '1', + id: 1, + userId: Identity.zero(), name: 'Player 1', location: { x: 1, @@ -662,8 +662,8 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory.length).toBe(1); expect(callbackHistory[0].type).toBe('insert'); expect(callbackHistory[0].row).toEqual(player); @@ -678,8 +678,8 @@ describe('TableCache', () => { assertions: [ ({ tableCache, callbackHistory }) => { // We still have one reference left, so it isn't actually deleted. - expect(tableCache.count()).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory.length).toBe(0); }, ], @@ -707,8 +707,8 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory).toEqual([insertEvent(player)]); }, ], @@ -720,8 +720,8 @@ describe('TableCache', () => { }, assertions: [ ({ tableCache, callbackHistory }) => { - expect(tableCache.count()).toBe(1); - expect(tableCache.iter()[0]).toEqual(player); + expect(tableCache.count()).toBe(1n); + expect(Array.from(tableCache.iter())[0]).toEqual(player); expect(callbackHistory).toEqual([]); }, ], @@ -744,7 +744,8 @@ describe('TableCache', () => { test('Insert one', () => { const tableCache = newTable(); const op = mkOperation('insert', { - ownerId: '1', + id: 1, + userId: Identity.zero(), name: 'Player 1', location: { x: 1, @@ -758,7 +759,7 @@ describe('TableCache', () => { expect(row).toEqual(op.row); }); expect(callbacks.length).toBe(1); - expect(tableCache.count()).toBe(1); + expect(tableCache.count()).toBe(1n); callbacks.forEach(cb => { cb.cb(); }); @@ -781,16 +782,7 @@ describe('TableCache', () => { }); test('should be empty on creation', () => { - const tableTypeInfo: TableRuntimeTypeInfo = { - tableName: 'player', - rowType: playerType, - primaryKeyInfo: { - colName: 'ownerId', - colType: (playerType as AlgebraicTypeVariants.Product).value.elements[0] - .algebraicType, - }, - }; - const tableCache = new TableCache(tableTypeInfo); - expect(tableCache.count()).toBe(0); + const tableCache = new TableCache(tables.player); + expect(tableCache.count()).toBe(0n); }); }); diff --git a/crates/bindings-typescript/tests/utils.ts b/crates/bindings-typescript/tests/utils.ts index 19461b384cf..4ed63d7e2ed 100644 --- a/crates/bindings-typescript/tests/utils.ts +++ b/crates/bindings-typescript/tests/utils.ts @@ -1,4 +1,7 @@ -import { AlgebraicType, BinaryWriter, Identity } from '../src'; +import { AlgebraicType } from '../src/lib/algebraic_type'; +import BinaryWriter from '../src/lib/binary_writer'; +import { Identity } from '../src/lib/identity'; +import type { Infer } from '../src/lib/type_builders'; import { Player, Point, User } from '../test-app/src/module_bindings'; export const anIdentity = Identity.fromString( @@ -11,13 +14,13 @@ export const sallyIdentity = Identity.fromString( '000000000000000000000000000000000000000000000000000000000006a111' ); -export function encodePlayer(value: Player): Uint8Array { +export function encodePlayer(value: Infer): Uint8Array { const writer = new BinaryWriter(1024); Player.serialize(writer, value); return writer.getBuffer(); } -export function encodeUser(value: User): Uint8Array { +export function encodeUser(value: Infer): Uint8Array { const writer = new BinaryWriter(1024); User.serialize(writer, value); return writer.getBuffer(); @@ -25,7 +28,7 @@ export function encodeUser(value: User): Uint8Array { export function encodeCreatePlayerArgs( name: string, - location: Point + location: Infer ): Uint8Array { const writer = new BinaryWriter(1024); AlgebraicType.serializeValue(writer, AlgebraicType.String, name); diff --git a/crates/codegen/examples/regen-typescript-moduledef.rs b/crates/codegen/examples/regen-typescript-moduledef.rs index b47162d15f3..a5f76e64be4 100644 --- a/crates/codegen/examples/regen-typescript-moduledef.rs +++ b/crates/codegen/examples/regen-typescript-moduledef.rs @@ -39,7 +39,7 @@ fn main() -> anyhow::Result<()> { if filename == "index.ts" { return Ok(()); } - let code = regex_replace!(&code, r#"from "spacetimedb";"#, r#"from "../../index";"#); + let code = regex_replace!(&code, r#"from "spacetimedb";"#, r#"from "../../lib/type_builders";"#); // Elide types which are related to client-side only things let code = regex_replace!(&code, r"type CallReducerFlags as __CallReducerFlags,", r""); @@ -58,6 +58,7 @@ fn main() -> anyhow::Result<()> { ); let code = regex_replace!(&code, r"DbConnectionBuilder as __DbConnectionBuilder,", r""); let code = regex_replace!(&code, r"DbConnectionImpl as __DbConnectionImpl,", r""); + let code = regex_replace!(&code, r"type DbConnectionConfig as __DbConnectionConfig,", r""); let code = regex_replace!(&code, r"SubscriptionBuilderImpl as __SubscriptionBuilderImpl,", r""); let code = regex_replace!(&code, r"TableCache as __TableCache,", r""); let code = regex_replace!(&code, r"ClientCache as __ClientCache,", r""); diff --git a/crates/codegen/src/typescript.rs b/crates/codegen/src/typescript.rs index 6f055ee1622..c3aa847b7e4 100644 --- a/crates/codegen/src/typescript.rs +++ b/crates/codegen/src/typescript.rs @@ -1,8 +1,7 @@ use crate::util::{ - is_reducer_invokable, iter_reducers, iter_tables, iter_types, iter_unique_cols, - print_auto_generated_version_comment, + is_reducer_invokable, iter_indexes, iter_reducers, iter_tables, iter_types, print_auto_generated_version_comment, }; -use crate::{indent_scope, OutputFile}; +use crate::OutputFile; use super::util::{collect_case, print_auto_generated_file_comment, type_ref_name}; @@ -13,9 +12,12 @@ use std::ops::Deref; use convert_case::{Case, Casing}; use spacetimedb_lib::sats::layout::PrimitiveType; use spacetimedb_lib::sats::AlgebraicTypeRef; -use spacetimedb_schema::def::{ModuleDef, ReducerDef, ScopedTypeName, TableDef, TypeDef}; +use spacetimedb_primitives::ColId; +use spacetimedb_schema::def::{ + BTreeAlgorithm, IndexAlgorithm, ModuleDef, ReducerDef, ScopedTypeName, TableDef, TypeDef, +}; use spacetimedb_schema::identifier::Identifier; -use spacetimedb_schema::schema::{Schema, TableSchema}; +use spacetimedb_schema::schema::TableSchema; use spacetimedb_schema::type_for_generate::{AlgebraicTypeDef, AlgebraicTypeUse, ProductTypeDef}; use super::code_indenter::{CodeIndenter, Indenter}; @@ -36,7 +38,7 @@ impl Lang for TypeScript { let mut output = CodeIndenter::new(String::new(), INDENT); let out = &mut output; - print_file_header(out, false); + print_file_header(out, false, true); gen_and_print_imports(module, out, &product.elements, &[typ.ty], None); writeln!(out); define_body_for_product(module, out, &type_name, &product.elements); @@ -47,34 +49,12 @@ impl Lang for TypeScript { } }; - let define_variants_for_sum = |variants: &[(Identifier, AlgebraicTypeUse)]| { - let mut output = CodeIndenter::new(String::new(), INDENT); - let out = &mut output; - - print_file_header(out, false); - // Note that the current type is not included in dont_import below. - gen_and_print_imports(module, out, variants, &[], Some("Type")); - writeln!(out); - write_variant_types(module, out, variants); - out.newline(); - OutputFile { - filename: variants_module_name(&typ.name) + ".ts", - code: output.into_inner(), - } - }; - let define_type_for_sum = |variants: &[(Identifier, AlgebraicTypeUse)]| { let mut output = CodeIndenter::new(String::new(), INDENT); let out = &mut output; - print_file_header(out, false); + print_file_header(out, false, true); gen_and_print_imports(module, out, variants, &[typ.ty], None); - writeln!( - out, - "import * as {}Variants from './{}'", - type_name, - variants_module_name(&typ.name) - ); writeln!(out); // For the purpose of bootstrapping AlgebraicType, if the name of the type // is `AlgebraicType`, we need to use an alias. @@ -91,10 +71,7 @@ impl Lang for TypeScript { vec![define_type_for_product(product)] } AlgebraicTypeDef::Sum(sum) => { - vec![ - define_variants_for_sum(&sum.variants), - define_type_for_sum(&sum.variants), - ] + vec![define_type_for_sum(&sum.variants)] } AlgebraicTypeDef::PlainEnum(plain_enum) => { let variants = plain_enum @@ -103,23 +80,37 @@ impl Lang for TypeScript { .cloned() .map(|var| (var, AlgebraicTypeUse::Unit)) .collect::>(); - vec![define_variants_for_sum(&variants), define_type_for_sum(&variants)] + vec![define_type_for_sum(&variants)] } } } - fn generate_table_file_from_schema(&self, module: &ModuleDef, table: &TableDef, schema: TableSchema) -> OutputFile { + /// e.g. + /// ```ts + /// table({ + /// name: 'player', + /// indexes: [ + /// { name: 'this_is_an_index', algorithm: "btree", columns: [ "ownerId" ] } + /// ], + /// }, t.row({ + /// id: t.u32().primaryKey(), + /// ownerId: t.string(), + /// name: t.string().unique(), + /// location: pointType, + /// })) + /// ``` + fn generate_table_file_from_schema( + &self, + module: &ModuleDef, + table: &TableDef, + _schema: TableSchema, + ) -> OutputFile { let mut output = CodeIndenter::new(String::new(), INDENT); let out = &mut output; - print_file_header(out, false); + print_file_header(out, false, true); let type_ref = table.product_type_ref; - let row_type = type_ref_name(module, type_ref); - let row_type_module = type_ref_module_name(module, type_ref); - - writeln!(out, "import {{ {row_type} }} from \"./{row_type_module}\";"); - let product_def = module.typespace_for_generate()[type_ref].as_product().unwrap(); // Import the types of all fields. @@ -133,150 +124,13 @@ impl Lang for TypeScript { None, ); - writeln!( - out, - "import {{ type EventContext, type Reducer, RemoteReducers, RemoteTables }} from \".\";" - ); - - // Mark potentially unused types - writeln!( - out, - "declare type __keep = [EventContext, Reducer, RemoteReducers, RemoteTables];" - ); - - let table_name = table.name.deref(); - let table_name_pascalcase = table.name.deref().to_case(Case::Pascal); - let table_handle = table_name_pascalcase.clone() + "TableHandle"; - let accessor_method = table_method_name(&table.name); - writeln!(out); - write!( - out, - "/** - * Table handle for the table `{table_name}`. - * - * Obtain a handle from the [`{accessor_method}`] property on [`RemoteTables`], - * like `ctx.db.{accessor_method}`. - * - * Users are encouraged not to explicitly reference this type, - * but to directly chain method calls, - * like `ctx.db.{accessor_method}.on_insert(...)`. - */ -export class {table_handle} implements __TableHandle {{ -" - ); + writeln!(out, "export default __t.row({{"); out.indent(1); - writeln!(out, "// phantom type to track the table name"); - writeln!(out, "readonly tableName!: TableName;"); - writeln!(out, "tableCache: __TableCache<{row_type}>;"); - writeln!(out); - writeln!(out, "constructor(tableCache: __TableCache<{row_type}>) {{"); - out.with_indent(|out| writeln!(out, "this.tableCache = tableCache;")); - writeln!(out, "}}"); - writeln!(out); - writeln!(out, "count(): number {{"); - out.with_indent(|out| { - writeln!(out, "return this.tableCache.count();"); - }); - writeln!(out, "}}"); - writeln!(out); - writeln!(out, "iter(): Iterable<{row_type}> {{"); - out.with_indent(|out| { - writeln!(out, "return this.tableCache.iter();"); - }); - writeln!(out, "}}"); - - for (unique_field_ident, unique_field_type_use) in - iter_unique_cols(module.typespace_for_generate(), &schema, product_def) - { - let unique_field_name = unique_field_ident.deref().to_case(Case::Camel); - let unique_field_name_pascalcase = unique_field_name.to_case(Case::Pascal); - - let unique_constraint = table_name_pascalcase.clone() + &unique_field_name_pascalcase + "Unique"; - let unique_field_type = type_name(module, unique_field_type_use); - - writeln!( - out, - "/** - * Access to the `{unique_field_name}` unique index on the table `{table_name}`, - * which allows point queries on the field of the same name - * via the [`{unique_constraint}.find`] method. - * - * Users are encouraged not to explicitly reference this type, - * but to directly chain method calls, - * like `ctx.db.{accessor_method}.{unique_field_name}().find(...)`. - * - * Get a handle on the `{unique_field_name}` unique index on the table `{table_name}`. - */" - ); - writeln!(out, "{unique_field_name} = {{"); - out.with_indent(|out| { - writeln!( - out, - "// Find the subscribed row whose `{unique_field_name}` column value is equal to `col_val`," - ); - writeln!(out, "// if such a row is present in the client cache."); - writeln!( - out, - "find: (col_val: {unique_field_type}): {row_type} | undefined => {{" - ); - out.with_indent(|out| { - writeln!(out, "for (let row of this.tableCache.iter()) {{"); - out.with_indent(|out| { - writeln!(out, "if (__deepEqual(row.{unique_field_name}, col_val)) {{"); - out.with_indent(|out| { - writeln!(out, "return row;"); - }); - writeln!(out, "}}"); - }); - writeln!(out, "}}"); - }); - writeln!(out, "}},"); - }); - writeln!(out, "}};"); - } - - writeln!(out); - - // TODO: expose non-unique indices. - - writeln!( - out, - "onInsert = (cb: (ctx: EventContext, row: {row_type}) => void) => {{ -{INDENT}return this.tableCache.onInsert(cb); -}} - -removeOnInsert = (cb: (ctx: EventContext, row: {row_type}) => void) => {{ -{INDENT}return this.tableCache.removeOnInsert(cb); -}} - -onDelete = (cb: (ctx: EventContext, row: {row_type}) => void) => {{ -{INDENT}return this.tableCache.onDelete(cb); -}} - -removeOnDelete = (cb: (ctx: EventContext, row: {row_type}) => void) => {{ -{INDENT}return this.tableCache.removeOnDelete(cb); -}}" - ); - - if schema.pk().is_some() { - write!( - out, - " -// Updates are only defined for tables with primary keys. -onUpdate = (cb: (ctx: EventContext, oldRow: {row_type}, newRow: {row_type}) => void) => {{ -{INDENT}return this.tableCache.onUpdate(cb); -}} - -removeOnUpdate = (cb: (ctx: EventContext, onRow: {row_type}, newRow: {row_type}) => void) => {{ -{INDENT}return this.tableCache.removeOnUpdate(cb); -}}" - ); - } + write_object_type_builder_fields(module, out, &product_def.elements, true).unwrap(); out.dedent(1); - - writeln!(out, "}}"); + writeln!(out, "}});"); OutputFile { filename: table_module_name(&table.name) + ".ts", code: output.into_inner(), @@ -287,7 +141,7 @@ removeOnUpdate = (cb: (ctx: EventContext, onRow: {row_type}, newRow: {row_type}) let mut output = CodeIndenter::new(String::new(), INDENT); let out = &mut output; - print_file_header(out, false); + print_file_header(out, false, true); out.newline(); @@ -300,9 +154,7 @@ removeOnUpdate = (cb: (ctx: EventContext, onRow: {row_type}, newRow: {row_type}) None, ); - let args_type = reducer_args_type_name(&reducer.name); - - define_body_for_product(module, out, &args_type, &reducer.params_for_generate.elements); + define_body_for_reducer(module, out, &reducer.params_for_generate.elements); OutputFile { filename: reducer_module_name(&reducer.name) + ".ts", @@ -314,16 +166,16 @@ removeOnUpdate = (cb: (ctx: EventContext, onRow: {row_type}, newRow: {row_type}) let mut output = CodeIndenter::new(String::new(), INDENT); let out = &mut output; - print_file_header(out, true); + print_file_header(out, true, false); out.newline(); writeln!(out, "// Import and reexport all reducer arg types"); for reducer in iter_reducers(module) { let reducer_name = &reducer.name; - let reducer_module_name = reducer_module_name(reducer_name) + ".ts"; + let reducer_module_name = reducer_module_name(reducer_name); let args_type = reducer_args_type_name(&reducer.name); - writeln!(out, "import {{ {args_type} }} from \"./{reducer_module_name}\";"); + writeln!(out, "import {args_type} from \"./{reducer_module_name}\";"); writeln!(out, "export {{ {args_type} }};"); } @@ -331,389 +183,220 @@ removeOnUpdate = (cb: (ctx: EventContext, onRow: {row_type}, newRow: {row_type}) writeln!(out, "// Import and reexport all table handle types"); for table in iter_tables(module) { let table_name = &table.name; - let table_module_name = table_module_name(table_name) + ".ts"; + let table_module_name = table_module_name(table_name); let table_name_pascalcase = table.name.deref().to_case(Case::Pascal); - let table_handle = table_name_pascalcase.clone() + "TableHandle"; - writeln!(out, "import {{ {table_handle} }} from \"./{table_module_name}\";"); - writeln!(out, "export {{ {table_handle} }};"); + // TODO: This really shouldn't be necessary. We could also have `table()` accept + // `__t.object(...)`s. + writeln!(out, "import {table_name_pascalcase}Row from \"./{table_module_name}\";"); + writeln!(out, "export {{ {table_name_pascalcase}Row }};"); } writeln!(out); writeln!(out, "// Import and reexport all types"); for ty in iter_types(module) { let type_name = collect_case(Case::Pascal, ty.name.name_segments()); - let type_module_name = type_module_name(&ty.name) + ".ts"; - writeln!(out, "import {{ {type_name} }} from \"./{type_module_name}\";"); + let type_module_name = type_module_name(&ty.name); + writeln!(out, "import {type_name} from \"./{type_module_name}\";"); writeln!(out, "export {{ {type_name} }};"); } out.newline(); - // Define SpacetimeModule - writeln!(out, "const REMOTE_MODULE = {{"); - out.indent(1); - writeln!(out, "tables: {{"); + writeln!(out); + writeln!(out, "const tablesSchema = __schema("); out.indent(1); for table in iter_tables(module) { let type_ref = table.product_type_ref; - let row_type = type_ref_name(module, type_ref); - let schema = TableSchema::from_module_def(module, table, (), 0.into()) - .validated() - .expect("Failed to generate table due to validation errors"); - writeln!(out, "{}: {{", table.name); + let row_type_name = type_ref_name(module, type_ref); + writeln!(out, "__table({{"); out.indent(1); - writeln!(out, "tableName: \"{}\" as const,", table.name); - writeln!(out, "rowType: {row_type}.getTypeScriptAlgebraicType(),"); - if let Some(pk) = schema.pk() { - // This is left here so we can release the codegen change before releasing a new - // version of the SDK. - // - // Eventually we can remove this and only generate use the `primaryKeyInfo` field. - writeln!(out, "primaryKey: \"{}\",", pk.col_name.to_string().to_case(Case::Camel)); - - writeln!(out, "primaryKeyInfo: {{"); - out.indent(1); - writeln!(out, "colName: \"{}\",", pk.col_name.to_string().to_case(Case::Camel)); - writeln!( - out, - "colType: ({row_type}.getTypeScriptAlgebraicType() as __AlgebraicTypeVariants.Product).value.elements[{}].algebraicType,", - pk.col_pos.0 - ); - out.dedent(1); - writeln!(out, "}},"); - } + write_table_opts(module, out, table); out.dedent(1); - writeln!(out, "}},"); + writeln!(out, "}}, {}Row),", row_type_name); } out.dedent(1); - writeln!(out, "}},"); - writeln!(out, "reducers: {{"); + writeln!(out, ");"); + + writeln!(out); + + writeln!(out, "const reducersSchema = __reducers("); out.indent(1); for reducer in iter_reducers(module) { - writeln!(out, "{}: {{", reducer.name); - out.indent(1); - writeln!(out, "reducerName: \"{}\",", reducer.name); - writeln!( - out, - "argsType: {args_type}.getTypeScriptAlgebraicType(),", - args_type = reducer_args_type_name(&reducer.name) - ); - out.dedent(1); - writeln!(out, "}},"); + if !is_reducer_invokable(reducer) { + // Skip system-defined reducers + continue; + } + let reducer_name = &reducer.name; + let args_type = reducer_args_type_name(&reducer.name); + writeln!(out, "__reducerSchema(\"{}\", {}),", reducer_name, args_type); } out.dedent(1); - writeln!(out, "}},"); + writeln!(out, ");"); + + writeln!(out); + + writeln!(out, "const REMOTE_MODULE = {{"); + out.indent(1); writeln!(out, "versionInfo: {{"); out.indent(1); - writeln!(out, "cliVersion: \"{}\",", spacetimedb_lib_version()); + writeln!(out, "cliVersion: \"{}\" as const,", spacetimedb_lib_version()); out.dedent(1); writeln!(out, "}},"); + writeln!(out, "tables: tablesSchema.schemaType.tables,"); + writeln!(out, "reducers: reducersSchema.reducersType.reducers,"); + out.dedent(1); + writeln!(out, "}} satisfies __RemoteModule<"); + out.indent(1); + writeln!(out, "typeof tablesSchema.schemaType,"); + writeln!(out, "typeof reducersSchema.reducersType"); + out.dedent(1); + writeln!(out, ">;"); + out.dedent(1); + + writeln!(out); writeln!( out, - "// Constructors which are used by the DbConnectionImpl to -// extract type information from the generated RemoteModule. -// -// NOTE: This is not strictly necessary for `eventContextConstructor` because -// all we do is build a TypeScript object which we could have done inside the -// SDK, but if in the future we wanted to create a class this would be -// necessary because classes have methods, so we'll keep it. -eventContextConstructor: (imp: __DbConnectionImpl, event: __Event) => {{ - return {{ - ...(imp as DbConnection), - event - }} -}}, -dbViewConstructor: (imp: __DbConnectionImpl) => {{ - return new RemoteTables(imp); -}}, -reducersConstructor: (imp: __DbConnectionImpl, setReducerFlags: SetReducerFlags) => {{ - return new RemoteReducers(imp, setReducerFlags); -}}, -setReducerFlagsConstructor: () => {{ - return new SetReducerFlags(); -}}" + "export const tables = __convertToAccessorMap(tablesSchema.schemaType.tables);" + ); + writeln!( + out, + "export const reducers = __convertToAccessorMap(reducersSchema.reducersType.reducers);" ); - out.dedent(1); - writeln!(out, "}}"); - - // Define `type Reducer` enum. writeln!(out); - print_reducer_enum_defn(module, out); - - out.newline(); - - print_remote_reducers(module, out); - - out.newline(); - - print_set_reducer_flags(module, out); - - out.newline(); - - print_remote_tables(module, out); - - out.newline(); - - print_subscription_builder(module, out); - - out.newline(); - - print_db_connection(module, out); out.newline(); + // Write type aliases for EventContext, ReducerEventContext, SubscriptionEventContext, ErrorContext writeln!( out, - "export type EventContext = __EventContextInterface;" + "export type EventContext = __EventContextInterface;" ); - writeln!( out, - "export type ReducerEventContext = __ReducerEventContextInterface;" + "export type ReducerEventContext = __ReducerEventContextInterface;" ); - writeln!( out, - "export type SubscriptionEventContext = __SubscriptionEventContextInterface;" + "export type SubscriptionEventContext = __SubscriptionEventContextInterface;" ); - writeln!( out, - "export type ErrorContext = __ErrorContextInterface;" + "export type ErrorContext = __ErrorContextInterface;" ); - vec![OutputFile { - filename: "index.ts".to_string(), - code: output.into_inner(), - }] - } -} - -fn print_remote_reducers(module: &ModuleDef, out: &mut Indenter) { - writeln!(out, "export class RemoteReducers {{"); - out.indent(1); - writeln!( - out, - "constructor(private connection: __DbConnectionImpl, private setCallReducerFlags: SetReducerFlags) {{}}" - ); - out.newline(); - - for reducer in iter_reducers(module) { - // The reducer argument names and types as `ident: ty, ident: ty, ident: ty`, - // and the argument names as `ident, ident, ident` - // for passing to function call and struct literal expressions. - let mut arg_list = "".to_string(); - let mut arg_name_list = "".to_string(); - for (arg_ident, arg_ty) in &reducer.params_for_generate.elements[..] { - let arg_name = arg_ident.deref().to_case(Case::Camel); - arg_name_list += &arg_name; - arg_list += &arg_name; - arg_list += ": "; - write_type(module, &mut arg_list, arg_ty, None, None).unwrap(); - arg_list += ", "; - arg_name_list += ", "; - } - let arg_list = arg_list.trim_end_matches(", "); - let arg_name_list = arg_name_list.trim_end_matches(", "); - - let reducer_name = &reducer.name; - - if is_reducer_invokable(reducer) { - let reducer_function_name = reducer_function_name(reducer); - let reducer_variant = reducer_variant_name(&reducer.name); - if reducer.params_for_generate.elements.is_empty() { - writeln!(out, "{reducer_function_name}() {{"); - out.with_indent(|out| { - writeln!( - out, - "this.connection.callReducer(\"{reducer_name}\", new Uint8Array(0), this.setCallReducerFlags.{reducer_function_name}Flags);" - ); - }); - } else { - writeln!(out, "{reducer_function_name}({arg_list}) {{"); - out.with_indent(|out| { - writeln!(out, "const __args = {{ {arg_name_list} }};"); - writeln!(out, "let __writer = new __BinaryWriter(1024);"); - writeln!( - out, - "{reducer_variant}.serialize(__writer, __args);" - ); - writeln!(out, "let __argsBuffer = __writer.getBuffer();"); - writeln!(out, "this.connection.callReducer(\"{reducer_name}\", __argsBuffer, this.setCallReducerFlags.{reducer_function_name}Flags);"); - }); - } - writeln!(out, "}}"); - out.newline(); - } + writeln!(out); - let arg_list_padded = if arg_list.is_empty() { - String::new() - } else { - format!(", {arg_list}") - }; - let reducer_name_pascal = reducer_name.deref().to_case(Case::Pascal); writeln!( out, - "on{reducer_name_pascal}(callback: (ctx: ReducerEventContext{arg_list_padded}) => void) {{" + "export class SubscriptionBuilder extends __SubscriptionBuilderImpl<" ); out.indent(1); - writeln!(out, "this.connection.onReducer(\"{reducer_name}\", callback);"); + writeln!(out, "typeof REMOTE_MODULE"); out.dedent(1); - writeln!(out, "}}"); - out.newline(); + writeln!(out, "> {{}}"); + + writeln!(out); + writeln!(out, "export class DbConnectionBuilder extends __DbConnectionBuilder<"); + out.indent(1); + writeln!(out, "DbConnection"); + out.dedent(1); + writeln!(out, "> {{}}"); + + writeln!(out); writeln!( out, - "removeOn{reducer_name_pascal}(callback: (ctx: ReducerEventContext{arg_list_padded}) => void) {{" + "export class DbConnection extends __DbConnectionImpl {{" ); out.indent(1); - writeln!(out, "this.connection.offReducer(\"{reducer_name}\", callback);"); + writeln!(out, "static builder = (): DbConnectionBuilder => {{"); + out.indent(1); + writeln!( + out, + "return new DbConnectionBuilder(REMOTE_MODULE, (config: __DbConnectionConfig) => new DbConnection(config));" + ); out.dedent(1); - writeln!(out, "}}"); - out.newline(); - } - - out.dedent(1); - writeln!(out, "}}"); -} - -fn print_set_reducer_flags(module: &ModuleDef, out: &mut Indenter) { - writeln!(out, "export class SetReducerFlags {{"); - out.indent(1); + writeln!(out, "}};"); + writeln!(out, "subscriptionBuilder = (): SubscriptionBuilder => {{"); + out.indent(1); + writeln!(out, "return new SubscriptionBuilder(this);"); - for reducer in iter_reducers(module).filter(|r| is_reducer_invokable(r)) { - let reducer_function_name = reducer_function_name(reducer); - writeln!(out, "{reducer_function_name}Flags: __CallReducerFlags = 'FullUpdate';"); - writeln!(out, "{reducer_function_name}(flags: __CallReducerFlags) {{"); - out.with_indent(|out| { - writeln!(out, "this.{reducer_function_name}Flags = flags;"); - }); + out.dedent(1); + writeln!(out, "}};"); + out.dedent(1); writeln!(out, "}}"); out.newline(); - } - - out.dedent(1); - writeln!(out, "}}"); -} - -fn print_remote_tables(module: &ModuleDef, out: &mut Indenter) { - writeln!(out, "export class RemoteTables {{"); - out.indent(1); - writeln!(out, "constructor(private connection: __DbConnectionImpl) {{}}"); - - for table in iter_tables(module) { - writeln!(out); - let table_name = table.name.deref(); - let table_name_pascalcase = table.name.deref().to_case(Case::Pascal); - let table_name_camelcase = table.name.deref().to_case(Case::Camel); - let table_handle = table_name_pascalcase.clone() + "TableHandle"; - let type_ref = table.product_type_ref; - let row_type = type_ref_name(module, type_ref); - writeln!(out, "get {table_name_camelcase}(): {table_handle}<'{table_name}'> {{"); - out.with_indent(|out| { - writeln!(out, "// clientCache is a private property"); - writeln!( - out, - "return new {table_handle}((this.connection as unknown as {{ clientCache: __ClientCache }}).clientCache.getOrCreateTable<{row_type}>(REMOTE_MODULE.tables.{table_name}));" - ); - }); - writeln!(out, "}}"); - } - - out.dedent(1); - writeln!(out, "}}"); -} - -fn print_subscription_builder(_module: &ModuleDef, out: &mut Indenter) { - writeln!( - out, - "export class SubscriptionBuilder extends __SubscriptionBuilderImpl {{ }}" - ); -} -fn print_db_connection(_module: &ModuleDef, out: &mut Indenter) { - writeln!( - out, - "export class DbConnection extends __DbConnectionImpl {{" - ); - out.indent(1); - writeln!( - out, - "static builder = (): __DbConnectionBuilder => {{" - ); - out.indent(1); - writeln!( - out, - "return new __DbConnectionBuilder(REMOTE_MODULE, (imp: __DbConnectionImpl) => imp as DbConnection);" - ); - out.dedent(1); - writeln!(out, "}}"); - writeln!(out, "subscriptionBuilder = (): SubscriptionBuilder => {{"); - out.indent(1); - writeln!(out, "return new SubscriptionBuilder(this);"); - out.dedent(1); - writeln!(out, "}}"); - out.dedent(1); - writeln!(out, "}}"); -} - -fn print_reducer_enum_defn(module: &ModuleDef, out: &mut Indenter) { - writeln!(out, "// A type representing all the possible variants of a reducer."); - writeln!(out, "export type Reducer = never"); - for reducer in iter_reducers(module) { - writeln!( - out, - "| {{ name: \"{}\", args: {} }}", - reducer_variant_name(&reducer.name), - reducer_args_type_name(&reducer.name) - ); + vec![OutputFile { + filename: "index.ts".to_string(), + code: output.into_inner(), + }] } - writeln!(out, ";"); } -fn print_spacetimedb_imports(out: &mut Indenter) { +fn print_index_imports(out: &mut Indenter) { // All library imports are prefixed with `__` to avoid // clashing with the names of user generated types. let mut types = [ - "type AlgebraicType as __AlgebraicTypeType", - "AlgebraicType as __AlgebraicTypeValue", - "type AlgebraicTypeVariants as __AlgebraicTypeVariants", - "Identity as __Identity", - "ClientCache as __ClientCache", - "ConnectionId as __ConnectionId", - "Timestamp as __Timestamp", - "TimeDuration as __TimeDuration", + "TypeBuilder as __TypeBuilder", + "type AlgebraicTypeType as __AlgebraicTypeType", "DbConnectionBuilder as __DbConnectionBuilder", - "TableCache as __TableCache", - "BinaryWriter as __BinaryWriter", - "type TableHandle as __TableHandle", - "type CallReducerFlags as __CallReducerFlags", + "convertToAccessorMap as __convertToAccessorMap", "type EventContextInterface as __EventContextInterface", "type ReducerEventContextInterface as __ReducerEventContextInterface", "type SubscriptionEventContextInterface as __SubscriptionEventContextInterface", "type ErrorContextInterface as __ErrorContextInterface", + "type RemoteModule as __RemoteModule", "SubscriptionBuilderImpl as __SubscriptionBuilderImpl", - "BinaryReader as __BinaryReader", "DbConnectionImpl as __DbConnectionImpl", "type Event as __Event", - "deepEqual as __deepEqual", + "schema as __schema", + "table as __table", + "type Infer as __Infer", + "reducers as __reducers", + "reducerSchema as __reducerSchema", + "type DbConnectionConfig as __DbConnectionConfig", + "t as __t", ]; types.sort(); writeln!(out, "import {{"); out.indent(1); - for ty in &types { + for ty in types { writeln!(out, "{ty},"); } out.dedent(1); writeln!(out, "}} from \"spacetimedb\";"); } -fn print_file_header(output: &mut Indenter, include_version: bool) { +fn print_type_builder_imports(out: &mut Indenter) { + // All library imports are prefixed with `__` to avoid + // clashing with the names of user generated types. + let mut types = [ + "TypeBuilder as __TypeBuilder", + "type AlgebraicTypeType as __AlgebraicTypeType", + "type Infer as __Infer", + "t as __t", + ]; + types.sort(); + writeln!(out, "import {{"); + out.indent(1); + for ty in types { + writeln!(out, "{ty},"); + } + out.dedent(1); + writeln!(out, "}} from \"spacetimedb\";"); +} + +fn print_file_header(output: &mut Indenter, include_version: bool, type_builder_only: bool) { print_auto_generated_file_comment(output); if include_version { print_auto_generated_version_comment(output); } print_lint_suppression(output); - print_spacetimedb_imports(output); + if type_builder_only { + print_type_builder_imports(output); + } else { + print_index_imports(output); + } } fn print_lint_suppression(output: &mut Indenter) { @@ -721,220 +404,195 @@ fn print_lint_suppression(output: &mut Indenter) { writeln!(output, "/* tslint:disable */"); } -fn write_get_algebraic_type_for_product( - module: &ModuleDef, - out: &mut Indenter, - type_cache_name: &str, - elements: &[(Identifier, AlgebraicTypeUse)], -) { - writeln!( - out, - "/** -* A function which returns this type represented as an AlgebraicType. -* This function is derived from the AlgebraicType used to generate this type. -*/" - ); - writeln!(out, "getTypeScriptAlgebraicType(): __AlgebraicTypeType {{"); - { - out.indent(1); - writeln!(out, "if ({type_cache_name}) return {type_cache_name};"); - // initialization is split in two because of recursive types - writeln!( - out, - "{type_cache_name} = __AlgebraicTypeValue.Product({{ elements: [] }});" - ); - writeln!(out, "{type_cache_name}.value.elements.push("); - out.indent(1); - convert_product_type_elements(module, out, elements, ""); - out.dedent(1); - writeln!(out, ");"); - writeln!(out, "return {type_cache_name};"); - out.dedent(1); +/// e.g. +/// ```ts +/// export default { +/// x: __t.f32(), +/// y: __t.f32(), +/// fooBar: __t.string(), +/// }; +/// ``` +fn define_body_for_reducer(module: &ModuleDef, out: &mut Indenter, params: &[(Identifier, AlgebraicTypeUse)]) { + write!(out, "export default {{"); + if params.is_empty() { + writeln!(out, "}};"); + } else { + writeln!(out); + out.with_indent(|out| write_object_type_builder_fields(module, out, params, true).unwrap()); + writeln!(out, "}};"); } - writeln!(out, "}},"); } +/// e.g. +/// ```ts +/// export default __t.object('Point', { +/// x: __t.f32(), +/// y: __t.f32(), +/// fooBar: __t.string(), +/// }); +/// ``` fn define_body_for_product( module: &ModuleDef, out: &mut Indenter, name: &str, elements: &[(Identifier, AlgebraicTypeUse)], ) { - write!(out, "export type {name} = {{"); + write!(out, "export default __t.object(\"{name}\", {{"); if elements.is_empty() { - writeln!(out, "}};"); + writeln!(out, "}});"); } else { writeln!(out); - out.with_indent(|out| write_arglist_no_delimiters(module, out, elements, None, true).unwrap()); - writeln!(out, "}};"); + out.with_indent(|out| write_object_type_builder_fields(module, out, elements, true).unwrap()); + writeln!(out, "}});"); } - - let type_cache_name = &*format!("_cached_{name}_type_value"); - writeln!(out, "let {type_cache_name}: __AlgebraicTypeType | null = null;"); out.newline(); +} - writeln!( - out, - "/** - * An object for generated helper functions. - */" - ); - writeln!(out, "export const {name} = {{"); - out.indent(1); - write_get_algebraic_type_for_product(module, out, type_cache_name, elements); - writeln!(out); - - writeln!(out, "serialize(writer: __BinaryWriter, value: {name}): void {{"); - out.indent(1); - writeln!( - out, - "__AlgebraicTypeValue.serializeValue(writer, {name}.getTypeScriptAlgebraicType(), value);" - ); - out.dedent(1); - writeln!(out, "}},"); - writeln!(out); - - writeln!(out, "deserialize(reader: __BinaryReader): {name} {{"); +fn write_table_opts(module: &ModuleDef, out: &mut Indenter, table: &TableDef) { + let type_ref = table.product_type_ref; + let product_def = module.typespace_for_generate()[type_ref].as_product().unwrap(); + writeln!(out, "name: '{}',", table.name.deref()); + writeln!(out, "indexes: ["); out.indent(1); - writeln!( - out, - "return __AlgebraicTypeValue.deserializeValue(reader, {name}.getTypeScriptAlgebraicType());" - ); - out.dedent(1); - writeln!(out, "}},"); - writeln!(out); - + for index_def in iter_indexes(table) { + if !index_def.generated() { + // Skip system-defined indexes + continue; + } + match &index_def.algorithm { + IndexAlgorithm::BTree(BTreeAlgorithm { columns }) => { + let get_name_and_type = |col_pos: ColId| { + let (field_name, field_type) = &product_def.elements[col_pos.idx()]; + let name_camel = field_name.deref().to_case(Case::Camel); + (name_camel, field_type) + }; + writeln!(out, "{{ name: '{}', algorithm: 'btree', columns: [", index_def.name); + out.indent(1); + for col_id in columns.iter() { + writeln!(out, "'{}',", get_name_and_type(col_id).0); + } + out.dedent(1); + writeln!(out, "] }},"); + } + IndexAlgorithm::Direct(_) => { + // Direct indexes are not implemented yet. + continue; + } + _ => todo!(), + }; + } out.dedent(1); - writeln!(out, "}}"); - - out.newline(); - - writeln!(out, "export default {name};"); - - out.newline(); + writeln!(out, "],"); } -fn write_arglist_no_delimiters( +/// e.g. +/// ```ts +/// x: __t.f32(), +/// y: __t.f32(), +/// fooBar: __t.string(), +/// ``` +fn write_object_type_builder_fields( module: &ModuleDef, - out: &mut impl Write, + out: &mut Indenter, elements: &[(Identifier, AlgebraicTypeUse)], - prefix: Option<&str>, convert_case: bool, ) -> anyhow::Result<()> { for (ident, ty) in elements { - if let Some(prefix) = prefix { - write!(out, "{prefix} ")?; - } - let name = if convert_case { ident.deref().to_case(Case::Camel) } else { ident.deref().into() }; - write!(out, "{name}: ")?; - write_type(module, out, ty, None, None)?; - writeln!(out, ",")?; + write_type_builder_field(module, out, &name, ty)?; } Ok(()) } -fn write_sum_variant_type(module: &ModuleDef, out: &mut Indenter, ident: &Identifier, ty: &AlgebraicTypeUse) { - let name = ident.deref().to_case(Case::Pascal); - write!(out, "export type {name} = "); - - // If the contained type is the unit type, i.e. this variant has no members, - // write only the tag. - // ``` - // { tag: "Foo" } - // ``` - write!(out, "{{ "); - write!(out, "tag: \"{name}\""); - - // If the contained type is not the unit type, write the tag and the value. - // ``` - // { tag: "Bar", value: BarType } - // { tag: "Bar", value: number } - // { tag: "Bar", value: string } - // ``` - // Note you could alternatively do: - // ``` - // { tag: "Bar" } & BarType - // ``` - // for non-primitive types but that doesn't extend to primitives. - // Another alternative would be to name the value field the same as the tag field, but lowercased - // ``` - // { tag: "Bar", bar: BarType } - // { tag: "Bar", bar: number } - // { tag: "Bar", bar: string } - // ``` - // but this is a departure from our previous convention and is not much different. - if !matches!(ty, AlgebraicTypeUse::Unit) { - write!(out, ", value: "); - write_type(module, out, ty, None, Some("Type")).unwrap(); - } - - writeln!(out, " }};"); -} +fn write_type_builder_field(module: &ModuleDef, out: &mut Indenter, name: &str, ty: &AlgebraicTypeUse) -> fmt::Result { + // Do we need a getter? (Option/Array only if their inner is a Ref) + let needs_getter = match ty { + AlgebraicTypeUse::Ref(_) => true, + AlgebraicTypeUse::Option(inner) | AlgebraicTypeUse::Array(inner) => { + matches!(inner.as_ref(), AlgebraicTypeUse::Ref(_)) + } + _ => false, + }; -fn write_variant_types(module: &ModuleDef, out: &mut Indenter, variants: &[(Identifier, AlgebraicTypeUse)]) { - // Write all the variant types. - for (ident, ty) in variants { - write_sum_variant_type(module, out, ident, ty); + if needs_getter { + writeln!(out, "get {name}() {{"); + out.indent(1); + write!(out, "return "); + write_type_builder(module, out, ty)?; + writeln!(out, ";"); + out.dedent(1); + writeln!(out, "}},"); + } else { + write!(out, "{name}: "); + write_type_builder(module, out, ty)?; + writeln!(out, ","); } -} -fn write_variant_constructors( - module: &ModuleDef, - out: &mut Indenter, - name: &str, - variants: &[(Identifier, AlgebraicTypeUse)], -) { - // Write all the variant constructors. - // Write all of the variant constructors. - for (ident, ty) in variants { - if matches!(ty, AlgebraicTypeUse::Unit) { - // If the variant has no members, we can export a simple object. - // ``` - // Foo: { tag: "Foo" } = { tag: "Foo" } as const, - // ``` - write!(out, "{ident}: {{ tag: \"{ident}\" }} as const,"); - writeln!(out); - continue; - } - let variant_name = ident.deref().to_case(Case::Pascal); - write!(out, "{variant_name}: (value: "); - write_type(module, out, ty, None, None).unwrap(); - writeln!( - out, - "): {name}Variants.{variant_name} => ({{ tag: \"{variant_name}\", value }})," - ); - } + Ok(()) } -fn write_get_algebraic_type_for_sum( - module: &ModuleDef, - out: &mut Indenter, - type_cache_name: &str, - variants: &[(Identifier, AlgebraicTypeUse)], -) { - writeln!(out, "getTypeScriptAlgebraicType(): __AlgebraicTypeType {{"); - { - indent_scope!(out); - writeln!(out, "if ({type_cache_name}) return {type_cache_name};"); - // initialization is split in two because of recursive types - writeln!(out, "{type_cache_name} = __AlgebraicTypeValue.Sum({{ variants: [] }});"); - writeln!(out, "{type_cache_name}.value.variants.push("); - out.indent(1); - convert_sum_type_variants(module, &mut out, variants, ""); - out.dedent(1); - writeln!(out, ");"); - writeln!(out, "return {type_cache_name};"); +/// e.g. `__t.option(__t.i32())`, `__t.string()` +fn write_type_builder(module: &ModuleDef, out: &mut W, ty: &AlgebraicTypeUse) -> fmt::Result { + match ty { + AlgebraicTypeUse::Unit => write!(out, "__t.unit()")?, + AlgebraicTypeUse::Never => write!(out, "__t.never()")?, + AlgebraicTypeUse::Identity => write!(out, "__t.identity()")?, + AlgebraicTypeUse::ConnectionId => write!(out, "__t.connectionId()")?, + AlgebraicTypeUse::Timestamp => write!(out, "__t.timestamp()")?, + AlgebraicTypeUse::TimeDuration => write!(out, "__t.timeDuration()")?, + AlgebraicTypeUse::ScheduleAt => write!(out, "__t.scheduleAt()")?, + AlgebraicTypeUse::Option(inner_ty) => { + write!(out, "__t.option(")?; + write_type_builder(module, out, inner_ty)?; + write!(out, ")")?; + } + AlgebraicTypeUse::Primitive(prim) => match prim { + PrimitiveType::Bool => write!(out, "__t.bool()")?, + PrimitiveType::I8 => write!(out, "__t.i8()")?, + PrimitiveType::U8 => write!(out, "__t.u8()")?, + PrimitiveType::I16 => write!(out, "__t.i16()")?, + PrimitiveType::U16 => write!(out, "__t.u16()")?, + PrimitiveType::I32 => write!(out, "__t.i32()")?, + PrimitiveType::U32 => write!(out, "__t.u32()")?, + PrimitiveType::I64 => write!(out, "__t.i64()")?, + PrimitiveType::U64 => write!(out, "__t.u64()")?, + PrimitiveType::I128 => write!(out, "__t.i128()")?, + PrimitiveType::U128 => write!(out, "__t.u128()")?, + PrimitiveType::I256 => write!(out, "__t.i256()")?, + PrimitiveType::U256 => write!(out, "__t.u256()")?, + PrimitiveType::F32 => write!(out, "__t.f32()")?, + PrimitiveType::F64 => write!(out, "__t.f64()")?, + }, + AlgebraicTypeUse::String => write!(out, "__t.string()")?, + AlgebraicTypeUse::Array(elem_ty) => { + if matches!(&**elem_ty, AlgebraicTypeUse::Primitive(PrimitiveType::U8)) { + return write!(out, "__t.byteArray()"); + } + write!(out, "__t.array(")?; + write_type_builder(module, out, elem_ty)?; + write!(out, ")")?; + } + AlgebraicTypeUse::Ref(r) => { + write!(out, "{}", type_ref_name(module, *r))?; + } } - writeln!(out, "}},"); + Ok(()) } +/// e.g. +/// ```ts +/// // The tagged union or sum type for the algebraic type `Option`. +/// export default __t.enum("Option", { +/// none: __t.unit(), +/// some: { value: __t.i32() }, +/// }); +/// ``` fn define_body_for_sum( module: &ModuleDef, out: &mut Indenter, @@ -942,71 +600,15 @@ fn define_body_for_sum( variants: &[(Identifier, AlgebraicTypeUse)], ) { writeln!(out, "// The tagged union or sum type for the algebraic type `{name}`."); - write!(out, "export type {name} = "); - - let names = variants - .iter() - .map(|(ident, _)| format!("{name}Variants.{}", ident.deref().to_case(Case::Pascal))) - .collect::>() - .join(" |\n "); - - if variants.is_empty() { - writeln!(out, "never;"); - } else { - writeln!(out, "{names};"); + write!(out, "const {name}"); + if name == "AlgebraicType" { + write!(out, ": __TypeBuilder<__AlgebraicTypeType, __AlgebraicTypeType>"); } - + write!(out, " = __t.enum(\"{name}\", {{"); + out.with_indent(|out| write_object_type_builder_fields(module, out, variants, false).unwrap()); + writeln!(out, "}});"); out.newline(); - - let type_cache_name = &*format!("_cached_{name}_type_value"); - writeln!(out, "let {type_cache_name}: __AlgebraicTypeType | null = null;"); - out.newline(); - - // Write the runtime value with helper functions - writeln!(out, "// A value with helper functions to construct the type."); - writeln!(out, "export const {name} = {{"); - out.indent(1); - - // Write all of the variant constructors. - writeln!( - out, - "// Helper functions for constructing each variant of the tagged union. -// ``` -// const foo = Foo.A(42); -// assert!(foo.tag === \"A\"); -// assert!(foo.value === 42); -// ```" - ); - write_variant_constructors(module, out, name, variants); - writeln!(out); - - // Write the function that generates the algebraic type. - write_get_algebraic_type_for_sum(module, out, type_cache_name, variants); - writeln!(out); - - writeln!( - out, - "serialize(writer: __BinaryWriter, value: {name}): void {{ - __AlgebraicTypeValue.serializeValue(writer, {name}.getTypeScriptAlgebraicType(), value); -}}," - ); - writeln!(out); - - writeln!( - out, - "deserialize(reader: __BinaryReader): {name} {{ - return __AlgebraicTypeValue.deserializeValue(reader, {name}.getTypeScriptAlgebraicType()); -}}," - ); - writeln!(out); - - out.dedent(1); - - writeln!(out, "}}"); - out.newline(); - writeln!(out, "export default {name};"); - out.newline(); } @@ -1019,34 +621,18 @@ fn type_module_name(type_name: &ScopedTypeName) -> String { collect_case(Case::Snake, type_name.name_segments()) + "_type" } -fn variants_module_name(type_name: &ScopedTypeName) -> String { - collect_case(Case::Snake, type_name.name_segments()) + "_variants" -} - fn table_module_name(table_name: &Identifier) -> String { table_name.deref().to_case(Case::Snake) + "_table" } -fn table_method_name(table_name: &Identifier) -> String { - table_name.deref().to_case(Case::Camel) -} - fn reducer_args_type_name(reducer_name: &Identifier) -> String { reducer_name.deref().to_case(Case::Pascal) } -fn reducer_variant_name(reducer_name: &Identifier) -> String { - reducer_name.deref().to_case(Case::Pascal) -} - fn reducer_module_name(reducer_name: &Identifier) -> String { reducer_name.deref().to_case(Case::Snake) + "_reducer" } -fn reducer_function_name(reducer: &ReducerDef) -> String { - reducer.name.deref().to_case(Case::Camel) -} - pub fn type_name(module: &ModuleDef, ty: &AlgebraicTypeUse) -> String { let mut s = String::new(); write_type(module, &mut s, ty, None, None).unwrap(); @@ -1086,13 +672,13 @@ pub fn write_type( match ty { AlgebraicTypeUse::Unit => write!(out, "void")?, AlgebraicTypeUse::Never => write!(out, "never")?, - AlgebraicTypeUse::Identity => write!(out, "__Identity")?, - AlgebraicTypeUse::ConnectionId => write!(out, "__ConnectionId")?, - AlgebraicTypeUse::Timestamp => write!(out, "__Timestamp")?, - AlgebraicTypeUse::TimeDuration => write!(out, "__TimeDuration")?, + AlgebraicTypeUse::Identity => write!(out, "__Infer")?, + AlgebraicTypeUse::ConnectionId => write!(out, "__Infer")?, + AlgebraicTypeUse::Timestamp => write!(out, "__Infer")?, + AlgebraicTypeUse::TimeDuration => write!(out, "__Infer")?, AlgebraicTypeUse::ScheduleAt => write!( out, - "{{ tag: \"Interval\", value: __TimeDuration }} | {{ tag: \"Time\", value: __Timestamp }}" + "{{ tag: \"Interval\", value: __Infer }} | {{ tag: \"Time\", value: __Infer }}" )?, AlgebraicTypeUse::Option(inner_ty) => { write_type(module, out, inner_ty, ref_prefix, ref_suffix)?; @@ -1132,6 +718,7 @@ pub fn write_type( write!(out, "[]")?; } AlgebraicTypeUse::Ref(r) => { + write!(out, "__Infer( if let Some(suffix) = ref_suffix { write!(out, "{suffix}")?; } + write!(out, ">")?; } } Ok(()) } -fn convert_algebraic_type<'a>( - module: &'a ModuleDef, - out: &mut Indenter, - ty: &'a AlgebraicTypeUse, - ref_prefix: &'a str, -) { - match ty { - AlgebraicTypeUse::ScheduleAt => write!(out, "__AlgebraicTypeValue.createScheduleAtType()"), - AlgebraicTypeUse::Identity => write!(out, "__AlgebraicTypeValue.createIdentityType()"), - AlgebraicTypeUse::ConnectionId => write!(out, "__AlgebraicTypeValue.createConnectionIdType()"), - AlgebraicTypeUse::Timestamp => write!(out, "__AlgebraicTypeValue.createTimestampType()"), - AlgebraicTypeUse::TimeDuration => write!(out, "__AlgebraicTypeValue.createTimeDurationType()"), - AlgebraicTypeUse::Option(inner_ty) => { - write!(out, "__AlgebraicTypeValue.createOptionType("); - convert_algebraic_type(module, out, inner_ty, ref_prefix); - write!(out, ")"); - } - AlgebraicTypeUse::Array(ty) => { - write!(out, "__AlgebraicTypeValue.Array("); - convert_algebraic_type(module, out, ty, ref_prefix); - write!(out, ")"); - } - AlgebraicTypeUse::Ref(r) => write!( - out, - "{ref_prefix}{}.getTypeScriptAlgebraicType()", - type_ref_name(module, *r) - ), - AlgebraicTypeUse::Primitive(prim) => { - write!(out, "__AlgebraicTypeValue.{prim:?}"); - } - AlgebraicTypeUse::Unit => write!(out, "__AlgebraicTypeValue.Product({{ elements: [] }})"), - AlgebraicTypeUse::Never => unimplemented!(), - AlgebraicTypeUse::String => write!(out, "__AlgebraicTypeValue.String"), - } -} - -fn convert_sum_type_variants<'a>( - module: &'a ModuleDef, - out: &mut Indenter, - variants: &'a [(Identifier, AlgebraicTypeUse)], - ref_prefix: &'a str, -) { - for (ident, ty) in variants { - write!(out, "{{ name: \"{ident}\", algebraicType: ",); - convert_algebraic_type(module, out, ty, ref_prefix); - writeln!(out, " }},"); - } -} - -fn convert_product_type_elements<'a>( - module: &'a ModuleDef, - out: &mut Indenter, - elements: &'a [(Identifier, AlgebraicTypeUse)], - ref_prefix: &'a str, -) { - for (ident, ty) in elements { - write!( - out, - "{{ name: \"{}\", algebraicType: ", - ident.deref().to_case(Case::Camel) - ); - convert_algebraic_type(module, out, ty, ref_prefix); - writeln!(out, " }},"); - } -} - /// Print imports for each of the `imports`. fn print_imports(module: &ModuleDef, out: &mut Indenter, imports: Imports, suffix: Option<&str>) { for typeref in imports { let module_name = type_ref_module_name(module, typeref); let type_name = type_ref_name(module, typeref); if let Some(suffix) = suffix { - writeln!( - out, - "import {{ {type_name} as {type_name}{suffix} }} from \"./{module_name}\";" - ); - writeln!(out, "// Mark import as potentially unused"); - writeln!(out, "declare type __keep_{type_name}{suffix} = {type_name}{suffix};"); + writeln!(out, "import {type_name}{suffix} from \"./{module_name}\";"); } else { - writeln!(out, "import {{ {type_name} }} from \"./{module_name}\";"); - writeln!(out, "// Mark import as potentially unused"); - writeln!(out, "declare type __keep_{type_name} = {type_name};"); + writeln!(out, "import {type_name} from \"./{module_name}\";"); } } } diff --git a/crates/update/src/proxy.rs b/crates/update/src/proxy.rs index 95d8ef8f2ae..51296ee85f4 100644 --- a/crates/update/src/proxy.rs +++ b/crates/update/src/proxy.rs @@ -102,7 +102,7 @@ fn exec_replace(cmd: &mut Command) -> io::Result { } unsafe { if SetConsoleCtrlHandler(Some(ctrlc_handler), TRUE) == FALSE { - return Err(io::Error::new(io::ErrorKind::Other, "Unable to set console handler")); + return Err(io::Error::other("Unable to set console handler")); } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bd66da9016c..5a173665ccb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -57,8 +57,8 @@ importers: specifier: ^3.3.3 version: 3.6.2 react: - specifier: ^18.0.0 || ^19.0.0-0 || ^19.0.0 - version: 18.3.1 + specifier: ^19.0.0 + version: 19.2.0 undici: specifier: ^6.19.2 version: 6.21.3 @@ -204,6 +204,37 @@ importers: specifier: ^7.1.5 version: 7.1.5(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4) + crates/bindings-typescript/test-react-router-app: + dependencies: + react: + specifier: ^18.3.1 + version: 18.3.1 + react-dom: + specifier: ^18.3.1 + version: 18.3.1(react@18.3.1) + react-router-dom: + specifier: ^7.9.4 + version: 7.9.5(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + devDependencies: + '@types/react': + specifier: ^18.3.3 + version: 18.3.23 + '@types/react-dom': + specifier: ^18.3.0 + version: 18.3.7(@types/react@18.3.23) + '@types/react-router-dom': + specifier: ^5.3.3 + version: 5.3.3 + '@vitejs/plugin-react': + specifier: ^4.3.1 + version: 4.7.0(vite@7.1.5(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4)) + typescript: + specifier: ^5.2.2 + version: 5.9.3 + vite: + specifier: ^7.1.5 + version: 7.1.5(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4) + docs: dependencies: '@docusaurus/core': @@ -211,7 +242,7 @@ importers: version: 3.9.1(@mdx-js/react@3.1.1(@types/react@19.2.0)(react@19.2.0))(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(typescript@5.6.3) '@docusaurus/plugin-content-docs': specifier: ^3.9.2 - version: 3.9.2(@mdx-js/react@3.1.1(@types/react@19.2.0)(react@19.2.0))(debug@4.4.3)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(typescript@5.6.3) + version: 3.9.2(@mdx-js/react@3.1.1(@types/react@19.2.0)(react@19.2.0))(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(typescript@5.6.3) '@docusaurus/preset-classic': specifier: 3.9.1 version: 3.9.1(@algolia/client-search@5.39.0)(@mdx-js/react@3.1.1(@types/react@19.2.0)(react@19.2.0))(@types/react@19.2.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(search-insights@2.17.3)(typescript@5.6.3) @@ -4522,6 +4553,10 @@ packages: resolution: {integrity: sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==} engines: {node: '>= 0.6'} + cookie@1.0.2: + resolution: {integrity: sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==} + engines: {node: '>=18'} + copy-webpack-plugin@11.0.0: resolution: {integrity: sha512-fX2MWpamkW0hZxMEg0+mYnA40LTosOSa5TqZ9GYIBzyJa9C3QUaMPSE2xAi/buNr8u89SfD9wHSQVBzrRa/SOQ==} engines: {node: '>= 14.15.0'} @@ -7511,11 +7546,28 @@ packages: peerDependencies: react: '>=15' + react-router-dom@7.9.5: + resolution: {integrity: sha512-mkEmq/K8tKN63Ae2M7Xgz3c9l9YNbY+NHH6NNeUmLA3kDkhKXRsNb/ZpxaEunvGo2/3YXdk5EJU3Hxp3ocaBPw==} + engines: {node: '>=20.0.0'} + peerDependencies: + react: '>=18' + react-dom: '>=18' + react-router@5.3.4: resolution: {integrity: sha512-Ys9K+ppnJah3QuaRiLxk+jDWOR1MekYQrlytiXxC1RyfbdsZkS5pvKAzCCr031xHixZwpnsYNT5xysdFHQaYsA==} peerDependencies: react: '>=15' + react-router@7.9.5: + resolution: {integrity: sha512-JmxqrnBZ6E9hWmf02jzNn9Jm3UqyeimyiwzD69NjxGySG6lIz/1LVPsoTCwN7NBX2XjCEa1LIX5EMz1j2b6u6A==} + engines: {node: '>=20.0.0'} + peerDependencies: + react: '>=18' + react-dom: '>=18' + peerDependenciesMeta: + react-dom: + optional: true + react-style-singleton@2.2.3: resolution: {integrity: sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==} engines: {node: '>=10'} @@ -7827,6 +7879,9 @@ packages: resolution: {integrity: sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==} engines: {node: '>= 0.8.0'} + set-cookie-parser@2.7.2: + resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==} + set-function-length@1.2.2: resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==} engines: {node: '>= 0.4'} @@ -9131,10 +9186,10 @@ snapshots: '@babel/helper-compilation-targets': 7.27.2 '@babel/helper-module-transforms': 7.28.3(@babel/core@7.28.3) '@babel/helpers': 7.28.3 - '@babel/parser': 7.28.3 + '@babel/parser': 7.28.4 '@babel/template': 7.27.2 - '@babel/traverse': 7.28.3 - '@babel/types': 7.28.2 + '@babel/traverse': 7.28.4 + '@babel/types': 7.28.4 convert-source-map: 2.0.0 debug: 4.4.3 gensync: 1.0.0-beta.2 @@ -9145,8 +9200,8 @@ snapshots: '@babel/generator@7.28.3': dependencies: - '@babel/parser': 7.28.3 - '@babel/types': 7.28.2 + '@babel/parser': 7.28.4 + '@babel/types': 7.28.4 '@jridgewell/gen-mapping': 0.3.13 '@jridgewell/trace-mapping': 0.3.30 jsesc: 3.1.0 @@ -9206,7 +9261,7 @@ snapshots: '@babel/helper-module-imports@7.27.1': dependencies: '@babel/traverse': 7.28.4 - '@babel/types': 7.28.2 + '@babel/types': 7.28.4 transitivePeerDependencies: - supports-color @@ -9215,7 +9270,7 @@ snapshots: '@babel/core': 7.28.3 '@babel/helper-module-imports': 7.27.1 '@babel/helper-validator-identifier': 7.27.1 - '@babel/traverse': 7.28.3 + '@babel/traverse': 7.28.4 transitivePeerDependencies: - supports-color @@ -9267,7 +9322,7 @@ snapshots: '@babel/helpers@7.28.3': dependencies: '@babel/template': 7.27.2 - '@babel/types': 7.28.2 + '@babel/types': 7.28.4 '@babel/parser@7.28.3': dependencies: @@ -9862,8 +9917,8 @@ snapshots: '@babel/template@7.27.2': dependencies: '@babel/code-frame': 7.27.1 - '@babel/parser': 7.28.3 - '@babel/types': 7.28.2 + '@babel/parser': 7.28.4 + '@babel/types': 7.28.4 '@babel/traverse@7.28.3': dependencies: @@ -10711,6 +10766,46 @@ snapshots: - webpack-cli '@docusaurus/plugin-content-docs@3.9.2(@mdx-js/react@3.1.1(@types/react@19.2.0)(react@19.2.0))(debug@4.4.3)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(typescript@5.6.3)': + dependencies: + '@docusaurus/core': 3.9.2(@mdx-js/react@3.1.1(@types/react@19.2.0)(react@19.2.0))(debug@4.4.3)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(typescript@5.6.3) + '@docusaurus/logger': 3.9.2 + '@docusaurus/mdx-loader': 3.9.2(react-dom@19.2.0(react@19.2.0))(react@19.2.0) + '@docusaurus/module-type-aliases': 3.9.2(react-dom@19.2.0(react@19.2.0))(react@19.2.0) + '@docusaurus/theme-common': 3.9.2(@docusaurus/plugin-content-docs@3.9.2(@mdx-js/react@3.1.1(@types/react@19.2.0)(react@19.2.0))(debug@4.4.3)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(typescript@5.6.3))(react-dom@19.2.0(react@19.2.0))(react@19.2.0) + '@docusaurus/types': 3.9.2(react-dom@19.2.0(react@19.2.0))(react@19.2.0) + '@docusaurus/utils': 3.9.2(react-dom@19.2.0(react@19.2.0))(react@19.2.0) + '@docusaurus/utils-common': 3.9.2(react-dom@19.2.0(react@19.2.0))(react@19.2.0) + '@docusaurus/utils-validation': 3.9.2(react-dom@19.2.0(react@19.2.0))(react@19.2.0) + '@types/react-router-config': 5.0.11 + combine-promises: 1.2.0 + fs-extra: 11.3.2 + js-yaml: 4.1.0 + lodash: 4.17.21 + react: 19.2.0 + react-dom: 19.2.0(react@19.2.0) + schema-dts: 1.1.5 + tslib: 2.8.1 + utility-types: 3.11.0 + webpack: 5.102.0 + transitivePeerDependencies: + - '@docusaurus/faster' + - '@mdx-js/react' + - '@parcel/css' + - '@rspack/core' + - '@swc/core' + - '@swc/css' + - bufferutil + - csso + - debug + - esbuild + - lightningcss + - supports-color + - typescript + - uglify-js + - utf-8-validate + - webpack-cli + + '@docusaurus/plugin-content-docs@3.9.2(@mdx-js/react@3.1.1(@types/react@19.2.0)(react@19.2.0))(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(typescript@5.6.3)': dependencies: '@docusaurus/core': 3.9.2(@mdx-js/react@3.1.1(@types/react@19.2.0)(react@19.2.0))(debug@4.4.3)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(typescript@5.6.3) '@docusaurus/logger': 3.9.2 @@ -11095,7 +11190,7 @@ snapshots: dependencies: '@docusaurus/mdx-loader': 3.9.1(react-dom@19.2.0(react@19.2.0))(react@19.2.0) '@docusaurus/module-type-aliases': 3.9.1(react-dom@19.2.0(react@19.2.0))(react@19.2.0) - '@docusaurus/plugin-content-docs': 3.9.2(@mdx-js/react@3.1.1(@types/react@19.2.0)(react@19.2.0))(debug@4.4.3)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(typescript@5.6.3) + '@docusaurus/plugin-content-docs': 3.9.2(@mdx-js/react@3.1.1(@types/react@19.2.0)(react@19.2.0))(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(typescript@5.6.3) '@docusaurus/utils': 3.9.1(react-dom@19.2.0(react@19.2.0))(react@19.2.0) '@docusaurus/utils-common': 3.9.1(react-dom@19.2.0(react@19.2.0))(react@19.2.0) '@types/history': 4.7.11 @@ -11115,7 +11210,7 @@ snapshots: - uglify-js - webpack-cli - '@docusaurus/theme-common@3.9.2(@docusaurus/plugin-content-docs@3.9.2(@mdx-js/react@3.1.1(@types/react@19.2.0)(react@19.2.0))(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(typescript@5.6.3))(react-dom@19.2.0(react@19.2.0))(react@19.2.0)': + '@docusaurus/theme-common@3.9.2(@docusaurus/plugin-content-docs@3.9.2(@mdx-js/react@3.1.1(@types/react@19.2.0)(react@19.2.0))(debug@4.4.3)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(typescript@5.6.3))(react-dom@19.2.0(react@19.2.0))(react@19.2.0)': dependencies: '@docusaurus/mdx-loader': 3.9.2(react-dom@19.2.0(react@19.2.0))(react@19.2.0) '@docusaurus/module-type-aliases': 3.9.2(react-dom@19.2.0(react@19.2.0))(react@19.2.0) @@ -11139,6 +11234,30 @@ snapshots: - uglify-js - webpack-cli + '@docusaurus/theme-common@3.9.2(@docusaurus/plugin-content-docs@3.9.2(@mdx-js/react@3.1.1(@types/react@19.2.0)(react@19.2.0))(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(typescript@5.6.3))(react-dom@19.2.0(react@19.2.0))(react@19.2.0)': + dependencies: + '@docusaurus/mdx-loader': 3.9.2(react-dom@19.2.0(react@19.2.0))(react@19.2.0) + '@docusaurus/module-type-aliases': 3.9.2(react-dom@19.2.0(react@19.2.0))(react@19.2.0) + '@docusaurus/plugin-content-docs': 3.9.2(@mdx-js/react@3.1.1(@types/react@19.2.0)(react@19.2.0))(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(typescript@5.6.3) + '@docusaurus/utils': 3.9.2(react-dom@19.2.0(react@19.2.0))(react@19.2.0) + '@docusaurus/utils-common': 3.9.2(react-dom@19.2.0(react@19.2.0))(react@19.2.0) + '@types/history': 4.7.11 + '@types/react': 18.3.23 + '@types/react-router-config': 5.0.11 + clsx: 2.1.1 + parse-numeric-range: 1.3.0 + prism-react-renderer: 2.4.1(react@19.2.0) + react: 19.2.0 + react-dom: 19.2.0(react@19.2.0) + tslib: 2.8.1 + utility-types: 3.11.0 + transitivePeerDependencies: + - '@swc/core' + - esbuild + - supports-color + - uglify-js + - webpack-cli + '@docusaurus/theme-search-algolia@3.9.1(@algolia/client-search@5.39.0)(@mdx-js/react@3.1.1(@types/react@19.2.0)(react@19.2.0))(@types/react@19.2.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(search-insights@2.17.3)(typescript@5.6.3)': dependencies: '@docsearch/react': 4.2.0(@algolia/client-search@5.39.0)(@types/react@19.2.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(search-insights@2.17.3) @@ -13175,24 +13294,24 @@ snapshots: '@types/babel__core@7.20.5': dependencies: - '@babel/parser': 7.28.3 - '@babel/types': 7.28.2 + '@babel/parser': 7.28.4 + '@babel/types': 7.28.4 '@types/babel__generator': 7.27.0 '@types/babel__template': 7.4.4 '@types/babel__traverse': 7.28.0 '@types/babel__generator@7.27.0': dependencies: - '@babel/types': 7.28.2 + '@babel/types': 7.28.4 '@types/babel__template@7.4.4': dependencies: - '@babel/parser': 7.28.3 - '@babel/types': 7.28.2 + '@babel/parser': 7.28.4 + '@babel/types': 7.28.4 '@types/babel__traverse@7.28.0': dependencies: - '@babel/types': 7.28.2 + '@babel/types': 7.28.4 '@types/body-parser@1.19.6': dependencies: @@ -15280,6 +15399,8 @@ snapshots: cookie@0.7.1: {} + cookie@1.0.2: {} + copy-webpack-plugin@11.0.0(webpack@5.102.0): dependencies: fast-glob: 3.3.3 @@ -18813,6 +18934,12 @@ snapshots: tiny-invariant: 1.3.3 tiny-warning: 1.0.3 + react-router-dom@7.9.5(react-dom@18.3.1(react@18.3.1))(react@18.3.1): + dependencies: + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + react-router: 7.9.5(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + react-router@5.3.4(react@19.2.0): dependencies: '@babel/runtime': 7.28.4 @@ -18826,6 +18953,14 @@ snapshots: tiny-invariant: 1.3.3 tiny-warning: 1.0.3 + react-router@7.9.5(react-dom@18.3.1(react@18.3.1))(react@18.3.1): + dependencies: + cookie: 1.0.2 + react: 18.3.1 + set-cookie-parser: 2.7.2 + optionalDependencies: + react-dom: 18.3.1(react@18.3.1) + react-style-singleton@2.2.3(@types/react@19.2.0)(react@19.2.0): dependencies: get-nonce: 1.0.1 @@ -19262,6 +19397,8 @@ snapshots: transitivePeerDependencies: - supports-color + set-cookie-parser@2.7.2: {} + set-function-length@1.2.2: dependencies: define-data-property: 1.1.4