@evolu/common 6.0.1-preview.2 → 6.0.1-preview.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { isNonEmptyArray, isNonEmptyReadonlyArray } from "../Array.js";
2
- import { assertNonEmptyArray } from "../Assert.js";
2
+ import { assert, assertNonEmptyArray } from "../Assert.js";
3
3
  import { createCallbacks } from "../Callbacks.js";
4
4
  import { ConsoleDep } from "../Console.js";
5
5
  import { SymmetricCryptoDecryptError } from "../Crypto.js";
@@ -44,9 +44,9 @@ import {
44
44
  SubscribedQueries,
45
45
  } from "./Query.js";
46
46
  import {
47
- assertValidEvoluSchema,
48
47
  CreateQuery,
49
48
  EvoluSchema,
49
+ evoluSchemaToDbSchema,
50
50
  insertable,
51
51
  Mutation,
52
52
  MutationKind,
@@ -54,7 +54,7 @@ import {
54
54
  MutationOptions,
55
55
  updateable,
56
56
  upsertable,
57
- validEvoluSchemaToDbSchema,
57
+ ValidateSchema,
58
58
  ValidMutationSize,
59
59
  ValidMutationSizeError,
60
60
  } from "./Schema.js";
@@ -431,9 +431,7 @@ let tabId: Id | null = null;
431
431
  export const createEvolu =
432
432
  (deps: EvoluDeps) =>
433
433
  <S extends EvoluSchema>(
434
- // TODO: Validate missing Id, unsupported types, used default types via TS types
435
- // with type errors messages as we had it in the old Evolu.
436
- schema: S,
434
+ schema: ValidateSchema<S> extends never ? S : ValidateSchema<S>,
437
435
  partialConfig: Partial<EvoluConfigWithInitialData<S>> = {},
438
436
  ): Evolu<S> => {
439
437
  const config = { ...defaultConfig, ...partialConfig };
@@ -441,11 +439,14 @@ export const createEvolu =
441
439
  let evolu = evoluInstances.get(config.name);
442
440
 
443
441
  if (evolu == null) {
444
- evolu = createEvoluInstance(deps)(schema, config as IntentionalNever);
442
+ evolu = createEvoluInstance(deps)(
443
+ schema as EvoluSchema,
444
+ config as IntentionalNever,
445
+ );
445
446
  evoluInstances.set(config.name, evolu);
446
447
  } else {
447
448
  // Hot reloading. Note that indexes are intentionally omitted.
448
- evolu.ensureSchema(schema);
449
+ evolu.ensureSchema(schema as EvoluSchema);
449
450
  }
450
451
 
451
452
  return evolu as IntentionalNever;
@@ -554,10 +555,7 @@ const createEvoluInstance =
554
555
  }
555
556
  });
556
557
 
557
- const dbSchema = validEvoluSchemaToDbSchema(
558
- assertValidEvoluSchema(schema),
559
- indexes,
560
- );
558
+ const dbSchema = evoluSchemaToDbSchema(schema, indexes);
561
559
 
562
560
  const mutationTypesCache = new Map<
563
561
  MutationKind,
@@ -592,21 +590,17 @@ const createEvoluInstance =
592
590
  if (initialData)
593
591
  initialData({
594
592
  insert: (table, props) => {
595
- const Type = getMutationType(table, "insert");
596
593
  const id = createId(deps);
594
+ const values = getMutationType(table, "insert").fromUnknown(props);
597
595
 
598
- const result = Type.fromUnknown(props);
599
-
600
- if (result.ok) {
601
- initialDataDbChanges.push({
602
- id,
603
- table,
604
- values: result.value,
605
- } as unknown as DbChange);
596
+ if (values.ok) {
597
+ const dbChange = { table, id, values: values.value };
598
+ assertValidDbChange(dbChange);
599
+ initialDataDbChanges.push(dbChange);
606
600
  return ok({ id });
607
601
  }
608
602
 
609
- return result;
603
+ return values;
610
604
  },
611
605
  });
612
606
 
@@ -654,14 +648,14 @@ const createEvoluInstance =
654
648
  } else {
655
649
  // Remove `id` from values.
656
650
  const { id: _id, ...values } = result.value;
657
- // EvoluSchema Types ensure valid types.
658
- const change = { table, id, values } as unknown as DbChange;
659
- mutateMicrotaskQueue.push([change, options?.onComplete]);
651
+ const dbChange = { table, id, values };
652
+ assertValidDbChange(dbChange);
653
+ mutateMicrotaskQueue.push([dbChange, options?.onComplete]);
660
654
  }
661
655
 
662
656
  if (mutateMicrotaskQueue.length === 1)
663
657
  queueMicrotask(() => {
664
- const changes = [];
658
+ const changes: Array<DbChange> = [];
665
659
  const onCompletes = [];
666
660
 
667
661
  for (const [change, onComplete] of mutateMicrotaskQueue) {
@@ -807,6 +801,7 @@ const createEvoluInstance =
807
801
  const onCompleteId = callbacks.register(() => {
808
802
  resolve();
809
803
  });
804
+
810
805
  dbWorker.postMessage({
811
806
  type: "reset",
812
807
  onCompleteId,
@@ -822,11 +817,8 @@ const createEvoluInstance =
822
817
 
823
818
  ensureSchema: (schema) => {
824
819
  mutationTypesCache.clear();
825
- const validSchema = assertValidEvoluSchema(schema);
826
- dbWorker.postMessage({
827
- type: "ensureDbSchema",
828
- dbSchema: validEvoluSchemaToDbSchema(validSchema),
829
- });
820
+ const dbSchema = evoluSchemaToDbSchema(schema);
821
+ dbWorker.postMessage({ type: "ensureDbSchema", dbSchema });
830
822
  },
831
823
 
832
824
  exportDatabase: () => {
@@ -945,3 +937,14 @@ const createLoadingPromises = (
945
937
 
946
938
  return loadingPromises;
947
939
  };
940
+
941
+ const assertValidDbChange: (dbChange: {
942
+ table: string;
943
+ id: Id;
944
+ values: unknown;
945
+ }) => asserts dbChange is DbChange = (dbChange) => {
946
+ assert(
947
+ DbChange.is(dbChange),
948
+ `Failed to create DbChange for table "${dbChange.table}". If you see this message, you either disabled EvoluSchema validation or Evolu has a bug - please report it.`,
949
+ );
950
+ };
@@ -144,7 +144,7 @@ import {
144
144
  } from "../Crypto.js";
145
145
  import { eqArrayNumber } from "../Eq.js";
146
146
  import { computeBalancedBuckets } from "../Number.js";
147
- import { objectToEntries, ReadonlyRecord } from "../Object.js";
147
+ import { objectToEntries } from "../Object.js";
148
148
  import { err, ok, Result } from "../Result.js";
149
149
  import { SqliteValue } from "../Sqlite.js";
150
150
  import {
@@ -157,7 +157,9 @@ import {
157
157
  NanoId,
158
158
  NonNegativeInt,
159
159
  Number,
160
+ object,
160
161
  PositiveInt,
162
+ record,
161
163
  } from "../Type.js";
162
164
  import { Brand, Predicate } from "../Types.js";
163
165
  import {
@@ -293,15 +295,23 @@ export interface CrdtMessage {
293
295
  readonly change: DbChange;
294
296
  }
295
297
 
298
+ /**
299
+ * Base64Url string with maximum length of 256 characters. Encoding strings as
300
+ * Base64UrlString saves up to 25% in size compared to regular strings.
301
+ */
302
+ export const Base64Url256 = maxLength(256)(Base64Url);
303
+ export type Base64Url256 = typeof Base64Url256.Type;
304
+
296
305
  /**
297
306
  * A DbChange is a change to a table row. Together with a unique
298
307
  * {@link Timestamp}, it forms a {@link CrdtMessage}.
299
308
  */
300
- export interface DbChange {
301
- readonly table: Base64Url256;
302
- readonly id: Id;
303
- readonly values: ReadonlyRecord<Base64Url256, SqliteValue>;
304
- }
309
+ export const DbChange = object({
310
+ table: Base64Url256,
311
+ id: Id,
312
+ values: record(Base64Url256, SqliteValue),
313
+ });
314
+ export type DbChange = typeof DbChange.Type;
305
315
 
306
316
  export const RangeType = {
307
317
  Fingerprint: 1,
@@ -1434,13 +1444,6 @@ export const ownerIdToBinaryOwnerId = (ownerId: OwnerId): BinaryOwnerId =>
1434
1444
  export const binaryOwnerIdToOwnerId = (binaryOwnerId: BinaryOwnerId): OwnerId =>
1435
1445
  decodeOwnerId(createBuffer(binaryOwnerId));
1436
1446
 
1437
- /**
1438
- * Base64Url string with maximum length of 256 characters. Encoding strings as
1439
- * Base64UrlString saves up to 25% in size compared to regular strings.
1440
- */
1441
- export const Base64Url256 = maxLength(256)(Base64Url);
1442
- export type Base64Url256 = typeof Base64Url256.Type;
1443
-
1444
1447
  /**
1445
1448
  * Union type for all variants of Base64Url strings with limited length. All
1446
1449
  * these types use Base64Url alphabet and are < 256 characters.
@@ -1,5 +1,6 @@
1
1
  import { Kysely, SelectQueryBuilder } from "kysely";
2
2
  import { pack } from "msgpackr";
3
+ import { assert } from "../Assert.js";
3
4
  import { mapObject, objectToEntries, ReadonlyRecord } from "../Object.js";
4
5
  import { err, ok, Result } from "../Result.js";
5
6
  import { SqliteBoolean, SqliteQueryOptions, SqliteValue } from "../Sqlite.js";
@@ -9,8 +10,7 @@ import {
9
10
  BrandType,
10
11
  createTypeErrorFormatter,
11
12
  DateIsoString,
12
- EvoluType,
13
- Id,
13
+ IdType,
14
14
  InferErrors,
15
15
  InferInput,
16
16
  InferType,
@@ -23,32 +23,20 @@ import {
23
23
  omit,
24
24
  optional,
25
25
  OptionalType,
26
- record,
27
26
  Type,
28
27
  TypeError,
29
- Unknown,
30
28
  } from "../Type.js";
31
29
  import { Simplify } from "../Types.js";
32
- import { DbSchema, DbTable } from "./Db.js";
30
+ import { DbSchema } from "./Db.js";
33
31
  import { createIndexes, DbIndexesBuilder } from "./Kysely.js";
34
32
  import { AppOwner, ShardOwner, SharedOwner } from "./Owner.js";
35
- import {
36
- Base64Url256,
37
- BinaryId,
38
- maxProtocolMessageRangesSize,
39
- } from "./Protocol.js";
33
+ import { BinaryId, maxProtocolMessageRangesSize } from "./Protocol.js";
40
34
  import { Query, Row } from "./Query.js";
41
35
  import { BinaryTimestamp } from "./Timestamp.js";
42
36
 
43
37
  /**
44
38
  * Defines the schema of an Evolu database.
45
39
  *
46
- * - Each top-level key represents a table name.
47
- * - The value for each table name is a record of column names mapped to their
48
- * respective data types, defined by {@link Type}.
49
- * - Each table must include a mandatory `id` column of type {@link Id}.
50
- * - No table may contain {@link DefaultColumns}.
51
- *
52
40
  * Table schema defines columns that are required for table rows. For not
53
41
  * required columns, use {@link nullOr}.
54
42
  *
@@ -82,11 +70,105 @@ import { BinaryTimestamp } from "./Timestamp.js";
82
70
  */
83
71
  export type EvoluSchema = ReadonlyRecord<
84
72
  string,
85
- ReadonlyRecord<string, Type<any, any, any, any, any>> & {
86
- readonly id: Type<any, any, any, any, any>;
87
- }
73
+ // TypeScript errors are cryptic so we use ValidateSchema.
74
+ ReadonlyRecord<string, Type<any, any, any, any, any>>
88
75
  >;
89
76
 
77
+ /**
78
+ * Validates an {@link EvoluSchema} at compile time, returning the first error
79
+ * found as a readable string literal type. This approach provides much clearer
80
+ * and more actionable TypeScript errors than the default, which are often hard
81
+ * to read.
82
+ *
83
+ * Validates the following schema requirements:
84
+ *
85
+ * 1. All tables must have an 'id' column
86
+ * 2. The 'id' column must be a branded ID type (created with id() function)
87
+ * 3. Tables cannot use default column names (createdAt, updatedAt, isDeleted)
88
+ * 4. All column types must be compatible with SQLite (extend SqliteValue)
89
+ */
90
+ export type ValidateSchema<S extends EvoluSchema> =
91
+ ValidateSchemaHasId<S> extends never
92
+ ? ValidateIdColumnType<S> extends never
93
+ ? ValidateNoDefaultColumns<S> extends never
94
+ ? ValidateColumnTypes<S> extends never
95
+ ? S
96
+ : ValidateColumnTypes<S>
97
+ : ValidateNoDefaultColumns<S>
98
+ : ValidateIdColumnType<S>
99
+ : ValidateSchemaHasId<S>;
100
+
101
+ export type ValidateSchemaHasId<S extends EvoluSchema> =
102
+ keyof S extends infer TableName
103
+ ? TableName extends keyof S
104
+ ? "id" extends keyof S[TableName]
105
+ ? never
106
+ : SchemaValidationError<`Table "${TableName & string}" is missing required id column.`>
107
+ : never
108
+ : never;
109
+
110
+ export type ValidateIdColumnType<S extends EvoluSchema> =
111
+ keyof S extends infer TableName
112
+ ? TableName extends keyof S
113
+ ? "id" extends keyof S[TableName]
114
+ ? S[TableName]["id"] extends IdType<any>
115
+ ? never
116
+ : SchemaValidationError<`Table "${TableName & string}" id column must be a branded ID type (created with id("${TableName & string}")).`>
117
+ : never
118
+ : never
119
+ : never;
120
+
121
+ export type ValidateNoDefaultColumns<S extends EvoluSchema> =
122
+ keyof S extends infer TableName
123
+ ? TableName extends keyof S
124
+ ? keyof S[TableName] extends infer ColumnName
125
+ ? ColumnName extends keyof S[TableName]
126
+ ? ColumnName extends "createdAt" | "updatedAt" | "isDeleted"
127
+ ? SchemaValidationError<`Table "${TableName & string}" uses default column name "${ColumnName & string}". Default columns (createdAt, updatedAt, isDeleted) are added automatically.`>
128
+ : never
129
+ : never
130
+ : never
131
+ : never
132
+ : never;
133
+
134
+ export type ValidateColumnTypes<S extends EvoluSchema> =
135
+ keyof S extends infer TableName
136
+ ? TableName extends keyof S
137
+ ? keyof S[TableName] extends infer ColumnName
138
+ ? ColumnName extends keyof S[TableName]
139
+ ? InferType<S[TableName][ColumnName]> extends SqliteValue
140
+ ? never
141
+ : SchemaValidationError<`Table "${TableName & string}" column "${ColumnName & string}" type is not compatible with SQLite. Column types must extend SqliteValue (string, number, Uint8Array, or null).`>
142
+ : never
143
+ : never
144
+ : never
145
+ : never;
146
+
147
+ /** Schema validation error that shows clear, readable messages */
148
+ export type SchemaValidationError<Message extends string> =
149
+ `❌ Schema Error: ${Message}`;
150
+
151
+ export const evoluSchemaToDbSchema = (
152
+ schema: EvoluSchema,
153
+ indexes?: DbIndexesBuilder,
154
+ ): DbSchema => {
155
+ const tables = objectToEntries(schema).map(([tableName, table]) => ({
156
+ name: tableName,
157
+ columns: objectToEntries(table)
158
+ .filter(([k]) => k !== "id")
159
+ .map(([k]) => k),
160
+ }));
161
+
162
+ const dbSchema = { tables, indexes: createIndexes(indexes) };
163
+
164
+ assert(
165
+ DbSchema.is(dbSchema),
166
+ "Invalid EvoluSchema: Table and column names must use only characters A-Za-z0-9_- and be at most 256 characters long.",
167
+ );
168
+
169
+ return dbSchema;
170
+ };
171
+
90
172
  export type CreateQuery<S extends EvoluSchema> = <R extends Row>(
91
173
  queryCallback: (
92
174
  db: Pick<
@@ -104,7 +186,7 @@ export type CreateQuery<S extends EvoluSchema> = <R extends Row>(
104
186
  readonly evolu_history: {
105
187
  readonly timestamp: BinaryTimestamp;
106
188
  readonly table: keyof S;
107
- readonly row: BinaryId;
189
+ readonly id: BinaryId;
108
190
  readonly column: string;
109
191
  readonly value: SqliteValue;
110
192
  };
@@ -123,116 +205,6 @@ export const DefaultColumns = object({
123
205
  });
124
206
  export type DefaultColumns = typeof DefaultColumns.Type;
125
207
 
126
- const isDefaultColumnName = (value: string): boolean =>
127
- value === "createdAt" || value === "updatedAt" || value === "isDeleted";
128
-
129
- /**
130
- * Valid {@link EvoluSchema}.
131
- *
132
- * - Table and column names must be Base64Url strings.
133
- * - Each table must include an `id` column of type {@link Id}.
134
- * - Default column names (`createdAt`, `updatedAt`, `isDeleted`) are not allowed.
135
- */
136
- export const ValidEvoluSchema = brand(
137
- "ValidEvoluSchema",
138
- record(
139
- Base64Url256,
140
- object({ id: EvoluType }, record(Base64Url256, Unknown)),
141
- ),
142
- (value) => {
143
- for (const tableName in value) {
144
- for (const columnName in value[tableName as never]) {
145
- if (isDefaultColumnName(columnName)) {
146
- return err<ValidEvoluSchemaError>({
147
- type: "ValidEvoluSchema",
148
- value,
149
- reason: {
150
- kind: "DefaultColumnError",
151
- tableName,
152
- columnName,
153
- },
154
- });
155
- }
156
- }
157
- }
158
-
159
- return ok(value);
160
- },
161
- );
162
-
163
- export type ValidEvoluSchema = typeof ValidEvoluSchema.Type;
164
-
165
- export interface ValidEvoluSchemaError extends TypeError<"ValidEvoluSchema"> {
166
- readonly reason: {
167
- kind: "DefaultColumnError";
168
- tableName: string;
169
- columnName: string;
170
- };
171
- }
172
-
173
- /**
174
- * Asserts that the given value is {@link ValidEvoluSchema}.
175
- *
176
- * Throws an error if the value is not a valid Evolu schema.
177
- */
178
- export const assertValidEvoluSchema = (value: unknown): ValidEvoluSchema => {
179
- const validEvoluSchema = ValidEvoluSchema.fromUnknown(value);
180
- if (!validEvoluSchema.ok) {
181
- const message = formatValidEvoluSchemaError(validEvoluSchema.error);
182
- throw new Error(`Invalid Evolu schema: ${message}`);
183
- }
184
- return validEvoluSchema.value;
185
- };
186
-
187
- const formatValidEvoluSchemaError = (
188
- error: typeof ValidEvoluSchema.Error | typeof ValidEvoluSchema.ParentError,
189
- ): string => {
190
- if (error.type === "Record") {
191
- if (error.reason.kind === "Key") {
192
- return `The table "${error.reason.key}" has invalid name. A table name must be Base64Url256 string (A-Z, a-z, 0-9, -, _).`;
193
- }
194
-
195
- if (
196
- error.reason.kind === "Value" &&
197
- error.reason.error.reason.kind === "Props" &&
198
- error.reason.error.reason.errors.id?.type === "EvoluType"
199
- ) {
200
- return `The table "${error.reason.key}" has invalid ID column. Check examples.`;
201
- }
202
-
203
- if (
204
- error.reason.kind === "Value" &&
205
- error.reason.error.reason.kind === "IndexKey"
206
- ) {
207
- return `The table "${error.reason.key}" has invalid column name "${error.reason.error.reason.key}". A column name must be Base64Url256 string (A-Z, a-z, 0-9, -, _).`;
208
- }
209
- }
210
-
211
- if (error.type === "ValidEvoluSchema") {
212
- return `The table "${error.reason.tableName}" uses reserved column name "${error.reason.columnName}". Reserved column names are: createdAt, updatedAt, isDeleted.`;
213
- }
214
-
215
- return JSON.stringify(error, null, 2);
216
- };
217
-
218
- export const validEvoluSchemaToDbSchema = (
219
- validEvoluSchema: ValidEvoluSchema,
220
- indexes?: DbIndexesBuilder,
221
- ): DbSchema => {
222
- const tables = objectToEntries(validEvoluSchema).map(
223
- ([tableName, table]): DbTable => ({
224
- name: tableName,
225
- columns: objectToEntries(table)
226
- .filter(([k]) => k !== "id")
227
- .map(([k]) => k as Base64Url256),
228
- }),
229
- );
230
- return {
231
- tables,
232
- indexes: createIndexes(indexes),
233
- };
234
- };
235
-
236
208
  export type MutationKind = "insert" | "update" | "upsert";
237
209
 
238
210
  export type Mutation<S extends EvoluSchema, Kind extends MutationKind> = <