@shivaedev/changes 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.1 - 2026-10-30
4
+
5
+ ### Changed
6
+
7
+ - Require Effect 4.0.6 and align the Effect companion package peers and generated starter catalog to the same exact release. Install the 4.0.6 Effect stack together.
8
+
9
+ ### Fixed
10
+
11
+ - Register hosted RPC cache-control handling through Effect 4.0.6's request-scoped pre-response API so responses keep `private, no-store`.
12
+ - Accept native RPC's `application/x-ndjson` media type while preserving `application/ndjson` callers at the transport guard.
13
+ - Keep subscriptions open after their HTTP request body completes; closing the socket still cancels them.
14
+
15
+ ## 0.5.0 - 2026-10-28
16
+
17
+ ### Added
18
+
19
+ - Mark model fields with `bucket(schema)` from `@shivaedev/changes/buckets.ts`. SQL repositories announce each written record and its old and new buckets after commit, including inserts, deletes, void writes and conflict writes. Bucket codecs decode stored values before building query keys; absent values have no bucket. Bucket writes require PostgreSQL 18 or later for atomic old-row observations.
20
+
21
+ ### Fixed
22
+
23
+ - Enforce declared query read policies at the hosted RPC handler boundary, including contracts without identity middleware, whose viewer is anonymous. Query RPC error schemas include `QueryReadDenied` so native clients receive typed refusals before handlers run.
24
+ - Keep collection methods and untyped schema internals from making data parameters appear to carry callable services. Direct service implementations, nested dependency fields and service arrays remain subject to `effect/service-parameters`.
25
+
26
+ ### Breaking
27
+
28
+ - Move key imports from `@shivaedev/contract/keys.ts` to `@shivaedev/changes/keys.ts`. Declare bucket fields with `collection(name, idSchema, fields)` and publish affected buckets alongside record keys.
29
+ - Replace collection policy maps, `mergeReadPolicies`, `ReadPolicy` and `ReadPolicyMemoWindow` with each query's `readPolicy(payload, viewer)`. Declare the same query's live scope with `reads(payload, viewer)`. Bound query atoms and subscriptions refuse missing policies with a declaration error; one-off query `run` calls remain available. Denied queries refuse the entire subscription. Server adapters replace `QueryReads` and `ChangesReads` with `QueryDefinition` and `ChangesQueries`. Custom middleware calls `authorizeReads(effect, request, viewer)` and declares `MissingReadPolicy` and `QueryReadDenied` errors.
30
+ - Custom subscription adapters yield `ChangesQueries.resolve(references)`, call `querySubscription(requests, viewer)` and pass the authorized result to `makeLiveServer.subscribe(subscription, context)`. Metadata values expose `QueryDefinition.definition` and `CommandInvalidation.invalidates` instead of bare definitions and callbacks. Yield the Effect returned by `queryKeys(queries, references)` when projecting keys for a custom stream. `resolveChanges` supplies the authorized subscription in hosted applications. Changed hints can carry query positions so bindings can rerun session-scoped reads without deriving session scopes in the browser.
31
+ - Remove `appHost`'s `readPolicy` option and module policy registration. Session and permission middleware apply query policies using the current session viewer. Handle the new typed policy errors in native clients, including `QueryReadDenied` on query RPCs without identity middleware; widen explicit query error annotations accordingly.
32
+ - Replace `sessionCommandChanges` with `commandChanges` for custom session middleware. Command invalidation callbacks can receive the session viewer as their third argument. Announce viewer buckets there; background writers must explicitly publish those bucket keys after commit.
33
+ - Built-in admin queries declare their permission policies alongside their schemas and read scopes. Consumers keep supplying the existing session and permission middleware layers.
34
+ - Local Work Board and Fleet queries declare their existing loopback read access explicitly so their generated live subscriptions remain available.
35
+ - `withChangeCoverage` now requires every declared record and bucket key, and a table name alone no longer covers a raw write. Migrate `covers` values from strings to typed item and bucket keys, and record `invalidationKeys(changedKeys)` through `invalidateOnCommit`. Repository writes declare their own keys automatically; raw writers declare all affected records and buckets.
36
+ - Bulk repository writes retain every record key instead of replacing them with `<table>:*` above 1,000 rows. Consumers observing raw notifications should handle the complete key set, which can span several NOTIFY payloads.
37
+ - Direct callers of the repository implementation helpers must pass a `RepositoryChanges` boundary to `makeCompositeCrud`; `versionedStatements` no longer returns `returningKeys`. Use the boundary's `returning()` fragment so void writes retain the row's bucket fields.
38
+
3
39
  ## 0.4.0 - 2026-10-27
4
40
 
5
41
  ### Breaking
package/README.md CHANGED
@@ -29,7 +29,6 @@ Owners matter when a program uses more than one database or client. Owner B comm
29
29
  The channel owns notifications, not writes. Record descriptions of what needs refreshing beside the write that affects it. Choose a key that identifies notifications that can share one refresh; this boundary is for coalescing refresh work, rather than storing every business event.
30
30
 
31
31
  The work has three parts:
32
-
33
32
  1. Once per binding, define the change type, owner, key and publish function, and bind the native transaction.
34
33
  2. Once per feature, record the subjects affected by each write.
35
34
  3. In each operation, run the feature through the transaction boundary or group autocommitted work with a batch.
@@ -42,19 +41,20 @@ import { Effect } from "effect";
42
41
  import { SqlClient } from "effect/sql";
43
42
 
44
43
  interface MembershipChange {
45
- readonly subject: string;
46
- readonly domain: string;
44
+ readonly subject: string;
45
+ readonly domain: string;
47
46
  }
48
47
 
49
48
  const published: Array<MembershipChange> = [];
50
49
 
51
50
  const membershipChanges = makeChannel<MembershipChange, SqlClient.SqlClient>({
52
- name: "MembershipChanges",
53
- owner: Effect.map(SqlClient.SqlClient, (sql) => sql.transactionService),
54
- key: (change) => `${change.subject}:${change.domain}`,
55
- publish: (changes) => Effect.sync(() => {
56
- published.push(...changes);
57
- }),
51
+ name: "MembershipChanges",
52
+ owner: Effect.map(SqlClient.SqlClient, (sql) => sql.transactionService),
53
+ key: (change) => `${change.subject}:${change.domain}`,
54
+ publish: (changes) =>
55
+ Effect.sync(() => {
56
+ published.push(...changes);
57
+ }),
58
58
  });
59
59
  ```
60
60
 
@@ -66,14 +66,14 @@ The owner is the native SQL client's transaction-service identity. The key group
66
66
 
67
67
  ```ts
68
68
  const grantMembership = (owner: string, member: string) =>
69
- Effect.gen(function* () {
70
- const sql = yield* SqlClient.SqlClient;
71
- yield* sql`insert into membership (owner, member) values (${owner}, ${member})`;
72
- yield* membershipChanges.record([
73
- { subject: owner, domain: "memberships" },
74
- { subject: member, domain: "memberships" },
75
- ]);
76
- });
69
+ Effect.gen(function* () {
70
+ const sql = yield* SqlClient.SqlClient;
71
+ yield* sql`insert into membership (owner, member) values (${owner}, ${member})`;
72
+ yield* membershipChanges.record([
73
+ { subject: owner, domain: "memberships" },
74
+ { subject: member, domain: "memberships" },
75
+ ]);
76
+ });
77
77
  ```
78
78
 
79
79
  One write can name several subjects. `record` deduplicates the supplied changes by the channel's key, and the transaction frame deduplicates across later records and committed nested frames. Keys retain their first-seen order.
@@ -84,12 +84,10 @@ Record while the transaction body is still running. A record or a nested frame o
84
84
 
85
85
  ```ts
86
86
  const grant = (owner: string, member: string) =>
87
- Effect.gen(function* () {
88
- const sql = yield* SqlClient.SqlClient;
89
- return yield* grantMembership(owner, member).pipe(
90
- membershipChanges.within(sql.withTransaction),
91
- );
92
- });
87
+ Effect.gen(function* () {
88
+ const sql = yield* SqlClient.SqlClient;
89
+ return yield* grantMembership(owner, member).pipe(membershipChanges.within(sql.withTransaction));
90
+ });
93
91
  ```
94
92
 
95
93
  Provide the application's native SQL layer when running `grant`. Publication happens after the native transaction succeeds and before the wrapper returns. A typed failure, defect, body interruption or failed commit discards the root frame. A nested commit merges into its parent; a nested rollback leaves the parent's own changes intact.
@@ -98,12 +96,39 @@ When interruption arrives while commit is in flight, the boundary waits for the
98
96
 
99
97
  Concurrent records from Effects that inherit the same frame join that frame and publish together. Keep all write-related work within the transaction's lifetime.
100
98
 
99
+ ### Record keys and buckets
100
+
101
+ `keys.ts` owns the shared dependency format for contract queries, committed writes and subscriptions. An item key identifies a record by id. A bucket identifies every row with a declared field value; a collection list key covers the whole collection.
102
+
103
+ ```ts
104
+ import { Schema } from "effect";
105
+ import { collection, invalidationKeys } from "@shivaedev/changes/keys.ts";
106
+
107
+ const notes = collection("notes", Schema.Number, { userId: Schema.String, listId: Schema.Number });
108
+ const keys = [notes.item(1), notes.bucket.userId("alice"), notes.bucket.listId(42)];
109
+ const invalidations = invalidationKeys(keys);
110
+ ```
111
+
112
+ Use `readKeys(keys)` to register dependencies with native Reactivity and `invalidationKeys(keys)` when announcing committed writes. A bucket changes when the writer names it; SQL repositories derive those names from model fields marked with `bucket`. Its value is typed by the declared field schema. A filtered list query still reads its entire bucket and reruns when any row there changes. Record changes also invalidate the collection list, while buckets remain explicit. The channel can buffer these keys until commit just like any other change vocabulary.
113
+
114
+ `bucket(schema)` from `@shivaedev/changes/buckets.ts` declares a model field as a write bucket without changing its schema type or variants:
115
+
116
+ ```ts
117
+ import { bucket } from "@shivaedev/changes/buckets.ts";
118
+
119
+ const listId = bucket(Schema.NumberFromString);
120
+ ```
121
+
122
+ The SQL binding reads these declarations with `declaredBuckets(model.fields)` and decodes old and new stored values into the same identity values queries use. Bucket schemas decode to strings, numbers, null or undefined and require no services. Absent values contribute no key. See the [SQL guide](https://github.com/ShivaeDev/platform/blob/main/packages/sql/README.md#transactions-and-invalidation) for repository writes and PostgreSQL requirements.
123
+
124
+ Query read policies belong to the contract. The query checks its session viewer before its record or bucket scope can become a subscription; a change key grants no read permission. See the [contract query guide](https://github.com/ShivaeDev/platform/blob/main/packages/contract/README.md#query-policies-record-keys-and-buckets).
125
+
101
126
  ### Group already-autocommitted writes
102
127
 
103
128
  ```ts
104
129
  const grantSeveral = Effect.gen(function* () {
105
- yield* grantMembership("ada", "bob");
106
- yield* grantMembership("ada", "cyd");
130
+ yield* grantMembership("ada", "bob");
131
+ yield* grantMembership("ada", "cyd");
107
132
  }).pipe(membershipChanges.batch);
108
133
  ```
109
134
 
@@ -138,23 +163,19 @@ import { Layer } from "effect";
138
163
  const captured: Array<MembershipChange> = [];
139
164
  const observations: Array<Observation<MembershipChange>> = [];
140
165
 
141
- const captureSink = Layer.succeed(
142
- membershipChanges.Sink,
143
- (changes: readonly MembershipChange[]) => Effect.sync(() => {
144
- captured.push(...changes);
145
- }),
166
+ const captureSink = Layer.succeed(membershipChanges.Sink, (changes: readonly MembershipChange[]) =>
167
+ Effect.sync(() => {
168
+ captured.push(...changes);
169
+ }),
146
170
  );
147
171
 
148
- const observe = Layer.succeed(
149
- membershipChanges.Observer,
150
- (observation: Observation<MembershipChange>) => Effect.sync(() => {
151
- observations.push(observation);
152
- }),
172
+ const observe = Layer.succeed(membershipChanges.Observer, (observation: Observation<MembershipChange>) =>
173
+ Effect.sync(() => {
174
+ observations.push(observation);
175
+ }),
153
176
  );
154
177
 
155
- const capturedGrant = grant("ada", "bob").pipe(
156
- Effect.provide(Layer.merge(captureSink, observe)),
157
- );
178
+ const capturedGrant = grant("ada", "bob").pipe(Effect.provide(Layer.merge(captureSink, observe)));
158
179
  ```
159
180
 
160
181
  `Sink` and `Observer` are channel-specific `Context.Reference`s. Within the provided scope, the sink receives the changes instead of the configured publish function; the configured sink resumes outside it. The observer receives `Recorded` for the distinct changes in a record call, `Published` for the buffer passed to publication and `Discarded` for a rolled-back frame's changes. `Published` is emitted before the sink runs; it does not prove successful delivery. Discarded parent changes include changes merged from children that committed earlier. A rollback therefore remains visible to a coverage check through its earlier `Recorded` observation.
@@ -169,23 +190,26 @@ A direct driver binding using `open` must run `frame.beforeCommit` inside its tr
169
190
 
170
191
  Import from the module that defines the name; the package has no root entry.
171
192
 
172
- | Module | Names |
173
- | --- | --- |
174
- | `channel.ts` | `makeChannel`, `ChannelOptions`, `Channel`, `BeforeCommit` |
175
- | `frame.ts` | `Frame`, `CommitFrame`, `Outcome` |
176
- | `observe.ts` | `Observation`, `Observer` |
177
- | `publish.ts` | `Publish`, `PublishFailure` |
193
+ | Module | Names |
194
+ | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
195
+ | `@shivaedev/changes/channel.ts` | `makeChannel`, `ChannelOptions`, `Channel`, `BeforeCommit` |
196
+ | `@shivaedev/changes/frame.ts` | `Frame`, `CommitFrame`, `Outcome` |
197
+ | `@shivaedev/changes/observe.ts` | `Observation`, `Observer` |
198
+ | `@shivaedev/changes/publish.ts` | `Publish`, `PublishFailure` |
199
+ | `@shivaedev/changes/keys.ts` | `collection`, `readKeys`, `invalidationKeys`, `Key`, `ListKey`, `ItemKey`, `BucketKey`, `Collection`, `Identity`, `KeyContext` |
200
+ | `@shivaedev/changes/buckets.ts` | `bucket`, `declaredBuckets` |
201
+
202
+ A `Channel` exposes `record`, `within`, `batch` and `open`, and the scoped references `Sink`, `CommittedSink`, `Observer` and `BeforeCommit`.
178
203
 
179
204
  `key` is optional; for string changes, omitting it deduplicates repeated strings. A custom key is useful when a change is a structured description of an affected subject.
180
205
 
181
206
  ### Install, setup and limits
182
207
 
183
208
  ```sh
184
- pnpm add @shivaedev/changes effect@4.0.5
209
+ pnpm add @shivaedev/changes effect
185
210
  ```
186
211
 
187
212
  `effect` is a peer dependency, so the application's Effect version runs the channel. The package declares Node 24 or newer. The SQL example also needs the application's native SQL driver and layer; neither the channel nor its installation creates a database connection or table.
188
-
189
213
  - The channel is an in-process notification boundary. It has no persistent outbox, replay or cross-process transport; deployment delivery requires a separate design.
190
214
  - Only explicitly recorded changes reach the channel. Trigger, cascade and raw SQL write discovery belongs to a binding or the application.
191
215
  - A native adapter must observe the real commit outcome. Wrapping only the body of a transaction does not establish that outcome.
@@ -0,0 +1,10 @@
1
+ import { Schema } from "effect";
2
+ import type { Identity } from "#keys.ts";
3
+ type BucketValue = Identity | null | undefined;
4
+ export declare function bucket<TSchema extends Schema.Top & Schema.ConstraintCodec<BucketValue, unknown, never, never>>(schema: TSchema): TSchema["Rebuild"];
5
+ export declare function declaredBuckets(fields: Schema.Struct.Fields): {
6
+ decode: (input: unknown, options?: import("effect/SchemaAST").ParseOptions) => import("effect/Effect").Effect<BucketValue, Schema.SchemaError, never>;
7
+ field: string;
8
+ }[];
9
+ export {};
10
+ //# sourceMappingURL=buckets.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buckets.d.ts","sourceRoot":"","sources":["../src/buckets.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEzC,KAAK,WAAW,GAAG,QAAQ,GAAG,IAAI,GAAG,SAAS,CAAC;AAE/C,wBAAgB,MAAM,CAAC,OAAO,SAAS,MAAM,CAAC,GAAG,GAAG,MAAM,CAAC,eAAe,CAAC,WAAW,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC,EAAE,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,CAEnJ;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM;;;IAQ3D"}
@@ -0,0 +1,14 @@
1
+ import { Schema } from "effect";
2
+ export function bucket(schema) {
3
+ return schema.annotate({ "@shivaedev/changes/bucket": true });
4
+ }
5
+ export function declaredBuckets(fields) {
6
+ return Object.entries(fields).flatMap(([field, schema]) => {
7
+ if (Schema.resolveAnnotations(schema)?.["@shivaedev/changes/bucket"] !== true) {
8
+ return [];
9
+ }
10
+ const codec = Schema.make(schema.ast);
11
+ return [{ decode: Schema.decodeUnknownEffect(codec), field }];
12
+ });
13
+ }
14
+ //# sourceMappingURL=buckets.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buckets.js","sourceRoot":"","sources":["../src/buckets.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAKhC,MAAM,UAAU,MAAM,CAA0F,MAAe;IAC9H,OAAO,MAAM,CAAC,QAAQ,CAAC,EAAE,2BAA2B,EAAE,IAAI,EAAE,CAAC,CAAC;AAC/D,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,MAA4B;IAC3D,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,MAAM,CAAC,EAAE,EAAE;QACzD,IAAI,MAAM,CAAC,kBAAkB,CAAC,MAAM,CAAC,EAAE,CAAC,2BAA2B,CAAC,KAAK,IAAI,EAAE,CAAC;YAC/E,OAAO,EAAE,CAAC;QACX,CAAC;QACD,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAqC,MAAM,CAAC,GAAG,CAAC,CAAC;QAC1E,OAAO,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,mBAAmB,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;IAC/D,CAAC,CAAC,CAAC;AACJ,CAAC"}
package/dist/keys.d.ts ADDED
@@ -0,0 +1,52 @@
1
+ import { Schema } from "effect";
2
+ export type Identity = string | number;
3
+ export interface ListKey<TName extends string = string> {
4
+ readonly _tag: "List";
5
+ readonly collection: TName;
6
+ }
7
+ export interface ItemKey<TName extends string = string> {
8
+ readonly _tag: "Item";
9
+ readonly collection: TName;
10
+ readonly id: Identity;
11
+ }
12
+ export interface BucketKey<TName extends string = string> {
13
+ readonly _tag: "Bucket";
14
+ readonly collection: TName;
15
+ readonly field: string;
16
+ readonly value: Identity;
17
+ }
18
+ export type Key = ListKey | ItemKey | BucketKey;
19
+ export declare const Key: Schema.Union<readonly [Schema.Struct<{
20
+ readonly _tag: Schema.Literal<"Bucket">;
21
+ readonly collection: Schema.String;
22
+ readonly field: Schema.String;
23
+ readonly value: Schema.Union<readonly [Schema.String, Schema.Number]>;
24
+ }>, Schema.Struct<{
25
+ readonly _tag: Schema.Literal<"List">;
26
+ readonly collection: Schema.String;
27
+ }>, Schema.Struct<{
28
+ readonly _tag: Schema.Literal<"Item">;
29
+ readonly collection: Schema.String;
30
+ readonly id: Schema.Union<readonly [Schema.String, Schema.Number]>;
31
+ }>]>;
32
+ type BucketFields = Readonly<Record<string, Schema.Top & {
33
+ readonly Type: Identity;
34
+ }>>;
35
+ export interface Collection<TName extends string, TId extends Identity, TFields extends BucketFields = Record<never, never>> {
36
+ readonly bucket: {
37
+ readonly [TField in keyof TFields]: (value: TFields[TField]["Type"]) => BucketKey<TName>;
38
+ };
39
+ readonly item: (id: TId) => ItemKey<TName>;
40
+ readonly list: ListKey<TName>;
41
+ readonly name: TName;
42
+ }
43
+ export declare function collection<const TName extends string, TId extends Schema.Top & {
44
+ readonly Type: Identity;
45
+ }, const TFields extends BucketFields = Record<never, never>>(name: TName, _id: TId, fields?: TFields): Collection<TName, TId["Type"], TFields>;
46
+ export interface KeyContext {
47
+ readonly scope: string;
48
+ }
49
+ export declare function readKeys(keys: readonly Key[], context?: KeyContext): readonly string[];
50
+ export declare function invalidationKeys(keys: readonly Key[], context?: KeyContext): readonly string[];
51
+ export {};
52
+ //# sourceMappingURL=keys.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keys.d.ts","sourceRoot":"","sources":["../src/keys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,MAAM,CAAC;AAEvC,MAAM,WAAW,OAAO,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM;IACrD,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,UAAU,EAAE,KAAK,CAAC;CAC3B;AAED,MAAM,WAAW,OAAO,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM;IACrD,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,UAAU,EAAE,KAAK,CAAC;IAC3B,QAAQ,CAAC,EAAE,EAAE,QAAQ,CAAC;CACtB;AAED,MAAM,WAAW,SAAS,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM;IACvD,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IACxB,QAAQ,CAAC,UAAU,EAAE,KAAK,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC;CACzB;AACD,MAAM,MAAM,GAAG,GAAG,OAAO,GAAG,OAAO,GAAG,SAAS,CAAC;AAEhD,eAAO,MAAM,GAAG;;;;;;;;;;;;IASd,CAAC;AAEH,KAAK,YAAY,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAA;CAAE,CAAC,CAAC,CAAC;AACvF,MAAM,WAAW,UAAU,CAAC,KA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
1
+ import { Schema } from "effect";
2
+ export const Key = Schema.Union([
3
+ Schema.Struct({
4
+ _tag: Schema.Literal("Bucket"),
5
+ collection: Schema.String,
6
+ field: Schema.String,
7
+ value: Schema.Union([Schema.String, Schema.Number]),
8
+ }),
9
+ Schema.Struct({ _tag: Schema.Literal("List"), collection: Schema.String }),
10
+ Schema.Struct({ _tag: Schema.Literal("Item"), collection: Schema.String, id: Schema.Union([Schema.String, Schema.Number]) }),
11
+ ]);
12
+ export function collection(name, _id, fields = {}) {
13
+ return {
14
+ bucket: Object.fromEntries(Object.keys(fields).map((field) => [field, (value) => ({ _tag: "Bucket", collection: name, field, value })])),
15
+ item: (id) => ({ _tag: "Item", collection: name, id }),
16
+ list: { _tag: "List", collection: name },
17
+ name,
18
+ };
19
+ }
20
+ function contextual(key, context) {
21
+ return context === undefined ? key : `${JSON.stringify(["session", context.scope])}:${key}`;
22
+ }
23
+ function own(key) {
24
+ switch (key._tag) {
25
+ case "List":
26
+ return key.collection;
27
+ case "Item":
28
+ return `${key.collection}:${key.id}`;
29
+ case "Bucket":
30
+ return JSON.stringify(["bucket", key.collection, key.field, key.value]);
31
+ }
32
+ }
33
+ export function readKeys(keys, context) {
34
+ return [...new Set(keys.flatMap((key) => (key._tag === "Item" ? [own(key), `${key.collection}:*`] : [own(key)])))].map((key) => contextual(key, context));
35
+ }
36
+ export function invalidationKeys(keys, context) {
37
+ return [...new Set(keys.flatMap((key) => (key._tag === "Item" ? [own(key), key.collection] : [own(key)])))].map((key) => contextual(key, context));
38
+ }
39
+ //# sourceMappingURL=keys.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keys.js","sourceRoot":"","sources":["../src/keys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAuBhC,MAAM,CAAC,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC;IAC/B,MAAM,CAAC,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC,OAA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MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AACpJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shivaedev/changes",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "Commit-bound change channels for Effect: publish recorded changes only after the transaction commits",
5
5
  "keywords": [
6
6
  "effect"
@@ -43,15 +43,15 @@
43
43
  "README.md"
44
44
  ],
45
45
  "devDependencies": {
46
- "@shivaedev/quality": "0.42.0",
47
- "@shivaedev/test-story": "0.21.0",
46
+ "@shivaedev/quality": "0.45.0",
47
+ "@shivaedev/test-story": "0.24.0",
48
48
  "@types/node": "24.19.2",
49
- "effect": "4.0.5",
49
+ "effect": "4.0.6",
50
50
  "typescript": "7.0.2",
51
51
  "vitest": "5.0.5"
52
52
  },
53
53
  "peerDependencies": {
54
- "effect": "4.0.5"
54
+ "effect": "4.0.6"
55
55
  },
56
56
  "engines": {
57
57
  "node": ">=24"
package/src/buckets.ts ADDED
@@ -0,0 +1,18 @@
1
+ import { Schema } from "effect";
2
+ import type { Identity } from "#keys.ts";
3
+
4
+ type BucketValue = Identity | null | undefined;
5
+
6
+ export function bucket<TSchema extends Schema.Top & Schema.ConstraintCodec<BucketValue, unknown, never, never>>(schema: TSchema): TSchema["Rebuild"] {
7
+ return schema.annotate({ "@shivaedev/changes/bucket": true });
8
+ }
9
+
10
+ export function declaredBuckets(fields: Schema.Struct.Fields) {
11
+ return Object.entries(fields).flatMap(([field, schema]) => {
12
+ if (Schema.resolveAnnotations(schema)?.["@shivaedev/changes/bucket"] !== true) {
13
+ return [];
14
+ }
15
+ const codec = Schema.make<Schema.Codec<BucketValue, unknown>>(schema.ast);
16
+ return [{ decode: Schema.decodeUnknownEffect(codec), field }];
17
+ });
18
+ }
package/src/keys.ts ADDED
@@ -0,0 +1,86 @@
1
+ import { Schema } from "effect";
2
+
3
+ export type Identity = string | number;
4
+
5
+ export interface ListKey<TName extends string = string> {
6
+ readonly _tag: "List";
7
+ readonly collection: TName;
8
+ }
9
+
10
+ export interface ItemKey<TName extends string = string> {
11
+ readonly _tag: "Item";
12
+ readonly collection: TName;
13
+ readonly id: Identity;
14
+ }
15
+
16
+ export interface BucketKey<TName extends string = string> {
17
+ readonly _tag: "Bucket";
18
+ readonly collection: TName;
19
+ readonly field: string;
20
+ readonly value: Identity;
21
+ }
22
+ export type Key = ListKey | ItemKey | BucketKey;
23
+
24
+ export const Key = Schema.Union([
25
+ Schema.Struct({
26
+ _tag: Schema.Literal("Bucket"),
27
+ collection: Schema.String,
28
+ field: Schema.String,
29
+ value: Schema.Union([Schema.String, Schema.Number]),
30
+ }),
31
+ Schema.Struct({ _tag: Schema.Literal("List"), collection: Schema.String }),
32
+ Schema.Struct({ _tag: Schema.Literal("Item"), collection: Schema.String, id: Schema.Union([Schema.String, Schema.Number]) }),
33
+ ]);
34
+
35
+ type BucketFields = Readonly<Record<string, Schema.Top & { readonly Type: Identity }>>;
36
+ export interface Collection<TName extends string, TId extends Identity, TFields extends BucketFields = Record<never, never>> {
37
+ readonly bucket: { readonly [TField in keyof TFields]: (value: TFields[TField]["Type"]) => BucketKey<TName> };
38
+ readonly item: (id: TId) => ItemKey<TName>;
39
+ readonly list: ListKey<TName>;
40
+ readonly name: TName;
41
+ }
42
+
43
+ export function collection<
44
+ const TName extends string,
45
+ TId extends Schema.Top & { readonly Type: Identity },
46
+ const TFields extends BucketFields = Record<never, never>,
47
+ >(name: TName, _id: TId, fields?: TFields): Collection<TName, TId["Type"], TFields>;
48
+ export function collection(name: string, _id: Schema.Top, fields: BucketFields = {}) {
49
+ return {
50
+ bucket: Object.fromEntries(
51
+ Object.keys(fields).map((field) => [field, (value: Identity): BucketKey => ({ _tag: "Bucket", collection: name, field, value })]),
52
+ ),
53
+ item: (id: Identity): ItemKey => ({ _tag: "Item", collection: name, id }),
54
+ list: { _tag: "List", collection: name },
55
+ name,
56
+ };
57
+ }
58
+
59
+ export interface KeyContext {
60
+ readonly scope: string;
61
+ }
62
+
63
+ function contextual(key: string, context?: KeyContext): string {
64
+ return context === undefined ? key : `${JSON.stringify(["session", context.scope])}:${key}`;
65
+ }
66
+
67
+ function own(key: Key): string {
68
+ switch (key._tag) {
69
+ case "List":
70
+ return key.collection;
71
+ case "Item":
72
+ return `${key.collection}:${key.id}`;
73
+ case "Bucket":
74
+ return JSON.stringify(["bucket", key.collection, key.field, key.value]);
75
+ }
76
+ }
77
+
78
+ export function readKeys(keys: readonly Key[], context?: KeyContext): readonly string[] {
79
+ return [...new Set(keys.flatMap((key) => (key._tag === "Item" ? [own(key), `${key.collection}:*`] : [own(key)])))].map((key) =>
80
+ contextual(key, context),
81
+ );
82
+ }
83
+
84
+ export function invalidationKeys(keys: readonly Key[], context?: KeyContext): readonly string[] {
85
+ return [...new Set(keys.flatMap((key) => (key._tag === "Item" ? [own(key), key.collection] : [own(key)])))].map((key) => contextual(key, context));
86
+ }