@gaganref/confect-server 10.3.1-fork.25 → 10.3.1-fork.26

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.
@@ -37,8 +37,42 @@ export interface DatabaseWriterService<DatabaseSchema_ extends DatabaseSchema.An
37
37
  * interfaces.
38
38
  */
39
39
  export type DatabaseWriterTag<DatabaseSchema_ extends DatabaseSchema.AnyWithProps, Docs = {}> = Context.Service<DatabaseWriterService<DatabaseSchema_>, DatabaseWriterService<DatabaseSchema_, Docs>>;
40
- export declare const make: <DatabaseSchema_ extends DatabaseSchema.AnyWithProps>(databaseSchema: DatabaseSchema_, convexDatabaseWriter: GenericDatabaseWriter<DataModel.ToConvex<DataModel.FromSchema<DatabaseSchema_>>>) => DatabaseWriterService<DatabaseSchema_>;
40
+ /**
41
+ * Decoded documents surrounding one successful write.
42
+ */
43
+ export type Change<S extends DatabaseSchema.AnyWithProps> = {
44
+ [Name in DataModel.TableNames<DataModel.FromSchema<S>>]: {
45
+ readonly tableName: Name;
46
+ } & ({
47
+ readonly operation: "insert";
48
+ readonly oldDoc: null;
49
+ readonly newDoc: DocumentByName_<DataModel.FromSchema<S>, Name>;
50
+ } | {
51
+ readonly operation: "update";
52
+ readonly oldDoc: DocumentByName_<DataModel.FromSchema<S>, Name>;
53
+ readonly newDoc: DocumentByName_<DataModel.FromSchema<S>, Name>;
54
+ } | {
55
+ readonly operation: "delete";
56
+ readonly oldDoc: DocumentByName_<DataModel.FromSchema<S>, Name>;
57
+ readonly newDoc: null;
58
+ });
59
+ }[DataModel.TableNames<DataModel.FromSchema<S>>];
60
+ /**
61
+ * Runs after the write, in its transaction. A defect aborts the mutation.
62
+ *
63
+ * Only writes through this writer are observed. Raw `ctx.db`, `MutationCtx`
64
+ * writes and a second `DatabaseWriter.make` bypass the hook, so a host that
65
+ * relies on it keeps raw writers out of its functions. Component writers and
66
+ * nested `runMutation` calls each need their own hook installation.
67
+ *
68
+ * Concurrent writes to one document (for example under `Effect.all`) can
69
+ * interleave the read-write-read steps. Await them sequentially when the hook
70
+ * needs exact per-write snapshots. The writer takes no lock, because a hook
71
+ * that writes through the same writer would deadlock under one.
72
+ */
73
+ export type Hook<S extends DatabaseSchema.AnyWithProps> = (change: Change<S>) => Effect.Effect<void>;
74
+ export declare const make: <DatabaseSchema_ extends DatabaseSchema.AnyWithProps>(databaseSchema: DatabaseSchema_, convexDatabaseWriter: GenericDatabaseWriter<DataModel.ToConvex<DataModel.FromSchema<DatabaseSchema_>>>, hook?: Hook<DatabaseSchema_>) => DatabaseWriterService<DatabaseSchema_>;
41
75
  export declare const DatabaseWriter: <DatabaseSchema_ extends DatabaseSchema.AnyWithProps, Docs = {}>() => DatabaseWriterTag<DatabaseSchema_, Docs>;
42
76
  export type DatabaseWriter<DatabaseSchema_ extends DatabaseSchema.AnyWithProps> = DatabaseWriterService<DatabaseSchema_>;
43
- export declare const layer: <DatabaseSchema_ extends DatabaseSchema.AnyWithProps>(databaseSchema: DatabaseSchema_, convexDatabaseWriter: GenericDatabaseWriter<DataModel.ToConvex<DataModel.FromSchema<DatabaseSchema_>>>) => Layer.Layer<DatabaseWriterService<DatabaseSchema_, {}>, never, never>;
77
+ export declare const layer: <DatabaseSchema_ extends DatabaseSchema.AnyWithProps>(databaseSchema: DatabaseSchema_, convexDatabaseWriter: GenericDatabaseWriter<DataModel.ToConvex<DataModel.FromSchema<DatabaseSchema_>>>, hook?: Hook<DatabaseSchema_>) => Layer.Layer<DatabaseWriterService<DatabaseSchema_, {}>, never, never>;
44
78
  //# sourceMappingURL=DatabaseWriter.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"DatabaseWriter.d.ts","sourceRoot":"","sources":["../src/DatabaseWriter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAIV,qBAAqB,EAEtB,MAAM,eAAe,CAAC;AAGvB,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAC;AAC1C,OAAO,KAAK,MAAM,MAAM,eAAe,CA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17
17
  make: () => make
18
18
  });
19
- const make = (databaseSchema, convexDatabaseWriter) => {
19
+ const make = (databaseSchema, convexDatabaseWriter, hook) => {
20
20
  const table = (tableName) => {
21
21
  const tableDef = tables(databaseSchema)[tableName];
22
22
  const insert = Effect.fn("DatabaseWriter.insert")(function* (document) {
@@ -50,17 +50,44 @@ const make = (databaseSchema, convexDatabaseWriter) => {
50
50
  yield* Effect.promise(() => convexDatabaseWriter.replace(id, updatedEncodedDoc));
51
51
  });
52
52
  const delete_ = (id) => Effect.promise(() => convexDatabaseWriter.delete(id));
53
- return {
53
+ const accessor = {
54
54
  insert,
55
55
  patch,
56
56
  replace,
57
57
  delete: delete_
58
58
  };
59
+ if (hook === void 0) return accessor;
60
+ const read = (id) => getById(convexDatabaseWriter, tableDef)(id);
61
+ const notify = (operation, oldDoc, newDoc) => hook({
62
+ tableName,
63
+ operation,
64
+ oldDoc,
65
+ newDoc
66
+ });
67
+ const update = (before, write) => (id, ...args) => Effect.gen(function* () {
68
+ const oldDoc = yield* before(id);
69
+ yield* write(id, ...args);
70
+ yield* notify("update", oldDoc, yield* read(id).pipe(Effect.orDie));
71
+ });
72
+ return {
73
+ insert: (document) => Effect.gen(function* () {
74
+ const id = yield* insert(document);
75
+ yield* notify("insert", null, yield* read(id).pipe(Effect.orDie));
76
+ return id;
77
+ }),
78
+ patch: update(read, patch),
79
+ replace: update((id) => read(id).pipe(Effect.orDie), replace),
80
+ delete: (id) => Effect.gen(function* () {
81
+ const oldDoc = yield* read(id).pipe(Effect.orDie);
82
+ yield* delete_(id);
83
+ yield* notify("delete", oldDoc, null);
84
+ })
85
+ };
59
86
  };
60
87
  return { table };
61
88
  };
62
89
  const DatabaseWriter = () => Context.Service("@confect/server/DatabaseWriter");
63
- const layer = (databaseSchema, convexDatabaseWriter) => Layer.succeed(DatabaseWriter(), make(databaseSchema, convexDatabaseWriter));
90
+ const layer = (databaseSchema, convexDatabaseWriter, hook) => Layer.succeed(DatabaseWriter(), make(databaseSchema, convexDatabaseWriter, hook));
64
91
  //#endregion
65
92
  export { DatabaseWriter, DatabaseWriter_exports, layer, make };
66
93
 
@@ -1 +1 @@
1
- {"version":3,"file":"DatabaseWriter.js","names":["DatabaseSchema.tables","Document.encode","QueryInitializer.getById","DocumentPatch.encoder","QueryInitializer.GetByIdFailure","Document.decode","Document.DocumentEncodeError"],"sources":["../src/DatabaseWriter.ts"],"sourcesContent":["import type {\n BetterOmit,\n DocumentByName,\n Expand,\n GenericDatabaseWriter,\n WithoutSystemFields,\n} from \"convex/server\";\nimport type { GenericId } from \"convex/values\";\nimport { pipe } from \"effect/Function\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\nimport * as Result from \"effect/Result\";\nimport * as DatabaseSchema from \"./DatabaseSchema.js\";\nimport type * as DataModel from \"./DataModel.js\";\nimport type { DocumentByName as DocumentByName_ } from \"./DataModel.js\";\nimport * as Document from \"./Document.js\";\nimport * as DocumentPatch from \"./internal/DocumentPatch.js\";\nimport * as QueryInitializer from \"./QueryInitializer.js\";\nimport type * as Table from \"./Table.js\";\n\n/**\n * The argument accepted by `patch`: like `Partial<Doc>` without system fields,\n * but the fields that are already optional also accept `undefined`, since\n * setting a field to `undefined` unsets it.\n */\nexport type PatchValue<Doc> = {\n [\n K in keyof Doc as K extends \"_id\" | \"_creationTime\" ? never : K\n ]?: undefined extends Doc[K] ? Doc[K] | undefined : Doc[K];\n};\n\nexport interface DatabaseWriterTableAccessor<\n DataModel_ extends DataModel.AnyWithProps,\n TableName extends DataModel.TableNames<DataModel_>,\n Doc = DocumentByName_<DataModel_, TableName>,\n> {\n readonly insert: (\n document: Document.WithoutSystemFields<Doc>,\n ) => Effect.Effect<\n DataModel.Id<DataModel_, TableName>,\n Document.DocumentEncodeError\n >;\n readonly patch: (\n id: DataModel.Id<DataModel_, TableName>,\n patchedValues: PatchValue<Doc>,\n ) => Effect.Effect<\n void,\n | QueryInitializer.GetByIdFailure\n | Document.DocumentDecodeError\n | Document.DocumentEncodeError\n >;\n readonly replace: (\n id: DataModel.Id<DataModel_, TableName>,\n value: Document.WithoutSystemFields<Doc>,\n ) => Effect.Effect<void, Document.DocumentEncodeError>;\n readonly delete: (\n id: DataModel.Id<DataModel_, TableName>,\n ) => Effect.Effect<void>;\n}\n\n/**\n * The service shape backing the `DatabaseWriter` tag. Named (rather than an\n * inferred anonymous object) so declaration emit prints\n * `DatabaseWriterService<…>` by reference instead of expanding the data model.\n * `Docs` is the optional named document registry (see\n * `DatabaseReaderService`).\n */\nexport interface DatabaseWriterService<\n DatabaseSchema_ extends DatabaseSchema.AnyWithProps,\n Docs = {},\n> {\n readonly table: <\n const TableName extends DataModel.TableNames<\n DataModel.FromSchema<DatabaseSchema_>\n >,\n >(\n tableName: TableName,\n ) => DatabaseWriterTableAccessor<\n DataModel.FromSchema<DatabaseSchema_>,\n TableName,\n TableName extends keyof Docs\n ? Docs[TableName]\n : DocumentByName_<DataModel.FromSchema<DatabaseSchema_>, TableName>\n >;\n}\n\n/**\n * The tag's _Identifier_ is `Docs`-independent (see `DatabaseReaderTag`); only\n * the _Service_ carries `Docs` so writer inputs print the named doc\n * interfaces.\n */\nexport type DatabaseWriterTag<\n DatabaseSchema_ extends DatabaseSchema.AnyWithProps,\n Docs = {},\n> = Context.Service<\n DatabaseWriterService<DatabaseSchema_>,\n DatabaseWriterService<DatabaseSchema_, Docs>\n>;\n\nexport const make = <DatabaseSchema_ extends DatabaseSchema.AnyWithProps>(\n databaseSchema: DatabaseSchema_,\n convexDatabaseWriter: GenericDatabaseWriter<\n DataModel.ToConvex<DataModel.FromSchema<DatabaseSchema_>>\n >,\n): DatabaseWriterService<DatabaseSchema_> => {\n type DataModel_ = DataModel.FromSchema<DatabaseSchema_>;\n\n const table = <const TableName extends DataModel.TableNames<DataModel_>>(\n tableName: TableName,\n ) => {\n const tableDef = DatabaseSchema.tables(databaseSchema)[tableName];\n\n const insert = Effect.fn(\"DatabaseWriter.insert\")(function* (\n document: Document.WithoutSystemFields<\n DocumentByName_<DataModel_, TableName>\n >,\n ) {\n const encodedDocument = yield* Document.encode(document, tableDef);\n\n const id = yield* Effect.promise(() =>\n convexDatabaseWriter.insert(\n tableName,\n encodedDocument as WithoutSystemFields<\n DocumentByName<DataModel.ToConvex<DataModel_>, TableName>\n >,\n ),\n );\n\n // The database supplies the ID in this table's execution scope. Its\n // scope brand is erased at the Convex syscall boundary.\n return id as unknown as DataModel.Id<DataModel_, TableName>;\n });\n\n // A codec whose encoding spans fields cannot encode a patch on its own, so\n // the patch is merged into the decoded document and the result replaces it.\n const replacePatched = (\n id: DataModel.Id<DataModel_, TableName>,\n patchedValues: PatchValue<\n Document.WithoutSystemFields<DocumentByName_<DataModel_, TableName>>\n >,\n ) =>\n Effect.gen(function* () {\n const originalDecodedDoc = yield* QueryInitializer.getById<\n Table.AnyWithProps,\n TableName\n >(\n convexDatabaseWriter as any,\n tableDef,\n )(id as unknown as GenericId<TableName>);\n\n const updatedEncodedDoc = yield* pipe(\n patchedValues,\n Record.reduce(originalDecodedDoc, (acc, value, key) =>\n value === undefined\n ? Record.remove(acc, key)\n : Record.set(acc, key, value),\n ),\n Document.encode(tableDef),\n );\n\n yield* Effect.promise(() =>\n convexDatabaseWriter.replace(\n id as unknown as GenericId<TableName>,\n updatedEncodedDoc as Expand<\n BetterOmit<\n DocumentByName<DataModel.ToConvex<DataModel_>, TableName>,\n \"_creationTime\" | \"_id\"\n >\n >,\n ),\n );\n });\n\n const patch = Effect.fn(\"DatabaseWriter.patch\")(function* (\n id: DataModel.Id<DataModel_, TableName>,\n patchedValues: PatchValue<\n Document.WithoutSystemFields<DocumentByName_<DataModel_, TableName>>\n >,\n ) {\n const encodePatch = DocumentPatch.encoder(tableDef);\n if (encodePatch === undefined) {\n return yield* replacePatched(id, patchedValues);\n }\n\n const storedDoc = yield* pipe(\n Effect.promise(() =>\n convexDatabaseWriter.get(id as unknown as GenericId<TableName>),\n ),\n Effect.andThen((value) =>\n Effect.fromResult(\n Result.fromNullishOr(\n value,\n () =>\n new QueryInitializer.GetByIdFailure({\n tableName,\n id,\n }),\n ),\n ),\n ),\n );\n // The patch must encode and the patched document must decode. When\n // either fails, the stored document decides whose fault that is.\n const encodedPatch = yield* pipe(\n encodePatch(patchedValues),\n Effect.mapError(({ message }) => message),\n Effect.tap((delta) =>\n pipe(\n { ...storedDoc, ...delta },\n Record.filter(Predicate.isNotUndefined),\n Document.decode(tableDef),\n Effect.mapError(({ parseError }) => parseError),\n ),\n ),\n Effect.catch((parseError) =>\n pipe(\n Document.decode(storedDoc, tableDef),\n Effect.andThen(\n Effect.fail(\n new Document.DocumentEncodeError({\n tableName,\n id,\n parseError,\n }),\n ),\n ),\n ),\n ),\n );\n\n yield* Effect.promise(() =>\n convexDatabaseWriter.patch(\n id as unknown as GenericId<TableName>,\n encodedPatch as Partial<\n DocumentByName<DataModel.ToConvex<DataModel_>, TableName>\n >,\n ),\n );\n });\n\n const replace = Effect.fn(\"DatabaseWriter.replace\")(function* (\n id: DataModel.Id<DataModel_, TableName>,\n value: Document.WithoutSystemFields<\n DocumentByName_<DataModel_, TableName>\n >,\n ) {\n const updatedEncodedDoc = yield* Document.encode(value, tableDef);\n\n yield* Effect.promise(() =>\n convexDatabaseWriter.replace(\n id as unknown as GenericId<TableName>,\n updatedEncodedDoc as Expand<\n BetterOmit<\n DocumentByName<DataModel.ToConvex<DataModel_>, TableName>,\n \"_creationTime\" | \"_id\"\n >\n >,\n ),\n );\n });\n\n const delete_ = (id: DataModel.Id<DataModel_, TableName>) =>\n Effect.promise(() =>\n convexDatabaseWriter.delete(id as unknown as GenericId<TableName>),\n );\n\n return {\n insert,\n patch,\n replace,\n delete: delete_,\n };\n };\n\n return {\n table,\n } as DatabaseWriterService<DatabaseSchema_>;\n};\n\nexport const DatabaseWriter = <\n DatabaseSchema_ extends DatabaseSchema.AnyWithProps,\n Docs = {},\n>(): DatabaseWriterTag<DatabaseSchema_, Docs> =>\n Context.Service<\n DatabaseWriterService<DatabaseSchema_>,\n DatabaseWriterService<DatabaseSchema_, Docs>\n >(\"@confect/server/DatabaseWriter\");\n\nexport type DatabaseWriter<\n DatabaseSchema_ extends DatabaseSchema.AnyWithProps,\n> = DatabaseWriterService<DatabaseSchema_>;\n\nexport const layer = <DatabaseSchema_ extends DatabaseSchema.AnyWithProps>(\n databaseSchema: DatabaseSchema_,\n convexDatabaseWriter: GenericDatabaseWriter<\n DataModel.ToConvex<DataModel.FromSchema<DatabaseSchema_>>\n >,\n) =>\n Layer.succeed(\n DatabaseWriter<DatabaseSchema_>(),\n make(databaseSchema, convexDatabaseWriter),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsGA,MAAa,QACX,gBACA,yBAG2C;CAG3C,MAAM,SACJ,cACG;EACH,MAAM,WAAWA,OAAsB,cAAc,CAAC,CAAC;EAEvD,MAAM,SAAS,OAAO,GAAG,uBAAuB,CAAC,CAAC,WAChD,UAGA;GACA,MAAM,kBAAkB,OAAOC,OAAgB,UAAU,QAAQ;GAajE,OAAO,OAXW,OAAO,cACvB,qBAAqB,OACnB,WACA,eAGF,CACF;EAKF,CAAC;EAID,MAAM,kBACJ,IACA,kBAIA,OAAO,IAAI,aAAa;GACtB,MAAM,qBAAqB,OAAOC,QAIhC,sBACA,QACF,CAAC,CAAC,EAAqC;GAEvC,MAAM,oBAAoB,OAAO,KAC/B,eACA,OAAO,OAAO,qBAAqB,KAAK,OAAO,QAC7C,UAAU,KAAA,IACN,OAAO,OAAO,KAAK,GAAG,IACtB,OAAO,IAAI,KAAK,KAAK,KAAK,CAChC,GACAD,OAAgB,QAAQ,CAC1B;GAEA,OAAO,OAAO,cACZ,qBAAqB,QACnB,IACA,iBAMF,CACF;EACF,CAAC;EAEH,MAAM,QAAQ,OAAO,GAAG,sBAAsB,CAAC,CAAC,WAC9C,IACA,eAGA;GACA,MAAM,cAAcE,QAAsB,QAAQ;GAClD,IAAI,gBAAgB,KAAA,GAClB,OAAO,OAAO,eAAe,IAAI,aAAa;GAGhD,MAAM,YAAY,OAAO,KACvB,OAAO,cACL,qBAAqB,IAAI,EAAqC,CAChE,GACA,OAAO,SAAS,UACd,OAAO,WACL,OAAO,cACL,aAEE,IAAIC,eAAgC;IAClC;IACA;GACF,CAAC,CACL,CACF,CACF,CACF;GAGA,MAAM,eAAe,OAAO,KAC1B,YAAY,aAAa,GACzB,OAAO,UAAU,EAAE,cAAc,OAAO,GACxC,OAAO,KAAK,UACV,KACE;IAAE,GAAG;IAAW,GAAG;GAAM,GACzB,OAAO,OAAO,UAAU,cAAc,GACtCC,OAAgB,QAAQ,GACxB,OAAO,UAAU,EAAE,iBAAiB,UAAU,CAChD,CACF,GACA,OAAO,OAAO,eACZ,KACEA,OAAgB,WAAW,QAAQ,GACnC,OAAO,QACL,OAAO,KACL,IAAIC,oBAA6B;IAC/B;IACA;IACA;GACF,CAAC,CACH,CACF,CACF,CACF,CACF;GAEA,OAAO,OAAO,cACZ,qBAAqB,MACnB,IACA,YAGF,CACF;EACF,CAAC;EAED,MAAM,UAAU,OAAO,GAAG,wBAAwB,CAAC,CAAC,WAClD,IACA,OAGA;GACA,MAAM,oBAAoB,OAAOL,OAAgB,OAAO,QAAQ;GAEhE,OAAO,OAAO,cACZ,qBAAqB,QACnB,IACA,iBAMF,CACF;EACF,CAAC;EAED,MAAM,WAAW,OACf,OAAO,cACL,qBAAqB,OAAO,EAAqC,CACnE;EAEF,OAAO;GACL;GACA;GACA;GACA,QAAQ;EACV;CACF;CAEA,OAAO,EACL,MACF;AACF;AAEA,MAAa,uBAIX,QAAQ,QAGN,gCAAgC;AAMpC,MAAa,SACX,gBACA,yBAIA,MAAM,QACJ,eAAgC,GAChC,KAAK,gBAAgB,oBAAoB,CAC3C"}
1
+ {"version":3,"file":"DatabaseWriter.js","names":["DatabaseSchema.tables","Document.encode","QueryInitializer.getById","DocumentPatch.encoder","QueryInitializer.GetByIdFailure","Document.decode","Document.DocumentEncodeError"],"sources":["../src/DatabaseWriter.ts"],"sourcesContent":["import type {\n BetterOmit,\n DocumentByName,\n Expand,\n GenericDatabaseWriter,\n WithoutSystemFields,\n} from \"convex/server\";\nimport type { GenericId } from \"convex/values\";\nimport { pipe } from \"effect/Function\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Record from \"effect/Record\";\nimport * as Result from \"effect/Result\";\nimport * as DatabaseSchema from \"./DatabaseSchema.js\";\nimport type * as DataModel from \"./DataModel.js\";\nimport type { DocumentByName as DocumentByName_ } from \"./DataModel.js\";\nimport * as Document from \"./Document.js\";\nimport * as DocumentPatch from \"./internal/DocumentPatch.js\";\nimport * as QueryInitializer from \"./QueryInitializer.js\";\nimport type * as Table from \"./Table.js\";\n\n/**\n * The argument accepted by `patch`: like `Partial<Doc>` without system fields,\n * but the fields that are already optional also accept `undefined`, since\n * setting a field to `undefined` unsets it.\n */\nexport type PatchValue<Doc> = {\n [\n K in keyof Doc as K extends \"_id\" | \"_creationTime\" ? never : K\n ]?: undefined extends Doc[K] ? Doc[K] | undefined : Doc[K];\n};\n\nexport interface DatabaseWriterTableAccessor<\n DataModel_ extends DataModel.AnyWithProps,\n TableName extends DataModel.TableNames<DataModel_>,\n Doc = DocumentByName_<DataModel_, TableName>,\n> {\n readonly insert: (\n document: Document.WithoutSystemFields<Doc>,\n ) => Effect.Effect<\n DataModel.Id<DataModel_, TableName>,\n Document.DocumentEncodeError\n >;\n readonly patch: (\n id: DataModel.Id<DataModel_, TableName>,\n patchedValues: PatchValue<Doc>,\n ) => Effect.Effect<\n void,\n | QueryInitializer.GetByIdFailure\n | Document.DocumentDecodeError\n | Document.DocumentEncodeError\n >;\n readonly replace: (\n id: DataModel.Id<DataModel_, TableName>,\n value: Document.WithoutSystemFields<Doc>,\n ) => Effect.Effect<void, Document.DocumentEncodeError>;\n readonly delete: (\n id: DataModel.Id<DataModel_, TableName>,\n ) => Effect.Effect<void>;\n}\n\n/**\n * The service shape backing the `DatabaseWriter` tag. Named (rather than an\n * inferred anonymous object) so declaration emit prints\n * `DatabaseWriterService<…>` by reference instead of expanding the data model.\n * `Docs` is the optional named document registry (see\n * `DatabaseReaderService`).\n */\nexport interface DatabaseWriterService<\n DatabaseSchema_ extends DatabaseSchema.AnyWithProps,\n Docs = {},\n> {\n readonly table: <\n const TableName extends DataModel.TableNames<\n DataModel.FromSchema<DatabaseSchema_>\n >,\n >(\n tableName: TableName,\n ) => DatabaseWriterTableAccessor<\n DataModel.FromSchema<DatabaseSchema_>,\n TableName,\n TableName extends keyof Docs\n ? Docs[TableName]\n : DocumentByName_<DataModel.FromSchema<DatabaseSchema_>, TableName>\n >;\n}\n\n/**\n * The tag's _Identifier_ is `Docs`-independent (see `DatabaseReaderTag`); only\n * the _Service_ carries `Docs` so writer inputs print the named doc\n * interfaces.\n */\nexport type DatabaseWriterTag<\n DatabaseSchema_ extends DatabaseSchema.AnyWithProps,\n Docs = {},\n> = Context.Service<\n DatabaseWriterService<DatabaseSchema_>,\n DatabaseWriterService<DatabaseSchema_, Docs>\n>;\n\n/**\n * Decoded documents surrounding one successful write.\n */\nexport type Change<S extends DatabaseSchema.AnyWithProps> = {\n [Name in DataModel.TableNames<DataModel.FromSchema<S>>]: {\n readonly tableName: Name;\n } & (\n | {\n readonly operation: \"insert\";\n readonly oldDoc: null;\n readonly newDoc: DocumentByName_<DataModel.FromSchema<S>, Name>;\n }\n | {\n readonly operation: \"update\";\n readonly oldDoc: DocumentByName_<DataModel.FromSchema<S>, Name>;\n readonly newDoc: DocumentByName_<DataModel.FromSchema<S>, Name>;\n }\n | {\n readonly operation: \"delete\";\n readonly oldDoc: DocumentByName_<DataModel.FromSchema<S>, Name>;\n readonly newDoc: null;\n }\n );\n}[DataModel.TableNames<DataModel.FromSchema<S>>];\n\n/**\n * Runs after the write, in its transaction. A defect aborts the mutation.\n *\n * Only writes through this writer are observed. Raw `ctx.db`, `MutationCtx`\n * writes and a second `DatabaseWriter.make` bypass the hook, so a host that\n * relies on it keeps raw writers out of its functions. Component writers and\n * nested `runMutation` calls each need their own hook installation.\n *\n * Concurrent writes to one document (for example under `Effect.all`) can\n * interleave the read-write-read steps. Await them sequentially when the hook\n * needs exact per-write snapshots. The writer takes no lock, because a hook\n * that writes through the same writer would deadlock under one.\n */\nexport type Hook<S extends DatabaseSchema.AnyWithProps> = (\n change: Change<S>,\n) => Effect.Effect<void>;\n\nexport const make = <DatabaseSchema_ extends DatabaseSchema.AnyWithProps>(\n databaseSchema: DatabaseSchema_,\n convexDatabaseWriter: GenericDatabaseWriter<\n DataModel.ToConvex<DataModel.FromSchema<DatabaseSchema_>>\n >,\n hook?: Hook<DatabaseSchema_>,\n): DatabaseWriterService<DatabaseSchema_> => {\n type DataModel_ = DataModel.FromSchema<DatabaseSchema_>;\n\n const table = <const TableName extends DataModel.TableNames<DataModel_>>(\n tableName: TableName,\n ) => {\n const tableDef = DatabaseSchema.tables(databaseSchema)[tableName];\n\n const insert = Effect.fn(\"DatabaseWriter.insert\")(function* (\n document: Document.WithoutSystemFields<\n DocumentByName_<DataModel_, TableName>\n >,\n ) {\n const encodedDocument = yield* Document.encode(document, tableDef);\n\n const id = yield* Effect.promise(() =>\n convexDatabaseWriter.insert(\n tableName,\n encodedDocument as WithoutSystemFields<\n DocumentByName<DataModel.ToConvex<DataModel_>, TableName>\n >,\n ),\n );\n\n // The database supplies the ID in this table's execution scope. Its\n // scope brand is erased at the Convex syscall boundary.\n return id as unknown as DataModel.Id<DataModel_, TableName>;\n });\n\n // A codec whose encoding spans fields cannot encode a patch on its own, so\n // the patch is merged into the decoded document and the result replaces it.\n const replacePatched = (\n id: DataModel.Id<DataModel_, TableName>,\n patchedValues: PatchValue<\n Document.WithoutSystemFields<DocumentByName_<DataModel_, TableName>>\n >,\n ) =>\n Effect.gen(function* () {\n const originalDecodedDoc = yield* QueryInitializer.getById<\n Table.AnyWithProps,\n TableName\n >(\n convexDatabaseWriter as any,\n tableDef,\n )(id as unknown as GenericId<TableName>);\n\n const updatedEncodedDoc = yield* pipe(\n patchedValues,\n Record.reduce(originalDecodedDoc, (acc, value, key) =>\n value === undefined\n ? Record.remove(acc, key)\n : Record.set(acc, key, value),\n ),\n Document.encode(tableDef),\n );\n\n yield* Effect.promise(() =>\n convexDatabaseWriter.replace(\n id as unknown as GenericId<TableName>,\n updatedEncodedDoc as Expand<\n BetterOmit<\n DocumentByName<DataModel.ToConvex<DataModel_>, TableName>,\n \"_creationTime\" | \"_id\"\n >\n >,\n ),\n );\n });\n\n const patch = Effect.fn(\"DatabaseWriter.patch\")(function* (\n id: DataModel.Id<DataModel_, TableName>,\n patchedValues: PatchValue<\n Document.WithoutSystemFields<DocumentByName_<DataModel_, TableName>>\n >,\n ) {\n const encodePatch = DocumentPatch.encoder(tableDef);\n if (encodePatch === undefined) {\n return yield* replacePatched(id, patchedValues);\n }\n\n const storedDoc = yield* pipe(\n Effect.promise(() =>\n convexDatabaseWriter.get(id as unknown as GenericId<TableName>),\n ),\n Effect.andThen((value) =>\n Effect.fromResult(\n Result.fromNullishOr(\n value,\n () =>\n new QueryInitializer.GetByIdFailure({\n tableName,\n id,\n }),\n ),\n ),\n ),\n );\n // The patch must encode and the patched document must decode. When\n // either fails, the stored document decides whose fault that is.\n const encodedPatch = yield* pipe(\n encodePatch(patchedValues),\n Effect.mapError(({ message }) => message),\n Effect.tap((delta) =>\n pipe(\n { ...storedDoc, ...delta },\n Record.filter(Predicate.isNotUndefined),\n Document.decode(tableDef),\n Effect.mapError(({ parseError }) => parseError),\n ),\n ),\n Effect.catch((parseError) =>\n pipe(\n Document.decode(storedDoc, tableDef),\n Effect.andThen(\n Effect.fail(\n new Document.DocumentEncodeError({\n tableName,\n id,\n parseError,\n }),\n ),\n ),\n ),\n ),\n );\n\n yield* Effect.promise(() =>\n convexDatabaseWriter.patch(\n id as unknown as GenericId<TableName>,\n encodedPatch as Partial<\n DocumentByName<DataModel.ToConvex<DataModel_>, TableName>\n >,\n ),\n );\n });\n\n const replace = Effect.fn(\"DatabaseWriter.replace\")(function* (\n id: DataModel.Id<DataModel_, TableName>,\n value: Document.WithoutSystemFields<\n DocumentByName_<DataModel_, TableName>\n >,\n ) {\n const updatedEncodedDoc = yield* Document.encode(value, tableDef);\n\n yield* Effect.promise(() =>\n convexDatabaseWriter.replace(\n id as unknown as GenericId<TableName>,\n updatedEncodedDoc as Expand<\n BetterOmit<\n DocumentByName<DataModel.ToConvex<DataModel_>, TableName>,\n \"_creationTime\" | \"_id\"\n >\n >,\n ),\n );\n });\n\n const delete_ = (id: DataModel.Id<DataModel_, TableName>) =>\n Effect.promise(() =>\n convexDatabaseWriter.delete(id as unknown as GenericId<TableName>),\n );\n\n const accessor = { insert, patch, replace, delete: delete_ };\n if (hook === undefined) return accessor;\n\n const read = (id: DataModel.Id<DataModel_, TableName>) =>\n QueryInitializer.getById<Table.AnyWithProps, TableName>(\n convexDatabaseWriter as any,\n tableDef,\n )(id as unknown as GenericId<TableName>);\n const notify = (\n operation: \"insert\" | \"update\" | \"delete\",\n oldDoc: unknown,\n newDoc: unknown,\n ) =>\n hook({ tableName, operation, oldDoc, newDoc } as Change<DatabaseSchema_>);\n const update =\n <A extends ReadonlyArray<unknown>, E, BeforeError>(\n before: (\n id: DataModel.Id<DataModel_, TableName>,\n ) => Effect.Effect<unknown, BeforeError>,\n write: (\n id: DataModel.Id<DataModel_, TableName>,\n ...args: A\n ) => Effect.Effect<void, E>,\n ) =>\n (id: DataModel.Id<DataModel_, TableName>, ...args: A) =>\n Effect.gen(function* () {\n const oldDoc = yield* before(id);\n yield* write(id, ...args);\n yield* notify(\"update\", oldDoc, yield* read(id).pipe(Effect.orDie));\n });\n\n return {\n insert: (document: Parameters<typeof insert>[0]) =>\n Effect.gen(function* () {\n const id = yield* insert(document);\n yield* notify(\"insert\", null, yield* read(id).pipe(Effect.orDie));\n return id;\n }),\n patch: update(read, patch),\n replace: update((id) => read(id).pipe(Effect.orDie), replace),\n delete: (id: DataModel.Id<DataModel_, TableName>) =>\n Effect.gen(function* () {\n const oldDoc = yield* read(id).pipe(Effect.orDie);\n yield* delete_(id);\n yield* notify(\"delete\", oldDoc, null);\n }),\n };\n };\n\n return {\n table,\n } as DatabaseWriterService<DatabaseSchema_>;\n};\n\nexport const DatabaseWriter = <\n DatabaseSchema_ extends DatabaseSchema.AnyWithProps,\n Docs = {},\n>(): DatabaseWriterTag<DatabaseSchema_, Docs> =>\n Context.Service<\n DatabaseWriterService<DatabaseSchema_>,\n DatabaseWriterService<DatabaseSchema_, Docs>\n >(\"@confect/server/DatabaseWriter\");\n\nexport type DatabaseWriter<\n DatabaseSchema_ extends DatabaseSchema.AnyWithProps,\n> = DatabaseWriterService<DatabaseSchema_>;\n\nexport const layer = <DatabaseSchema_ extends DatabaseSchema.AnyWithProps>(\n databaseSchema: DatabaseSchema_,\n convexDatabaseWriter: GenericDatabaseWriter<\n DataModel.ToConvex<DataModel.FromSchema<DatabaseSchema_>>\n >,\n hook?: Hook<DatabaseSchema_>,\n) =>\n Layer.succeed(\n DatabaseWriter<DatabaseSchema_>(),\n make(databaseSchema, convexDatabaseWriter, hook),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgJA,MAAa,QACX,gBACA,sBAGA,SAC2C;CAG3C,MAAM,SACJ,cACG;EACH,MAAM,WAAWA,OAAsB,cAAc,CAAC,CAAC;EAEvD,MAAM,SAAS,OAAO,GAAG,uBAAuB,CAAC,CAAC,WAChD,UAGA;GACA,MAAM,kBAAkB,OAAOC,OAAgB,UAAU,QAAQ;GAajE,OAAO,OAXW,OAAO,cACvB,qBAAqB,OACnB,WACA,eAGF,CACF;EAKF,CAAC;EAID,MAAM,kBACJ,IACA,kBAIA,OAAO,IAAI,aAAa;GACtB,MAAM,qBAAqB,OAAOC,QAIhC,sBACA,QACF,CAAC,CAAC,EAAqC;GAEvC,MAAM,oBAAoB,OAAO,KAC/B,eACA,OAAO,OAAO,qBAAq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",
4
4
  "dependencies": {
5
5
  "@effect/ai-openai-compat": "4.0.4",
6
6
  "@effect/ai-openrouter": "4.0.4"
7
7
  },
8
8
  "peerDependencies": {
9
- "@confect/core": "npm:@gaganref/confect-core@10.3.1-fork.25",
9
+ "@confect/core": "npm:@gaganref/confect-core@10.3.1-fork.26",
10
10
  "@effect/platform-node": "^4.0.0",
11
11
  "convex": "^1.45.0",
12
12
  "effect": "^4.0.4"
@@ -100,11 +100,54 @@ export type DatabaseWriterTag<
100
100
  DatabaseWriterService<DatabaseSchema_, Docs>
101
101
  >;
102
102
 
103
+ /**
104
+ * Decoded documents surrounding one successful write.
105
+ */
106
+ export type Change<S extends DatabaseSchema.AnyWithProps> = {
107
+ [Name in DataModel.TableNames<DataModel.FromSchema<S>>]: {
108
+ readonly tableName: Name;
109
+ } & (
110
+ | {
111
+ readonly operation: "insert";
112
+ readonly oldDoc: null;
113
+ readonly newDoc: DocumentByName_<DataModel.FromSchema<S>, Name>;
114
+ }
115
+ | {
116
+ readonly operation: "update";
117
+ readonly oldDoc: DocumentByName_<DataModel.FromSchema<S>, Name>;
118
+ readonly newDoc: DocumentByName_<DataModel.FromSchema<S>, Name>;
119
+ }
120
+ | {
121
+ readonly operation: "delete";
122
+ readonly oldDoc: DocumentByName_<DataModel.FromSchema<S>, Name>;
123
+ readonly newDoc: null;
124
+ }
125
+ );
126
+ }[DataModel.TableNames<DataModel.FromSchema<S>>];
127
+
128
+ /**
129
+ * Runs after the write, in its transaction. A defect aborts the mutation.
130
+ *
131
+ * Only writes through this writer are observed. Raw `ctx.db`, `MutationCtx`
132
+ * writes and a second `DatabaseWriter.make` bypass the hook, so a host that
133
+ * relies on it keeps raw writers out of its functions. Component writers and
134
+ * nested `runMutation` calls each need their own hook installation.
135
+ *
136
+ * Concurrent writes to one document (for example under `Effect.all`) can
137
+ * interleave the read-write-read steps. Await them sequentially when the hook
138
+ * needs exact per-write snapshots. The writer takes no lock, because a hook
139
+ * that writes through the same writer would deadlock under one.
140
+ */
141
+ export type Hook<S extends DatabaseSchema.AnyWithProps> = (
142
+ change: Change<S>,
143
+ ) => Effect.Effect<void>;
144
+
103
145
  export const make = <DatabaseSchema_ extends DatabaseSchema.AnyWithProps>(
104
146
  databaseSchema: DatabaseSchema_,
105
147
  convexDatabaseWriter: GenericDatabaseWriter<
106
148
  DataModel.ToConvex<DataModel.FromSchema<DatabaseSchema_>>
107
149
  >,
150
+ hook?: Hook<DatabaseSchema_>,
108
151
  ): DatabaseWriterService<DatabaseSchema_> => {
109
152
  type DataModel_ = DataModel.FromSchema<DatabaseSchema_>;
110
153
 
@@ -267,11 +310,52 @@ export const make = <DatabaseSchema_ extends DatabaseSchema.AnyWithProps>(
267
310
  convexDatabaseWriter.delete(id as unknown as GenericId<TableName>),
268
311
  );
269
312
 
313
+ const accessor = { insert, patch, replace, delete: delete_ };
314
+ if (hook === undefined) return accessor;
315
+
316
+ const read = (id: DataModel.Id<DataModel_, TableName>) =>
317
+ QueryInitializer.getById<Table.AnyWithProps, TableName>(
318
+ convexDatabaseWriter as any,
319
+ tableDef,
320
+ )(id as unknown as GenericId<TableName>);
321
+ const notify = (
322
+ operation: "insert" | "update" | "delete",
323
+ oldDoc: unknown,
324
+ newDoc: unknown,
325
+ ) =>
326
+ hook({ tableName, operation, oldDoc, newDoc } as Change<DatabaseSchema_>);
327
+ const update =
328
+ <A extends ReadonlyArray<unknown>, E, BeforeError>(
329
+ before: (
330
+ id: DataModel.Id<DataModel_, TableName>,
331
+ ) => Effect.Effect<unknown, BeforeError>,
332
+ write: (
333
+ id: DataModel.Id<DataModel_, TableName>,
334
+ ...args: A
335
+ ) => Effect.Effect<void, E>,
336
+ ) =>
337
+ (id: DataModel.Id<DataModel_, TableName>, ...args: A) =>
338
+ Effect.gen(function* () {
339
+ const oldDoc = yield* before(id);
340
+ yield* write(id, ...args);
341
+ yield* notify("update", oldDoc, yield* read(id).pipe(Effect.orDie));
342
+ });
343
+
270
344
  return {
271
- insert,
272
- patch,
273
- replace,
274
- delete: delete_,
345
+ insert: (document: Parameters<typeof insert>[0]) =>
346
+ Effect.gen(function* () {
347
+ const id = yield* insert(document);
348
+ yield* notify("insert", null, yield* read(id).pipe(Effect.orDie));
349
+ return id;
350
+ }),
351
+ patch: update(read, patch),
352
+ replace: update((id) => read(id).pipe(Effect.orDie), replace),
353
+ delete: (id: DataModel.Id<DataModel_, TableName>) =>
354
+ Effect.gen(function* () {
355
+ const oldDoc = yield* read(id).pipe(Effect.orDie);
356
+ yield* delete_(id);
357
+ yield* notify("delete", oldDoc, null);
358
+ }),
275
359
  };
276
360
  };
277
361
 
@@ -298,8 +382,9 @@ export const layer = <DatabaseSchema_ extends DatabaseSchema.AnyWithProps>(
298
382
  convexDatabaseWriter: GenericDatabaseWriter<
299
383
  DataModel.ToConvex<DataModel.FromSchema<DatabaseSchema_>>
300
384
  >,
385
+ hook?: Hook<DatabaseSchema_>,
301
386
  ) =>
302
387
  Layer.succeed(
303
388
  DatabaseWriter<DatabaseSchema_>(),
304
- make(databaseSchema, convexDatabaseWriter),
389
+ make(databaseSchema, convexDatabaseWriter, hook),
305
390
  );