@collective-intelligence/external-apps-client-sdk-react 0.11.0 → 0.12.0

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.
@@ -0,0 +1,322 @@
1
+ // Generated by dts-bundle-generator v9.5.1
2
+
3
+ import { EffectRunner } from '@collective-intelligence/effect-xstate/actors';
4
+ import { ResourceDefinition } from '@collective-intelligence/external-apps-client-sdk/resources';
5
+ import { Collection, DbClient, DehydratedDbState } from '@tanstack/db';
6
+ import { DehydratedState, QueryClient } from '@tanstack/query-core';
7
+ import { QueryKey } from '@tanstack/react-query';
8
+ import * as Cause from 'effect/Cause';
9
+ import * as Context from 'effect/Context';
10
+ import * as Duration from 'effect/Duration';
11
+ import * as Effect from 'effect/Effect';
12
+ import * as Exit from 'effect/Exit';
13
+ import * as Layer from 'effect/Layer';
14
+ import * as ManagedRuntime from 'effect/ManagedRuntime';
15
+ import * as Option$1 from 'effect/Option';
16
+ import * as Schema from 'effect/Schema';
17
+ import * as Scope from 'effect/Scope';
18
+ import { ReactNode } from 'react';
19
+ import { CallbackActorLogic, PromiseActorLogic } from 'xstate';
20
+
21
+ declare const RecordWriteRefused_base: Schema.Class<RecordWriteRefused, Schema.TaggedStruct<"RecordWriteRefused", {
22
+ readonly message: Schema.String;
23
+ }>, Cause.YieldableError>;
24
+ /**
25
+ * CI refused the write, for example an invalid value or a missing
26
+ * permission. Sending it again with the same key gets the same answer.
27
+ */
28
+ export declare class RecordWriteRefused extends RecordWriteRefused_base {
29
+ }
30
+ declare const RecordWriteConflict_base: Schema.Class<RecordWriteConflict, Schema.TaggedStruct<"RecordWriteConflict", {
31
+ readonly message: Schema.String;
32
+ }>, Cause.YieldableError>;
33
+ /**
34
+ * The write conflicts with the record that CI holds: a stale revision, a
35
+ * taken client id, or an idempotency key reused for another write.
36
+ */
37
+ export declare class RecordWriteConflict extends RecordWriteConflict_base {
38
+ }
39
+ declare const RecordWriteOutcomeUnknown_base: Schema.Class<RecordWriteOutcomeUnknown, Schema.TaggedStruct<"RecordWriteOutcomeUnknown", {
40
+ readonly cause: Schema.optional<Schema.Defect>;
41
+ readonly message: Schema.String;
42
+ }>, Cause.YieldableError>;
43
+ /**
44
+ * The answer to the write was lost: CI may or may not have applied it. Only
45
+ * this failure is sent again with the same idempotency key.
46
+ */
47
+ export declare class RecordWriteOutcomeUnknown extends RecordWriteOutcomeUnknown_base {
48
+ }
49
+ declare const RecordSyncFailed_base: Schema.Class<RecordSyncFailed, Schema.TaggedStruct<"RecordSyncFailed", {
50
+ readonly cause: Schema.optional<Schema.Defect>;
51
+ readonly message: Schema.String;
52
+ readonly retrying: Schema.Boolean;
53
+ }>, Cause.YieldableError>;
54
+ /**
55
+ * A Record Collection could not load or follow its records. `retrying` tells
56
+ * that its sync keeps trying, so the rows and the status stay.
57
+ */
58
+ export declare class RecordSyncFailed extends RecordSyncFailed_base {
59
+ }
60
+ /** The typed failures of one record write. */
61
+ export type RecordWriteError = RecordWriteConflict | RecordWriteOutcomeUnknown | RecordWriteRefused;
62
+ /** The id of a CI record. */
63
+ export declare const RecordId: Schema.brand<Schema.String, "RecordId">;
64
+ export type RecordId = typeof RecordId.Type;
65
+ declare const RecordRevision: Schema.brand<Schema.String, "RecordRevision">;
66
+ export type RecordRevision = typeof RecordRevision.Type;
67
+ /** The key that makes a resent write apply once (Write Receipt). */
68
+ export declare const IdempotencyKey: Schema.brand<Schema.String, "IdempotencyKey">;
69
+ export type IdempotencyKey = typeof IdempotencyKey.Type;
70
+ /**
71
+ * One row of a Record Collection: a CI record with its revision and value.
72
+ * `revision` is `null` while a create waits for CI's answer.
73
+ */
74
+ export type RecordRow<Value> = Readonly<{
75
+ id: RecordId;
76
+ revision: RecordRevision | null;
77
+ value: Value;
78
+ }>;
79
+ /** The schema of a record value; it decodes with no service. */
80
+ export type RecordValueSchema<Value extends object> = Schema.Codec<Value, unknown>;
81
+ /** One record as CI sends it, before decoding. */
82
+ export type UndecodedRecord = Readonly<{
83
+ id: string;
84
+ revision: string | null;
85
+ value: unknown;
86
+ }>;
87
+ /** The records of one entity schema, named by FQN or id, optionally filtered. */
88
+ export type RecordTopic = Readonly<{
89
+ schema: string;
90
+ filter?: Readonly<{
91
+ field: string;
92
+ eq: string | number | boolean | null;
93
+ }>;
94
+ }>;
95
+ /**
96
+ * Where a write goes. The SDK adapter that makes the target knows what
97
+ * `key` names; the record layer only reads `key`, which is stable for one
98
+ * target.
99
+ */
100
+ export type RecordWriteTarget = Readonly<{
101
+ key: string;
102
+ }>;
103
+ /** A Record Collection kept fresh by the Change Hints of one Realtime Topic. */
104
+ export type RealtimeRecordCollection<T extends object> = Collection<T, string>;
105
+ export interface RecordCollectionsValue {
106
+ /** The Realtime Record Collection of one Realtime Topic. */
107
+ readonly realtime: <Value extends object>(topic: RecordTopic, schema: RecordValueSchema<Value>) => Effect.Effect<RealtimeRecordCollection<RecordRow<Value>>>;
108
+ /**
109
+ * The Query Record Collection of one query on the app's shared QueryClient.
110
+ * Its `load` runs with the context of this call, so it may need services.
111
+ */
112
+ readonly query: <Value extends object, E = never, R = never>(options: QueryRecordCollectionOptions<Value, E, R>) => Effect.Effect<QueryRecordCollection<RecordRow<Value>>, never, R>;
113
+ }
114
+ declare const RecordCollections_base: Context.ServiceClass<RecordCollections, "@collective-intelligence/records/RecordCollections", RecordCollectionsValue>;
115
+ /** The Record Collections of one CI identity. */
116
+ export declare class RecordCollections extends RecordCollections_base {
117
+ }
118
+ /** A Record Collection whose rows hold values of type `Value`. */
119
+ export type RecordCollection<Value extends object> = Collection<RecordRow<Value>, string>;
120
+ export type RecordWriteInput<Value extends object> = Readonly<{
121
+ /**
122
+ * The collection whose row the write reads (an update or a delete sends
123
+ * its revision). Every other open Record Collection of the identity that
124
+ * shows the records of `target` shows the write too.
125
+ */
126
+ collection: RecordCollection<Value>;
127
+ target: RecordWriteTarget;
128
+ /**
129
+ * The write's identity: its TanStack DB transaction id and the key a resend
130
+ * carries. A write with the key of an earlier write whose answer stayed
131
+ * lost is that write sent again (the app's resubmit): it sends the earlier
132
+ * request as it was, whatever the row shows now.
133
+ */
134
+ idempotencyKey: IdempotencyKey;
135
+ id: RecordId;
136
+ }>;
137
+ export type RecordCreateInput<Value extends object> = RecordWriteInput<Value> & Readonly<{
138
+ value: Value;
139
+ }>;
140
+ export type RecordUpdateInput<Value extends object> = RecordWriteInput<Value> & Readonly<{
141
+ change: Partial<Value>;
142
+ }>;
143
+ export type RecordDeleteInput<Value extends object> = RecordWriteInput<Value>;
144
+ export interface RecordWritesValue {
145
+ /** Shows the new record at once and creates it in CI under the client's `id`. */
146
+ readonly create: <Value extends object>(input: RecordCreateInput<Value>) => Effect.Effect<RecordRow<Value>, RecordWriteError>;
147
+ /** Shows `change` at once and sends it with the revision of the row. */
148
+ readonly update: <Value extends object>(input: RecordUpdateInput<Value>) => Effect.Effect<RecordRow<Value>, RecordWriteError>;
149
+ /** Hides the record at once and deletes it in CI. */
150
+ readonly delete: <Value extends object>(input: RecordDeleteInput<Value>) => Effect.Effect<void, RecordWriteError>;
151
+ }
152
+ declare const RecordWrites_base: Context.ServiceClass<RecordWrites, "@collective-intelligence/records/RecordWrites", RecordWritesValue>;
153
+ /**
154
+ * Writes CI records as TanStack DB transactions on Record Collections, in
155
+ * order per record, with the confirmed row in place before the write settles.
156
+ * A refused or conflicting write fails its transaction with its typed error,
157
+ * so TanStack DB rolls back only that write.
158
+ */
159
+ export declare class RecordWrites extends RecordWrites_base {
160
+ }
161
+ /** The CI identity that owns a set of Record Collections: one user of one Organization in one application. */
162
+ export type RecordIdentity = Readonly<{
163
+ applicationId: string;
164
+ organizationId: string;
165
+ userId: string;
166
+ }>;
167
+ declare const RecordIdentityKey: Schema.brand<Schema.String, "RecordIdentityKey">;
168
+ export type RecordIdentityKey = typeof RecordIdentityKey.Type;
169
+ /** Runs Effects with the Record Collections and record writes of one identity. */
170
+ export type RecordRuntime = Pick<ManagedRuntime.ManagedRuntime<RecordCollections | RecordWrites, never>, "runFork" | "runPromise" | "runSync">;
171
+ /**
172
+ * XState actor logic that runs one `RecordWrites` action on the runtime of
173
+ * the actor input. The actor's output is the action's value, such as the
174
+ * confirmed row of an update; a typed write error fails the actor. A stop of
175
+ * the actor interrupts the write, so its send stops and TanStack DB rolls
176
+ * back its optimistic change. The machine keeps what it needs of the output,
177
+ * such as the record's id: the rows stay in their Record Collection.
178
+ */
179
+ export declare const fromTransaction: <A, E, R, I extends Readonly<{
180
+ runtime: EffectRunner<R | RecordWrites>;
181
+ }>>(write: (writes: RecordWritesValue, input: I) => Effect.Effect<A, E, R>) => PromiseActorLogic<A, I>;
182
+ /** The event that a `fromLiveQuery` actor sends its parent with each result of its query. */
183
+ export type LiveQueryRows<T> = Readonly<{
184
+ type: "records.rows";
185
+ rows: readonly T[];
186
+ }>;
187
+ /** The event that a `fromLiveQuery` actor sends its parent when its query fails. */
188
+ export type LiveQueryFailed = Readonly<{
189
+ type: "records.failed";
190
+ error: unknown;
191
+ }>;
192
+ /** What `fromLiveQuery` reads: a Record Collection or a live query collection over them. */
193
+ export type LiveRows<T> = Readonly<{
194
+ readonly toArray: readonly T[];
195
+ toArrayWhenReady: () => Promise<readonly T[]>;
196
+ subscribeChanges: (onChange: () => void) => Readonly<{
197
+ unsubscribe: () => void;
198
+ }>;
199
+ }>;
200
+ /**
201
+ * XState actor logic that sends its parent each result of a live query: the
202
+ * rows once the collection is ready, then the rows after each change. `query`
203
+ * runs on the runtime of the actor input, in a `fromEffect` actor, and gives
204
+ * the collection, such as a Record Collection from `RecordCollections` or a
205
+ * live query collection over them. A failure of `query` or of the first load
206
+ * sends `records.failed`. A stop of the actor ends the subscription.
207
+ */
208
+ export declare const fromLiveQuery: <T, E, R, I extends Readonly<{
209
+ runtime: EffectRunner<R>;
210
+ }>>(query: (input: I) => Effect.Effect<LiveRows<T>, E, R>) => CallbackActorLogic<LiveQueryRows<T> | LiveQueryFailed, I>;
211
+ /** The TanStack clients of one server request. */
212
+ export type RequestClients = Readonly<{
213
+ /** Holds the rows of the request's Record Collections; its `queryClient` dependency is the one below. */
214
+ dbClient: DbClient;
215
+ /** Holds the fetched rows of the request's Query Record Collections. */
216
+ queryClient: QueryClient;
217
+ }>;
218
+ declare const getRequestClients: () => RequestClients;
219
+ /** What the server read for one Realtime Record Collection. */
220
+ export type RealtimeRecordRead = Readonly<{
221
+ records: readonly UndecodedRecord[];
222
+ /**
223
+ * The `position` of the read. The browser stream of the topic starts there.
224
+ * Without one, it replays from the page's age.
225
+ */
226
+ position: string | undefined;
227
+ }>;
228
+ /** One Realtime Record Collection to seed: its topic, its value schema and its read. */
229
+ export type RealtimeRecordSeedOptions<Value extends object, E = never, R = never> = Readonly<{
230
+ topic: RecordTopic;
231
+ schema: RecordValueSchema<Value>;
232
+ load: Effect.Effect<RealtimeRecordRead, E, R>;
233
+ }>;
234
+ /**
235
+ * The Record Collections that one server render seeds. Each option names a
236
+ * collection as the browser opens it, so the seed hydrates that collection.
237
+ */
238
+ export type RecordSeedSources<E, R> = Readonly<{
239
+ /**
240
+ * The CI identity of the request's session: the application, Organization
241
+ * and user that the browser's entity source reports. The seed then keys its
242
+ * Query Record Collections as that identity's browser collections do, and
243
+ * hydrates only that identity's Record Collections. Leave it out where the
244
+ * provider has no identities (Studio).
245
+ */
246
+ identity?: RecordIdentity;
247
+ query?: readonly QueryRecordCollectionOptions<object, E, R>[];
248
+ realtime?: readonly RealtimeRecordSeedOptions<object, E, R>[];
249
+ }>;
250
+ /** The loads of one `seedRecords` call. */
251
+ export type RecordSeedLoad<Sources extends RecordSeedSources<unknown, unknown>> = NonNullable<Sources["query"]>[number]["load"] | NonNullable<Sources["realtime"]>[number]["load"];
252
+ /**
253
+ * The two payloads of a server seed. `query` holds the fetched rows of the
254
+ * Query Record Collections, `db` the rows of every seeded Record Collection,
255
+ * the live query snapshots of the first render and each Realtime Record
256
+ * Collection's position in its sync metadata.
257
+ */
258
+ export type RecordSeed = Readonly<{
259
+ query: DehydratedState;
260
+ db: DehydratedDbState;
261
+ /** The CI identity the seed was made for; only its Record Collections take it. */
262
+ identity?: RecordIdentityKey;
263
+ }>;
264
+ declare function seedRecords<const Sources extends RecordSeedSources<unknown, unknown>>(sources: Sources): Effect.Effect<RecordSeed, Effect.Error<RecordSeedLoad<Sources>> | RecordSyncFailed, Effect.Services<RecordSeedLoad<Sources>>>;
265
+ export type RecordSeedBoundaryProps = Readonly<{
266
+ /** What `seedRecords` returned in the server render. */
267
+ seed: RecordSeed;
268
+ children?: ReactNode;
269
+ }>;
270
+ /**
271
+ * Hydrates a server seed into the browser's QueryClient and the DbClient of
272
+ * the SDK provider's identity, so the seeded rows are in the first HTML. The
273
+ * Query boundary is outside: the QueryClient holds the fetched rows before
274
+ * the DbClient applies its seed, so a Query Record Collection starts from
275
+ * them. Render it inside the SDK provider. While no identity is signed in,
276
+ * the seed waits and hydrates at the sign-in. A seed made for another CI
277
+ * identity than the provider's never hydrates, so its rows never show.
278
+ */
279
+ export declare const RecordSeedBoundary: ({ children, seed }: RecordSeedBoundaryProps) => import("react").JSX.Element;
280
+ /** A Record Collection kept fresh by `queryCollectionOptions` on the app's shared QueryClient. */
281
+ export type QueryRecordCollection<T extends object> = Collection<T, string>;
282
+ export type QueryRecordCollectionOptions<Value extends object, E = never, R = never> = Readonly<{
283
+ /** The key of the rows on the app's shared QueryClient. */
284
+ queryKey: QueryKey;
285
+ schema: RecordValueSchema<Value>;
286
+ /** Reads every record of the query, as CI holds it. */
287
+ load: Effect.Effect<readonly UndecodedRecord[], E, R>;
288
+ /**
289
+ * The write target of the query's records, if they have one: a record
290
+ * write of that target then shows in the rows this collection holds.
291
+ */
292
+ target?: RecordWriteTarget;
293
+ }>;
294
+ /**
295
+ * The record layer of the signed-in CI identity: a runtime with
296
+ * `RecordCollections` and `RecordWrites`. Undefined while no identity is
297
+ * signed in. A user switch or a sign-out closes the old identity's Record
298
+ * Collections and rolls back its pending writes.
299
+ */
300
+ export declare const useRecordRuntime: () => RecordRuntime | undefined;
301
+ /** An entity contract of any record type: the write target names one. */
302
+ export type EntityContract = ResourceDefinition<unknown, unknown, unknown>;
303
+ /** The write target of one entity contract: the same object for each call. */
304
+ export declare const entityWriteTarget: (contract: EntityContract) => RecordWriteTarget;
305
+ /**
306
+ * The Realtime Topic of a Realtime Record Collection whose records one entity
307
+ * contract reads: the change source reads each hinted record through the
308
+ * entity client of `contract`. Pass the returned topic to
309
+ * `RecordCollections.realtime`.
310
+ */
311
+ export declare const entityTopic: (contract: EntityContract, topic: RecordTopic) => RecordTopic;
312
+ /** Server only: the QueryClient and DbClient of the current request. */
313
+ declare const getRequestClients$1: typeof getRequestClients;
314
+ /** Server only: fetches, renders and dehydrates the seeded Record Collections. */
315
+ declare const seedRecords$1: typeof seedRecords;
316
+
317
+ export {
318
+ getRequestClients$1 as getRequestClients,
319
+ seedRecords$1 as seedRecords,
320
+ };
321
+
322
+ export {};
@@ -0,0 +1,2 @@
1
+ "use client";
2
+ import{RecordWriteRefused2,RecordWriteConflict2,RecordWriteOutcomeUnknown2,RecordSyncFailed2,RecordId2,IdempotencyKey2,RecordWrites2,RecordCollections2}from"./index-0k92txne.js";import{RecordSeedBoundary2,entityWriteTarget2,entityTopic2,useRecordRuntime2}from"./index-7r4n344n.js";import"./index-v7pbmwry.js";import{fromEffect}from"@collective-intelligence/effect-xstate/actors";import*as Effect from"effect/Effect";import{createActor,fromCallback}from"xstate";var fromTransaction=(write)=>fromEffect((input)=>Effect.flatMap(Effect.service(RecordWrites2),(writes)=>write(writes,input)));var fromLiveQuery=(query)=>fromCallback(({input,sendBack})=>{const send=(rows)=>{sendBack({rows,type:"records.rows"})};const follow=fromEffect((actorInput)=>Effect.gen(function*followRows(){const rows=yield*query(actorInput);send(yield*Effect.promise(async()=>await rows.toArrayWhenReady()));yield*Effect.acquireRelease(Effect.sync(()=>rows.subscribeChanges(()=>{send(rows.toArray)})),(subscription)=>Effect.sync(()=>{subscription.unsubscribe()}));return yield*Effect.never}).pipe(Effect.scoped));const actor=createActor(follow,{input});actor.subscribe({error:(error)=>{sendBack({error,type:"records.failed"})}});actor.start();return()=>{actor.stop()}});export{IdempotencyKey2 as IdempotencyKey,RecordCollections2 as RecordCollections,RecordId2 as RecordId,RecordSeedBoundary2 as RecordSeedBoundary,RecordSyncFailed2 as RecordSyncFailed,RecordWriteConflict2 as RecordWriteConflict,RecordWriteOutcomeUnknown2 as RecordWriteOutcomeUnknown,RecordWriteRefused2 as RecordWriteRefused,RecordWrites2 as RecordWrites,entityTopic2 as entityTopic,entityWriteTarget2 as entityWriteTarget,fromLiveQuery,fromTransaction,useRecordRuntime2 as useRecordRuntime};
@@ -0,0 +1,155 @@
1
+ // Generated by dts-bundle-generator v9.5.1
2
+
3
+ import { DbClient, DehydratedDbState } from '@tanstack/db';
4
+ import { DehydratedState, QueryClient } from '@tanstack/query-core';
5
+ import { QueryKey } from '@tanstack/react-query';
6
+ import * as Cause from 'effect/Cause';
7
+ import * as Context from 'effect/Context';
8
+ import * as Duration from 'effect/Duration';
9
+ import * as Effect from 'effect/Effect';
10
+ import * as Exit from 'effect/Exit';
11
+ import * as Layer from 'effect/Layer';
12
+ import * as Option$1 from 'effect/Option';
13
+ import * as Schema from 'effect/Schema';
14
+ import { ReactNode } from 'react';
15
+
16
+ declare const RecordSyncFailed_base: Schema.Class<RecordSyncFailed, Schema.TaggedStruct<"RecordSyncFailed", {
17
+ readonly cause: Schema.optional<Schema.Defect>;
18
+ readonly message: Schema.String;
19
+ readonly retrying: Schema.Boolean;
20
+ }>, Cause.YieldableError>;
21
+ /**
22
+ * A Record Collection could not load or follow its records. `retrying` tells
23
+ * that its sync keeps trying, so the rows and the status stay.
24
+ */
25
+ export declare class RecordSyncFailed extends RecordSyncFailed_base {
26
+ }
27
+ /** The schema of a record value; it decodes with no service. */
28
+ export type RecordValueSchema<Value extends object> = Schema.Codec<Value, unknown>;
29
+ /** One record as CI sends it, before decoding. */
30
+ export type UndecodedRecord = Readonly<{
31
+ id: string;
32
+ revision: string | null;
33
+ value: unknown;
34
+ }>;
35
+ /** The records of one entity schema, named by FQN or id, optionally filtered. */
36
+ export type RecordTopic = Readonly<{
37
+ schema: string;
38
+ filter?: Readonly<{
39
+ field: string;
40
+ eq: string | number | boolean | null;
41
+ }>;
42
+ }>;
43
+ /**
44
+ * Where a write goes. The SDK adapter that makes the target knows what
45
+ * `key` names; the record layer only reads `key`, which is stable for one
46
+ * target.
47
+ */
48
+ export type RecordWriteTarget = Readonly<{
49
+ key: string;
50
+ }>;
51
+ /** The CI identity that owns a set of Record Collections: one user of one Organization in one application. */
52
+ export type RecordIdentity = Readonly<{
53
+ applicationId: string;
54
+ organizationId: string;
55
+ userId: string;
56
+ }>;
57
+ declare const RecordIdentityKey: Schema.brand<Schema.String, "RecordIdentityKey">;
58
+ export type RecordIdentityKey = typeof RecordIdentityKey.Type;
59
+ /** The TanStack clients of one server request. */
60
+ export type RequestClients = Readonly<{
61
+ /** Holds the rows of the request's Record Collections; its `queryClient` dependency is the one below. */
62
+ dbClient: DbClient;
63
+ /** Holds the fetched rows of the request's Query Record Collections. */
64
+ queryClient: QueryClient;
65
+ }>;
66
+ /**
67
+ * The QueryClient and the `DbClient({ queryClient })` of the current server
68
+ * request: the same pair in one request, a new pair in each other request.
69
+ * Call it only in a React Server Component; React `cache()` scopes it to the
70
+ * request.
71
+ */
72
+ export declare const getRequestClients: () => RequestClients;
73
+ /** What the server read for one Realtime Record Collection. */
74
+ export type RealtimeRecordRead = Readonly<{
75
+ records: readonly UndecodedRecord[];
76
+ /**
77
+ * The `position` of the read. The browser stream of the topic starts there.
78
+ * Without one, it replays from the page's age.
79
+ */
80
+ position: string | undefined;
81
+ }>;
82
+ /** One Realtime Record Collection to seed: its topic, its value schema and its read. */
83
+ export type RealtimeRecordSeedOptions<Value extends object, E = never, R = never> = Readonly<{
84
+ topic: RecordTopic;
85
+ schema: RecordValueSchema<Value>;
86
+ load: Effect.Effect<RealtimeRecordRead, E, R>;
87
+ }>;
88
+ /**
89
+ * The Record Collections that one server render seeds. Each option names a
90
+ * collection as the browser opens it, so the seed hydrates that collection.
91
+ */
92
+ export type RecordSeedSources<E, R> = Readonly<{
93
+ /**
94
+ * The CI identity of the request's session: the application, Organization
95
+ * and user that the browser's entity source reports. The seed then keys its
96
+ * Query Record Collections as that identity's browser collections do, and
97
+ * hydrates only that identity's Record Collections. Leave it out where the
98
+ * provider has no identities (Studio).
99
+ */
100
+ identity?: RecordIdentity;
101
+ query?: readonly QueryRecordCollectionOptions<object, E, R>[];
102
+ realtime?: readonly RealtimeRecordSeedOptions<object, E, R>[];
103
+ }>;
104
+ /** The loads of one `seedRecords` call. */
105
+ export type RecordSeedLoad<Sources extends RecordSeedSources<unknown, unknown>> = NonNullable<Sources["query"]>[number]["load"] | NonNullable<Sources["realtime"]>[number]["load"];
106
+ /**
107
+ * The two payloads of a server seed. `query` holds the fetched rows of the
108
+ * Query Record Collections, `db` the rows of every seeded Record Collection,
109
+ * the live query snapshots of the first render and each Realtime Record
110
+ * Collection's position in its sync metadata.
111
+ */
112
+ export type RecordSeed = Readonly<{
113
+ query: DehydratedState;
114
+ db: DehydratedDbState;
115
+ /** The CI identity the seed was made for; only its Record Collections take it. */
116
+ identity?: RecordIdentityKey;
117
+ }>;
118
+ /**
119
+ * Fetches each Query Record Collection once into the request QueryClient
120
+ * and reads each Realtime Record Collection, renders their rows on the
121
+ * request DbClient and dehydrates both clients. A Realtime Record Collection
122
+ * is in the DB payload only, with its read's position in its sync metadata.
123
+ * Each load runs with the context of this call. Render the result in
124
+ * `<RecordSeedBoundary>`.
125
+ */
126
+ export declare function seedRecords<const Sources extends RecordSeedSources<unknown, unknown>>(sources: Sources): Effect.Effect<RecordSeed, Effect.Error<RecordSeedLoad<Sources>> | RecordSyncFailed, Effect.Services<RecordSeedLoad<Sources>>>;
127
+ export type RecordSeedBoundaryProps = Readonly<{
128
+ /** What `seedRecords` returned in the server render. */
129
+ seed: RecordSeed;
130
+ children?: ReactNode;
131
+ }>;
132
+ /**
133
+ * Hydrates a server seed into the browser's QueryClient and the DbClient of
134
+ * the SDK provider's identity, so the seeded rows are in the first HTML. The
135
+ * Query boundary is outside: the QueryClient holds the fetched rows before
136
+ * the DbClient applies its seed, so a Query Record Collection starts from
137
+ * them. Render it inside the SDK provider. While no identity is signed in,
138
+ * the seed waits and hydrates at the sign-in. A seed made for another CI
139
+ * identity than the provider's never hydrates, so its rows never show.
140
+ */
141
+ export declare const RecordSeedBoundary: ({ children, seed }: RecordSeedBoundaryProps) => import("react").JSX.Element;
142
+ export type QueryRecordCollectionOptions<Value extends object, E = never, R = never> = Readonly<{
143
+ /** The key of the rows on the app's shared QueryClient. */
144
+ queryKey: QueryKey;
145
+ schema: RecordValueSchema<Value>;
146
+ /** Reads every record of the query, as CI holds it. */
147
+ load: Effect.Effect<readonly UndecodedRecord[], E, R>;
148
+ /**
149
+ * The write target of the query's records, if they have one: a record
150
+ * write of that target then shows in the rows this collection holds.
151
+ */
152
+ target?: RecordWriteTarget;
153
+ }>;
154
+
155
+ export {};
@@ -0,0 +1 @@
1
+ import{RecordSyncFailed2,recordIdentityKey,recordQueryScope,realtimeCollectionId,recordRowSchema,RealtimeChangeSource,RealtimeSyncMeta,make}from"./index-0k92txne.js";import{collectionOptions,DbClient}from"@tanstack/db";import{dehydrate,QueryClient}from"@tanstack/query-core";import*as Effect from"effect/Effect";import*as Schema from"effect/Schema";import*as Scope from"effect/Scope";import*as Stream from"effect/Stream";import{cache}from"react";var serverChangeSource=RealtimeChangeSource.of({changes:()=>Stream.die("A server seed follows no Realtime Topic"),read:()=>Effect.die("A server seed reads no record by id"),load:()=>Effect.die("A server seed reloads no Realtime Topic")});var getRequestClients=cache(()=>{const queryClient=new QueryClient;return{dbClient:new DbClient({queryClient}),queryClient}});var decodeRead=(schema,id)=>{const decode=Schema.decodeUnknownEffect(Schema.Struct({meta:Schema.UndefinedOr(RealtimeSyncMeta),rows:Schema.Array(recordRowSchema(schema))}));return(read)=>decode({meta:read.position===undefined?undefined:{position:read.position},rows:read.records}).pipe(Effect.mapError((cause)=>new RecordSyncFailed2({cause,message:`The read of the Record Collection ${id} does not decode: ${cause.message}`,retrying:false})))};var preload=(dbClient,collection)=>Effect.tryPromise({catch:(cause)=>new RecordSyncFailed2({cause,message:`The Record Collection ${collection.id} could not be seeded`,retrying:false}),try:async()=>{await dbClient.preloadLiveQuery({query:(q)=>q.from({record:collection})})}});function seedRecords(sources){return Effect.gen(function*(){const{dbClient,queryClient}=getRequestClients();const identity=sources.identity===undefined?undefined:recordIdentityKey(sources.identity);const collections=yield*make({dbClient,identity,queryClient}).pipe(Effect.provideService(RealtimeChangeSource,serverChangeSource));const queryKeyOf=(options)=>identity===undefined?options.queryKey:[...recordQueryScope(identity),...options.queryKey];const seedQuery=Effect.fnUntraced(function*(options){const collection=yield*collections.query(options);const preloaded=yield*Effect.exit(preload(dbClient,collection));const state=queryClient.getQueryState(queryKeyOf(options));if(state?.status==="error"&&state.error!==null){return yield*Effect.fail(state.error)}return yield*preloaded});const seedRealtime=Effect.fnUntraced(function*(options){const id=realtimeCollectionId(options.topic);const{meta,rows}=yield*options.load.pipe(Effect.flatMap(decodeRead(options.schema,id)));const collection=dbClient.collection(collectionOptions({getKey:(row)=>row.id,id,schema:Schema.toStandardSchemaV1(Schema.toType(recordRowSchema(options.schema))),sync:{exportSyncMeta:()=>meta,rowUpdateMode:"full",sync:({begin,commit,markReady,write})=>{begin();for(const value of rows){write({type:"insert",value})}commit();markReady()}}}));yield*preload(dbClient,collection)});yield*Effect.all([Effect.forEach(sources.query??[],seedQuery,{concurrency:"unbounded",discard:true}),Effect.forEach(sources.realtime??[],seedRealtime,{concurrency:"unbounded",discard:true})],{concurrency:"unbounded",discard:true});const seed={db:dbClient.dehydrate(),query:dehydrate(queryClient)};return identity===undefined?seed:{...seed,identity}}).pipe(Effect.provideServiceEffect(Scope.Scope,Scope.make()),Effect.withSpan("seedRecords"))}import{RecordSeedBoundary}from"./records.js";export{RecordSeedBoundary,RecordSyncFailed2 as RecordSyncFailed,getRequestClients,seedRecords};
@@ -3,9 +3,14 @@
3
3
  import { ClientFetch, FederatedAuthErrorCode, FederatedAuthState, FederatedSessionIdentity, RealtimeChange } from '@collective-intelligence/external-apps-client-sdk';
4
4
  import { EntityClient, EntityCreateInput, EntityDeleteInput, EntityListQuery, EntityMemberValue, EntityPage, EntityUpdateInput, EntityUploadInput, EntityUploadSlot, IdempotencyKey, PortableResourceSchema, ResourceCapabilities, ResourceClient, ResourceCreateInput, ResourceCursor, ResourceDefinition, ResourceError, ResourceErrorCode, ResourceFilter, ResourceId, ResourceIdentityField, ResourceJsonValue, ResourceLifecycleInput, ResourceListQuery, ResourceListResult, ResourceMutationInput, ResourcePaginationMode, ResourceRecord, ResourceRecordAccess, ResourceRecordId, ResourceRequestOptions, ResourceResult, ResourceRevision, ResourceSort } from '@collective-intelligence/external-apps-client-sdk/resources';
5
5
  import { ResourceField, ResourceFieldControlProps, ResourceObject, ResourceValue } from '@collective-intelligence/ui-react/resources';
6
+ import * as Cause from 'effect/Cause';
6
7
  import * as Context from 'effect/Context';
8
+ import * as Duration from 'effect/Duration';
7
9
  import * as Effect from 'effect/Effect';
10
+ import * as Exit from 'effect/Exit';
8
11
  import * as Layer from 'effect/Layer';
12
+ import * as Option$1 from 'effect/Option';
13
+ import * as Schema from 'effect/Schema';
9
14
  import { ComponentType, ReactNode } from 'react';
10
15
 
11
16
  export declare class ResourceQueryError extends Error {
@@ -240,7 +245,9 @@ export declare const useEntityRecord: <Value, Create, Patch>(contract: ResourceD
240
245
  refresh: () => Promise<void>;
241
246
  refreshing: boolean;
242
247
  };
243
- export declare const useEntityUpdate: <Value, Create, Patch>(contract: ResourceDefinition<Value, Create, Patch>, target: Readonly<{
248
+ export declare const useEntityUpdate: <Value, Create, Patch>(contract: ResourceDefinition<Value, Create, Patch>,
249
+ /** `optimistic` is kept for compatibility: every write shows at once in its Record Collection. */
250
+ target: Readonly<{
244
251
  id: string;
245
252
  optimistic?: boolean;
246
253
  }>) => {
@@ -315,10 +322,7 @@ export declare const useEntityCreate: <Value, Create, Patch>(contract: ResourceD
315
322
  value: Value;
316
323
  }>>>;
317
324
  status: "pending" | "success" | "idle" | "conflict" | "rejected" | "uncertain";
318
- submit: (input: Omit<Readonly<{
319
- idempotencyKey: import("@collective-intelligence/external-apps-client-sdk").IdempotencyKey;
320
- value: Create;
321
- }>, "idempotencyKey">) => Promise<ResourceResult<Readonly<{
325
+ submit: (input: Omit<EntityCreateInput<Create>, "idempotencyKey">) => Promise<ResourceResult<Readonly<{
322
326
  access?: Readonly<{
323
327
  writableFields: readonly string[];
324
328
  write: boolean;
@@ -330,12 +334,11 @@ export declare const useEntityCreate: <Value, Create, Patch>(contract: ResourceD
330
334
  truncated?: readonly string[];
331
335
  value: Value;
332
336
  }>>>;
333
- submitted: Readonly<{
334
- idempotencyKey: import("@collective-intelligence/external-apps-client-sdk").IdempotencyKey;
335
- value: Create;
336
- }> | undefined;
337
+ submitted: EntityCreateInput<Create> | undefined;
337
338
  };
338
- export declare const useEntityDelete: <Value, Create, Patch>(contract: ResourceDefinition<Value, Create, Patch>, target: Readonly<{
339
+ export declare const useEntityDelete: <Value, Create, Patch>(contract: ResourceDefinition<Value, Create, Patch>,
340
+ /** `optimistic` is kept for compatibility: every write shows at once in its Record Collection. */
341
+ target: Readonly<{
339
342
  id: string;
340
343
  optimistic?: boolean;
341
344
  }>) => {
package/dist/resources.js CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{resourceKeys,ResourceQueryError2,unwrapResourceResult2,createResourceListQueryOptions,mapResourceAuthState2,hasResourceCapability2,clearProtectedResourceQueries,useEntityRuntime,createDelegatedEntitySource2,defineEntity2,useEntityUpdate2,useEntityCreate2,useEntityDelete2,useEntityList2,useEntityRecord2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-5t792h25.js";import{useMutation,useQuery,useQueryClient as useQueryClient2}from"@tanstack/react-query";import{mutationOptions}from"@tanstack/react-query";var invalidateResource=async(options)=>{await options.queryClient.invalidateQueries({queryKey:resourceKeys.resource(options.organizationId,options.client.definition.id,options.client.definition.version)})};var createResourceMutationOptions=(options)=>mutationOptions({mutationFn:async(input)=>{let result;switch(options.operation){case"hard_delete":{unwrapResourceResult2(await options.client.hardDelete(input));break}case"restore":{result=unwrapResourceResult2(await options.client.restore(input));break}case"soft_delete":{result=unwrapResourceResult2(await options.client.softDelete(input));break}default:{throw new TypeError(`Unknown resource operation: ${String(options.operation)}`)}}return result},mutationKey:[...resourceKeys.resource(options.organizationId,options.client.definition.id,options.client.definition.version),"mutations",options.operation],onSuccess:async()=>{await invalidateResource(options)}});import{useQueryClient}from"@tanstack/react-query";import{createContext,useContext,useEffect,useMemo,useRef}from"react";import{jsx}from"react/jsx-runtime";var useResourceQueryCleanup=(queryClient,authStatus,organizationId)=>{const previousOrganizationId=useRef(null);const input=useMemo(()=>({authStatus,organizationId}),[authStatus,organizationId]);useEffect(()=>{const previous=previousOrganizationId.current;previousOrganizationId.current=input.organizationId;if(input.authStatus!=="authenticated"){clearProtectedResourceQueries(queryClient);return}if(previous!==null&&previous!==input.organizationId){clearProtectedResourceQueries(queryClient,previous)}},[input,queryClient])};var ResourceContext=createContext(null);var ResourceProvider=({authState,capabilities,children,organizationId})=>{const queryClient=useQueryClient();useResourceQueryCleanup(queryClient,authState.status,organizationId);const value=useMemo(()=>({authState,capabilities,organizationId}),[authState,capabilities,organizationId]);return jsx(ResourceContext.Provider,{value,children})};var useResourceContext=()=>{const value=useContext(ResourceContext);if(value===null){throw new Error("ResourceProvider must wrap resource bindings")}return value};var authStateForError=(error,fallback)=>error instanceof ResourceQueryError2?mapResourceAuthState2({correlationId:error.correlationId,error:error.resourceError,ok:false}):fallback;var useResourceList=(client,query)=>{const context=useResourceContext();const result=useQuery({...createResourceListQueryOptions({client,organizationId:context.organizationId,query}),enabled:context.authState.status==="authenticated"});return{...result,authState:authStateForError(result.error,context.authState)}};var useResourceLifecycleMutation=(client,operation)=>{const{capabilities,organizationId}=useResourceContext();const queryClient=useQueryClient2();const mutation=useMutation(createResourceMutationOptions({client,operation,organizationId,queryClient}));let capability;if(operation==="hard_delete"){capability="hardDelete"}else if(operation==="soft_delete"){capability="softDelete"}else{capability=operation}return{...mutation,available:capabilities[capability]===true}};import{jsx as jsx2,jsxs,Fragment}from"react/jsx-runtime";var nextQuery=(query,result)=>{if(result.pagination==="cursor"){return result.nextCursor===undefined?undefined:{...query,pagination:{cursor:result.nextCursor,limit:query.pagination.mode==="cursor"?query.pagination.limit:25,mode:"cursor"}}}return result.page>=result.totalPages?undefined:{...query,pagination:{mode:"page",page:result.page+1,pageSize:result.pageSize}}};var previousQuery=(query,result)=>result.pagination==="page"&&result.page>1?{...query,pagination:{mode:"page",page:result.page-1,pageSize:result.pageSize}}:undefined;var DefaultStatus=({authState,error,pending})=>{let message=authState.status;if(authState.status==="authenticated"){message=pending?"Loading resources":error?.message??""}return jsx2("output",{"aria-live":"polite",children:message})};var ResourceList=({client,components,onQueryChange,query,renderItem})=>{const resourceQuery=useResourceList(client,query);const Status=components.Status??DefaultStatus;if(resourceQuery.authState.status!=="authenticated"||resourceQuery.isPending||resourceQuery.error!==null){return jsx2(Status,{authState:resourceQuery.authState,pending:resourceQuery.isPending,...resourceQuery.error===null?{}:{error:resourceQuery.error}})}const{List}=components;const{Pagination}=components;const result=resourceQuery.data;const next=nextQuery(query,result);const previous=previousQuery(query,result);return jsxs(Fragment,{children:[jsx2(List,{getItemKey:(item)=>item.id,items:result.items,renderItem}),Pagination===undefined?null:jsx2(Pagination,{hasNextPage:next!==undefined,hasPreviousPage:previous!==undefined,isPending:resourceQuery.isFetching,onNext:()=>{if(next!==undefined){onQueryChange?.(next)}},onPrevious:()=>{if(previous!==undefined){onQueryChange?.(previous)}},...result.pagination==="page"?{currentPage:result.page}:{}})]})};var ResourceCapabilityAction=({capability,children,components,unsupported="disable"})=>{const{capabilities}=useResourceContext();const supported=capabilities[capability]===true;if(!supported&&unsupported==="hide"){return null}const{Action}=components;return jsx2(Action,{disabled:!supported,children})};var ResourceFilter=({components,label="Search resources",onQueryChange,query})=>{const{Filter}=components;const{textSearch:_textSearch,...queryWithoutTextSearch}=query;return jsx2(Filter,{label,onChange:(value)=>{onQueryChange(value===""?queryWithoutTextSearch:{...query,textSearch:value})},value:query.textSearch??""})};var ResourcePagination=({components,isPending=false,onQueryChange,query,result})=>{const{Pagination}=components;const next=nextQuery(query,result);const previous=previousQuery(query,result);return jsx2(Pagination,{hasNextPage:next!==undefined,hasPreviousPage:previous!==undefined,isPending,onNext:()=>{if(next!==undefined){onQueryChange(next)}},onPrevious:()=>{if(previous!==undefined){onQueryChange(previous)}},...result.pagination==="page"?{currentPage:result.page}:{}})};var ResourceTable=({caption,client,columns,components,query})=>{const resourceQuery=useResourceList(client,query);const Status=components.Status??DefaultStatus;if(resourceQuery.authState.status!=="authenticated"||resourceQuery.isPending||resourceQuery.error!==null){return jsx2(Status,{authState:resourceQuery.authState,pending:resourceQuery.isPending,...resourceQuery.error===null?{}:{error:resourceQuery.error}})}const{Table}=components;return jsx2(Table,{caption,columns,getRowKey:(row)=>row.id,renderCell:(row,column)=>column.render(row),rows:resourceQuery.data.items})};var ResourceLifecycleAction=({children,client,components,input,operation,unsupported="disable"})=>{const mutation=useResourceLifecycleMutation(client,operation);if(!mutation.available&&unsupported==="hide"){return null}const{Action}=components;return jsx2(Action,{disabled:!mutation.available,onClick:()=>{mutation.mutate(input)},pending:mutation.isPending,children})};import{useQueryClient as useQueryClient3}from"@tanstack/react-query";import{useCallback}from"react";var useEntityChanges=(contract)=>{const runtime=useEntityRuntime();const queryClient=useQueryClient3();return useCallback((changes)=>{if(changes.length===0||!runtime.current()){return}const resourceKey=["ci-entities",...runtime.key,contract.id,contract.version];for(const change of changes){const recordKey=[...resourceKey,"record",change.id];const record=queryClient.getQueryData(recordKey);if(record?.revision!==change.revision){queryClient.invalidateQueries({exact:true,queryKey:recordKey})}}queryClient.invalidateQueries({queryKey:[...resourceKey,"list"]})},[contract.id,contract.version,queryClient,runtime])};export{EntityForm2 as EntityForm,EntityList2 as EntityList,EntityTable2 as EntityTable,ResourceCapabilityAction,ResourceFilter,ResourceLifecycleAction,ResourceList,ResourcePagination,ResourceProvider,ResourceQueryError2 as ResourceQueryError,ResourceTable,createDelegatedEntitySource2 as createDelegatedEntitySource,defineEntity2 as defineEntity,hasResourceCapability2 as hasResourceCapability,mapResourceAuthState2 as mapResourceAuthState,unwrapResourceResult2 as unwrapResourceResult,useEntityChanges,useEntityCreate2 as useEntityCreate,useEntityDelete2 as useEntityDelete,useEntityList2 as useEntityList,useEntityRecord2 as useEntityRecord,useEntityUpdate2 as useEntityUpdate,useEntityViewState2 as useEntityViewState,useMemoryEntityViewState2 as useMemoryEntityViewState};
2
+ import{resourceKeys,ResourceQueryError2,unwrapResourceResult2,createResourceListQueryOptions,mapResourceAuthState2,hasResourceCapability2,clearProtectedResourceQueries,useEntityRuntime,createDelegatedEntitySource2}from"./index-7r4n344n.js";import"./index-0k92txne.js";import"./index-v7pbmwry.js";import{defineEntity2,useEntityUpdate2,useEntityCreate2,useEntityDelete2,useEntityList2,useEntityRecord2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-h4fpzytm.js";import{useMutation,useQuery,useQueryClient as useQueryClient2}from"@tanstack/react-query";import{mutationOptions}from"@tanstack/react-query";var invalidateResource=async(options)=>{await options.queryClient.invalidateQueries({queryKey:resourceKeys.resource(options.organizationId,options.client.definition.id,options.client.definition.version)})};var createResourceMutationOptions=(options)=>mutationOptions({mutationFn:async(input)=>{let result;switch(options.operation){case"hard_delete":{unwrapResourceResult2(await options.client.hardDelete(input));break}case"restore":{result=unwrapResourceResult2(await options.client.restore(input));break}case"soft_delete":{result=unwrapResourceResult2(await options.client.softDelete(input));break}default:{throw new TypeError(`Unknown resource operation: ${String(options.operation)}`)}}return result},mutationKey:[...resourceKeys.resource(options.organizationId,options.client.definition.id,options.client.definition.version),"mutations",options.operation],onSuccess:async()=>{await invalidateResource(options)}});import{useQueryClient}from"@tanstack/react-query";import{createContext,useContext,useEffect,useMemo,useRef}from"react";import{jsx}from"react/jsx-runtime";var useResourceQueryCleanup=(queryClient,authStatus,organizationId)=>{const previousOrganizationId=useRef(null);const input=useMemo(()=>({authStatus,organizationId}),[authStatus,organizationId]);useEffect(()=>{const previous=previousOrganizationId.current;previousOrganizationId.current=input.organizationId;if(input.authStatus!=="authenticated"){clearProtectedResourceQueries(queryClient);return}if(previous!==null&&previous!==input.organizationId){clearProtectedResourceQueries(queryClient,previous)}},[input,queryClient])};var ResourceContext=createContext(null);var ResourceProvider=({authState,capabilities,children,organizationId})=>{const queryClient=useQueryClient();useResourceQueryCleanup(queryClient,authState.status,organizationId);const value=useMemo(()=>({authState,capabilities,organizationId}),[authState,capabilities,organizationId]);return jsx(ResourceContext.Provider,{value,children})};var useResourceContext=()=>{const value=useContext(ResourceContext);if(value===null){throw new Error("ResourceProvider must wrap resource bindings")}return value};var authStateForError=(error,fallback)=>error instanceof ResourceQueryError2?mapResourceAuthState2({correlationId:error.correlationId,error:error.resourceError,ok:false}):fallback;var useResourceList=(client,query)=>{const context=useResourceContext();const result=useQuery({...createResourceListQueryOptions({client,organizationId:context.organizationId,query}),enabled:context.authState.status==="authenticated"});return{...result,authState:authStateForError(result.error,context.authState)}};var useResourceLifecycleMutation=(client,operation)=>{const{capabilities,organizationId}=useResourceContext();const queryClient=useQueryClient2();const mutation=useMutation(createResourceMutationOptions({client,operation,organizationId,queryClient}));let capability;if(operation==="hard_delete"){capability="hardDelete"}else if(operation==="soft_delete"){capability="softDelete"}else{capability=operation}return{...mutation,available:capabilities[capability]===true}};import{jsx as jsx2,jsxs,Fragment}from"react/jsx-runtime";var nextQuery=(query,result)=>{if(result.pagination==="cursor"){return result.nextCursor===undefined?undefined:{...query,pagination:{cursor:result.nextCursor,limit:query.pagination.mode==="cursor"?query.pagination.limit:25,mode:"cursor"}}}return result.page>=result.totalPages?undefined:{...query,pagination:{mode:"page",page:result.page+1,pageSize:result.pageSize}}};var previousQuery=(query,result)=>result.pagination==="page"&&result.page>1?{...query,pagination:{mode:"page",page:result.page-1,pageSize:result.pageSize}}:undefined;var DefaultStatus=({authState,error,pending})=>{let message=authState.status;if(authState.status==="authenticated"){message=pending?"Loading resources":error?.message??""}return jsx2("output",{"aria-live":"polite",children:message})};var ResourceList=({client,components,onQueryChange,query,renderItem})=>{const resourceQuery=useResourceList(client,query);const Status=components.Status??DefaultStatus;if(resourceQuery.authState.status!=="authenticated"||resourceQuery.isPending||resourceQuery.error!==null){return jsx2(Status,{authState:resourceQuery.authState,pending:resourceQuery.isPending,...resourceQuery.error===null?{}:{error:resourceQuery.error}})}const{List}=components;const{Pagination}=components;const result=resourceQuery.data;const next=nextQuery(query,result);const previous=previousQuery(query,result);return jsxs(Fragment,{children:[jsx2(List,{getItemKey:(item)=>item.id,items:result.items,renderItem}),Pagination===undefined?null:jsx2(Pagination,{hasNextPage:next!==undefined,hasPreviousPage:previous!==undefined,isPending:resourceQuery.isFetching,onNext:()=>{if(next!==undefined){onQueryChange?.(next)}},onPrevious:()=>{if(previous!==undefined){onQueryChange?.(previous)}},...result.pagination==="page"?{currentPage:result.page}:{}})]})};var ResourceCapabilityAction=({capability,children,components,unsupported="disable"})=>{const{capabilities}=useResourceContext();const supported=capabilities[capability]===true;if(!supported&&unsupported==="hide"){return null}const{Action}=components;return jsx2(Action,{disabled:!supported,children})};var ResourceFilter=({components,label="Search resources",onQueryChange,query})=>{const{Filter}=components;const{textSearch:_textSearch,...queryWithoutTextSearch}=query;return jsx2(Filter,{label,onChange:(value)=>{onQueryChange(value===""?queryWithoutTextSearch:{...query,textSearch:value})},value:query.textSearch??""})};var ResourcePagination=({components,isPending=false,onQueryChange,query,result})=>{const{Pagination}=components;const next=nextQuery(query,result);const previous=previousQuery(query,result);return jsx2(Pagination,{hasNextPage:next!==undefined,hasPreviousPage:previous!==undefined,isPending,onNext:()=>{if(next!==undefined){onQueryChange(next)}},onPrevious:()=>{if(previous!==undefined){onQueryChange(previous)}},...result.pagination==="page"?{currentPage:result.page}:{}})};var ResourceTable=({caption,client,columns,components,query})=>{const resourceQuery=useResourceList(client,query);const Status=components.Status??DefaultStatus;if(resourceQuery.authState.status!=="authenticated"||resourceQuery.isPending||resourceQuery.error!==null){return jsx2(Status,{authState:resourceQuery.authState,pending:resourceQuery.isPending,...resourceQuery.error===null?{}:{error:resourceQuery.error}})}const{Table}=components;return jsx2(Table,{caption,columns,getRowKey:(row)=>row.id,renderCell:(row,column)=>column.render(row),rows:resourceQuery.data.items})};var ResourceLifecycleAction=({children,client,components,input,operation,unsupported="disable"})=>{const mutation=useResourceLifecycleMutation(client,operation);if(!mutation.available&&unsupported==="hide"){return null}const{Action}=components;return jsx2(Action,{disabled:!mutation.available,onClick:()=>{mutation.mutate(input)},pending:mutation.isPending,children})};import{useQueryClient as useQueryClient3}from"@tanstack/react-query";import{useCallback}from"react";var useEntityChanges=(contract)=>{const runtime=useEntityRuntime();const queryClient=useQueryClient3();return useCallback((changes)=>{if(changes.length===0||!runtime.current()){return}const resourceKey=["ci-entities",...runtime.key,contract.id,contract.version];for(const change of changes){const recordKey=[...resourceKey,"record",change.id];const record=queryClient.getQueryData(recordKey);if(record?.revision!==change.revision){queryClient.invalidateQueries({exact:true,queryKey:recordKey})}}queryClient.invalidateQueries({queryKey:[...resourceKey,"list"]})},[contract.id,contract.version,queryClient,runtime])};export{EntityForm2 as EntityForm,EntityList2 as EntityList,EntityTable2 as EntityTable,ResourceCapabilityAction,ResourceFilter,ResourceLifecycleAction,ResourceList,ResourcePagination,ResourceProvider,ResourceQueryError2 as ResourceQueryError,ResourceTable,createDelegatedEntitySource2 as createDelegatedEntitySource,defineEntity2 as defineEntity,hasResourceCapability2 as hasResourceCapability,mapResourceAuthState2 as mapResourceAuthState,unwrapResourceResult2 as unwrapResourceResult,useEntityChanges,useEntityCreate2 as useEntityCreate,useEntityDelete2 as useEntityDelete,useEntityList2 as useEntityList,useEntityRecord2 as useEntityRecord,useEntityUpdate2 as useEntityUpdate,useEntityViewState2 as useEntityViewState,useMemoryEntityViewState2 as useMemoryEntityViewState};