@collective-intelligence/external-apps-client-sdk-react 0.13.5 → 0.13.7

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/dist/records.js CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{RecordWriteRefused2,RecordWriteConflict2,RecordWriteOutcomeUnknown2,RecordSyncFailed2,RecordOutboxUnavailable2,RecordIdentityMissing2,RecordIdentityMismatch2,RecordId2,IdempotencyKey2,markSeeded,OpenWait,RecordWrites2,RecordCollections2}from"./index-najx4ye0.js";import{entityWriteTarget2,entityTopic2,recordLayerOf,disposeRecordLayer2}from"./index-vw8r73tc.js";import{RecordScopeContext,recordIdentityOf,useEntityRuntime}from"./index-hmgpja4s.js";import"./index-xmbt130r.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()}});import{useOptionalDbClient}from"@tanstack/react-db";import{HydrationBoundary as QueryHydrationBoundary,useQueryClient}from"@tanstack/react-query";import{useContext,useState}from"react";import{jsx,jsxs}from"react/jsx-runtime";var Seed=({dbClient,seed})=>{const queryClient=useQueryClient();const[hydrated,setHydrated]=useState();if(dbClient!==undefined&&(hydrated?.client!==dbClient||hydrated.seed!==seed)){markSeeded(queryClient,seed.query);dbClient.hydrate(seed.db);setHydrated({client:dbClient,seed})}return null};var seedTarget=(scope,own,seed)=>{if(scope===undefined){return own}return scope.identity===seed.identity?scope.dbClient:undefined};var RecordSeedBoundary=({children,seed})=>{const dbClient=seedTarget(useContext(RecordScopeContext),useOptionalDbClient(),seed);return jsxs(QueryHydrationBoundary,{state:dbClient===undefined?undefined:seed.query,children:[jsx(Seed,{dbClient,seed}),children]})};import{useQueryClient as useQueryClient2}from"@tanstack/react-query";import{useLayoutEffect,useSyncExternalStore}from"react";var useRecordLayer=()=>{const layer=recordLayerOf(useQueryClient2());useSyncExternalStore(layer.subscribe,layer.version,layer.version);useLayoutEffect(()=>{layer.connect()},[layer]);return layer};var useRecordRuntime=()=>{const{recordScoped,state}=useEntityRuntime();const layer=useRecordLayer();const identity=recordScoped?recordIdentityOf(state):undefined;return identity===undefined?undefined:layer.records(identity).runtime};import*as Cause from"effect/Cause";import*as Duration from"effect/Duration";import*as Effect2 from"effect/Effect";import*as Exit from"effect/Exit";import{constVoid}from"effect/Function";import*as Schema from"effect/Schema";import{useCallback,useEffect,useMemo,useState as useState2,useSyncExternalStore as useSyncExternalStore2}from"react";var sameOpen=(a,b)=>a!==undefined&&a.runtime===b.runtime&&a.open===b.open&&a.attempt===b.attempt;var errorOf=(cause)=>{const failure=Cause.findErrorOption(cause);return failure._tag==="Some"?failure.value:new RecordSyncFailed2({cause:Cause.squash(cause),message:"The Record Collection could not open",retrying:false})};var loadFailed=(health)=>health.status==="error"&&!health.reloading;var isRecordSyncFailed=Schema.is(RecordSyncFailed2);var loadError=(health)=>{const cause=health.error?.cause;return isRecordSyncFailed(cause)?cause:new RecordSyncFailed2({cause,message:"The Record Collection could not load",retrying:false})};var healthHolds=(collection,holds)=>Effect2.callback((resume)=>{const check=()=>{if(holds(collection.health)){resume(Effect2.undefined)}};const stop=collection.on("health:change",check);check();return Effect2.sync(stop)});var loadSettled=(health)=>health.status==="ready"||loadFailed(health);var settled=(collection)=>Effect2.tryPromise(()=>collection.preload()).pipe(Effect2.ignore,Effect2.andThen(healthHolds(collection,loadSettled)));var withinOpenWait=(wait)=>wait.pipe(Effect2.timeoutOrElse({duration:OpenWait,orElse:()=>Effect2.fail(new RecordSyncFailed2({message:`The Record Collection did not open within ${Duration.format(OpenWait)}`,retrying:false}))}));var follow=(open,view)=>Effect2.gen(function*followOpen(){let opened;const first=yield*open.pipe(Effect2.tap((collection)=>Effect2.sync(()=>{opened=collection;view.opened(collection)})),Effect2.flatMap(settled),withinOpenWait,Effect2.exit);if(Exit.isFailure(first)){view.keepError(first.cause)}const collection=opened;if(collection===undefined){return}return yield*Effect2.forever(healthHolds(collection,(health)=>!health.reloading).pipe(Effect2.andThen(healthHolds(collection,(health)=>health.reloading)),Effect2.andThen(Effect2.sync(()=>{view.keepError()})),Effect2.andThen(withinOpenWait(healthHolds(collection,loadSettled))),Effect2.exit,Effect2.flatMap((exit)=>Exit.isFailure(exit)?Effect2.sync(()=>{view.keepError(exit.cause)}):Effect2.void)))});var useRecordCollection=(open)=>{const runtime=useRecordRuntime();const[attempt,setAttempt]=useState2(0);const[outcome,setOutcome]=useState2();const retry=useCallback(()=>{setAttempt((value)=>value+1)},[]);useEffect(()=>{if(runtime===undefined){return}const current={attempt,open,runtime};const keepError=(cause)=>{setOutcome((last)=>({...current,collection:sameOpen(last,current)?last?.collection:undefined,error:cause===undefined?undefined:errorOf(cause)}))};const following=follow(open,{keepError,opened:(collection)=>{setOutcome({...current,collection,error:undefined})}});const fiber=runtime.runFork(following);return()=>{fiber.interruptUnsafe()}},[runtime,open,attempt]);const latest=runtime!==undefined&&sameOpen(outcome,{attempt,open,runtime})?outcome:undefined;const collection=latest?.collection;const subscribe=useCallback((notify)=>collection===undefined?constVoid:collection.on("health:change",notify),[collection]);const readHealth=()=>collection?.health;const health=useSyncExternalStore2(subscribe,readHealth,readHealth);const failedLoad=useMemo(()=>health!==undefined&&loadFailed(health)?loadError(health):undefined,[health]);if(runtime===undefined){return{collection:undefined,error:undefined,retry,status:"idle"}}if(collection!==undefined&&health?.status==="ready"){return{collection,error:undefined,retry,status:"ready"}}const error=failedLoad??latest?.error;return error===undefined?{collection:undefined,error:undefined,retry,status:"opening"}:{collection:undefined,error,retry,status:"failed"}};export{IdempotencyKey2 as IdempotencyKey,RecordCollections2 as RecordCollections,RecordId2 as RecordId,RecordIdentityMismatch2 as RecordIdentityMismatch,RecordIdentityMissing2 as RecordIdentityMissing,RecordOutboxUnavailable2 as RecordOutboxUnavailable,RecordSeedBoundary,RecordSyncFailed2 as RecordSyncFailed,RecordWriteConflict2 as RecordWriteConflict,RecordWriteOutcomeUnknown2 as RecordWriteOutcomeUnknown,RecordWriteRefused2 as RecordWriteRefused,RecordWrites2 as RecordWrites,disposeRecordLayer2 as disposeRecordLayer,entityTopic2 as entityTopic,entityWriteTarget2 as entityWriteTarget,fromLiveQuery,fromTransaction,useRecordCollection,useRecordRuntime};
2
+ import{RecordWriteRefused2,RecordWriteConflict2,RecordWriteOutcomeUnknown2,RecordSyncFailed2,RecordOutboxUnavailable2,RecordIdentityMissing2,RecordIdentityMismatch2,reportRecordLayerError,RecordId2,IdempotencyKey2,markSeeded,RecordCollections2,OpenWait,IdentityWait}from"./index-3jq1t3k2.js";import{RecordWrites2,entityWriteTarget2,entityTopic2,recordLayerOf,disposeRecordLayer2}from"./index-v04mv78p.js";import{RecordScopeContext,RecordScopeProvider,useRecordScopeRuntime,recordIdentityOf,useEntityRuntime,useOptionalEntityRuntime}from"./index-1r3w51e7.js";import"./index-xmbt130r.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()}});import{useOptionalDbClient}from"@tanstack/react-db";import{HydrationBoundary as QueryHydrationBoundary,useQueryClient}from"@tanstack/react-query";import*as Duration from"effect/Duration";import{useContext,useEffect,useLayoutEffect,useRef,useState}from"react";import*as React from"react";var{use}=React;var useResolved=(value)=>{if(!("then"in(value??{}))){return value}if(use===undefined){throw new Error("Reading a seed promise needs React 19 (`use`)")}return use(value)};import{jsx,jsxs}from"react/jsx-runtime";var seededClients=new WeakSet;var useSeededRecordScope=()=>{const dbClient=useContext(RecordScopeContext)?.dbClient;return dbClient!==undefined&&seededClients.has(dbClient)};var useSeed=(seed)=>useResolved(seed);var Seed=({dbClient,seed})=>{const queryClient=useQueryClient();const[hydrated,setHydrated]=useState();if(dbClient!==undefined&&(hydrated?.client!==dbClient||hydrated.seed!==seed)){markSeeded(queryClient,seed.query);dbClient.hydrate(seed.db);seededClients.add(dbClient);setHydrated({client:dbClient,seed})}return null};var noSeed={provisional:undefined,target:undefined,waiting:false};var planSeed=(scope,own,seed,ended,provisional)=>{if(seed===null||ended){return noSeed}if(scope===undefined){return{...noSeed,target:own}}if(scope.identity!==undefined||seed.identity===undefined){return{...noSeed,target:scope.identity===seed.identity?scope.dbClient:undefined}}if(seed.owner===undefined||provisional===undefined){return{...noSeed,waiting:true}}if(provisional.ended(seed.owner)){return noSeed}const opened=provisional.open(seed.owner);return{provisional:opened,target:opened.dbClient,waiting:true}};var useSeedWait=(scope,provisional,seed,plan,ended,end)=>{const reported=useRef({});const owner=plan.provisional===undefined?undefined:seed?.owner;useLayoutEffect(()=>{if(owner!==undefined){provisional?.hold(owner)}},[owner,provisional]);const waitsHere=plan.waiting&&plan.provisional===undefined;useLayoutEffect(()=>{const timer=waitsHere&&seed!==null?setTimeout(()=>{end(seed)},Duration.toMillis(IdentityWait)):undefined;return()=>{clearTimeout(timer)}},[waitsHere,seed,end]);const identity=scope?.identity;useEffect(()=>{if(!ended||seed===null||reported.current.missing===seed){return}reported.current={...reported.current,missing:seed};reportRecordLayerError(new RecordIdentityMissing2({message:`A record seed waited ${Duration.format(IdentityWait)} for the provider's CI identity; its rows no longer show`}))},[ended,seed]);useEffect(()=>{if(seed?.identity===undefined||identity===undefined||identity===seed.identity||reported.current.mismatch===seed){return}reported.current={...reported.current,mismatch:seed};reportRecordLayerError(new RecordIdentityMismatch2({message:"A record seed was made for another CI identity than the provider's; its rows do not show"}))},[identity,seed])};var SeedBoundary=({children,provisional:scopes,seed:given})=>{const seed=useSeed(given);const scope=useContext(RecordScopeContext);const own=useOptionalDbClient();const[endedFor,setEndedFor]=useState();const[expiredFor,setExpiredFor]=useState();const ownerExpired=seed?.owner!==undefined&&scopes?.ended(seed.owner)===true;if(ownerExpired&&seed!==null&&expiredFor!==seed){setExpiredFor(seed)}const ended=seed!==null&&(endedFor===seed||expiredFor===seed||ownerExpired);const plan=planSeed(scope,own,seed,ended,scopes);useSeedWait(scope,scopes,seed,plan,endedFor===seed,setEndedFor);const{provisional}=plan;const content=jsxs(QueryHydrationBoundary,{state:plan.target===undefined?undefined:seed?.query,children:[seed===null?null:jsx(Seed,{dbClient:plan.target,seed}),children]});return scope===undefined?content:jsx(RecordScopeProvider,{dbClient:provisional?.dbClient??scope.dbClient,identity:provisional?.key??scope.identity,runtime:provisional?.runtime??scope.runtime,children:content})};import{useQueryClient as useQueryClient2}from"@tanstack/react-query";import{useLayoutEffect as useLayoutEffect2,useSyncExternalStore}from"react";var useRecordLayer=()=>{const layer=recordLayerOf(useQueryClient2());useSyncExternalStore(layer.subscribe,layer.version,layer.version);useLayoutEffect2(()=>{layer.connect()},[layer]);return layer};var useRecordRuntime=()=>{const{recordScoped,state}=useEntityRuntime();const layer=useRecordLayer();const provisional=useRecordScopeRuntime();const identity=recordScoped?recordIdentityOf(state):undefined;return provisional??(identity===undefined?undefined:layer.records(identity).runtime)};import{jsx as jsx2}from"react/jsx-runtime";var RecordSeedBoundary=({children,seed})=>{const entity=useOptionalEntityRuntime();const layer=useRecordLayer();const provisional=entity?.recordScoped===true?layer.provisionalFor(entity.state):undefined;return jsx2(SeedBoundary,{provisional,seed,children})};import*as Cause from"effect/Cause";import*as Duration2 from"effect/Duration";import*as Effect2 from"effect/Effect";import*as Exit from"effect/Exit";import{constVoid}from"effect/Function";import*as Schema from"effect/Schema";import{useCallback,useEffect as useEffect2,useMemo,useState as useState2,useSyncExternalStore as useSyncExternalStore2}from"react";var sameOpen=(a,b)=>a!==undefined&&a.runtime===b.runtime&&a.open===b.open&&a.attempt===b.attempt;var errorOf=(cause)=>{const failure=Cause.findErrorOption(cause);return failure._tag==="Some"?failure.value:new RecordSyncFailed2({cause:Cause.squash(cause),message:"The Record Collection could not open",retrying:false})};var loadFailed=(health)=>health.status==="error"&&!health.reloading;var isRecordSyncFailed=Schema.is(RecordSyncFailed2);var loadError=(health)=>{const cause=health.error?.cause;return isRecordSyncFailed(cause)?cause:new RecordSyncFailed2({cause,message:"The Record Collection could not load",retrying:false})};var healthHolds=(collection,holds)=>Effect2.callback((resume)=>{const check=()=>{if(holds(collection.health)){resume(Effect2.undefined)}};const stop=collection.on("health:change",check);check();return Effect2.sync(stop)});var loadSettled=(health)=>health.status==="ready"||loadFailed(health);var settled=(collection)=>Effect2.tryPromise(()=>collection.preload()).pipe(Effect2.ignore,Effect2.andThen(healthHolds(collection,loadSettled)));var withinOpenWait=(wait)=>wait.pipe(Effect2.timeoutOrElse({duration:OpenWait,orElse:()=>Effect2.fail(new RecordSyncFailed2({message:`The Record Collection did not open within ${Duration2.format(OpenWait)}`,retrying:false}))}));var holdsRows=(collection)=>collection.health.status==="ready"||(collection.size??0)>0&&!loadFailed(collection.health);var openAtOnce=(runtime,open)=>{const fiber=runtime.runFork(open);const exit=fiber.pollUnsafe();if(exit===undefined){fiber.interruptUnsafe();return}return Exit.isSuccess(exit)&&holdsRows(exit.value)?exit.value:undefined};var follow=(open,view)=>Effect2.gen(function*followOpen(){let opened;const first=yield*open.pipe(Effect2.tap((collection)=>Effect2.sync(()=>{opened=collection;view.opened(collection)})),Effect2.flatMap(settled),withinOpenWait,Effect2.exit);if(Exit.isFailure(first)){view.keepError(first.cause)}const collection=opened;if(collection===undefined){return}return yield*Effect2.forever(healthHolds(collection,(health)=>!health.reloading).pipe(Effect2.andThen(healthHolds(collection,(health)=>health.reloading)),Effect2.andThen(Effect2.sync(()=>{view.keepError()})),Effect2.andThen(withinOpenWait(healthHolds(collection,loadSettled))),Effect2.exit,Effect2.flatMap((exit)=>Exit.isFailure(exit)?Effect2.sync(()=>{view.keepError(exit.cause)}):Effect2.void)))});var useRecordCollection=(open)=>{const runtime=useRecordRuntime();const[attempt,setAttempt]=useState2(0);const[outcome,setOutcome]=useState2();const retry=useCallback(()=>{setAttempt((value)=>value+1)},[]);const seeded=useSeededRecordScope();const atOnce=useMemo(()=>runtime===undefined||!seeded?undefined:openAtOnce(runtime,open),[runtime,open,seeded]);useEffect2(()=>{if(runtime===undefined){return}const current={attempt,open,runtime};const keepError=(cause)=>{setOutcome((last)=>({...current,collection:sameOpen(last,current)?last?.collection:undefined,error:cause===undefined?undefined:errorOf(cause)}))};const following=follow(open,{keepError,opened:(collection)=>{setOutcome({...current,collection,error:undefined})}});const fiber=runtime.runFork(following);return()=>{fiber.interruptUnsafe()}},[runtime,open,attempt]);const latest=runtime!==undefined&&sameOpen(outcome,{attempt,open,runtime})?outcome:undefined;const collection=latest?.collection??(attempt===0?atOnce:undefined);const subscribe=useCallback((notify)=>collection===undefined?constVoid:collection.on("health:change",notify),[collection]);const readHealth=()=>collection?.health;const health=useSyncExternalStore2(subscribe,readHealth,readHealth);const failedLoad=useMemo(()=>health!==undefined&&loadFailed(health)?loadError(health):undefined,[health]);if(runtime===undefined){return{collection:undefined,error:undefined,retry,status:"idle"}}if(collection!==undefined&&(health?.status==="ready"||seeded&&holdsRows(collection))){return{collection,error:undefined,retry,status:"ready"}}const error=failedLoad??latest?.error;return error===undefined?{collection:undefined,error:undefined,retry,status:"opening"}:{collection:undefined,error,retry,status:"failed"}};export{IdempotencyKey2 as IdempotencyKey,RecordCollections2 as RecordCollections,RecordId2 as RecordId,RecordIdentityMismatch2 as RecordIdentityMismatch,RecordIdentityMissing2 as RecordIdentityMissing,RecordOutboxUnavailable2 as RecordOutboxUnavailable,RecordSeedBoundary,RecordSyncFailed2 as RecordSyncFailed,RecordWriteConflict2 as RecordWriteConflict,RecordWriteOutcomeUnknown2 as RecordWriteOutcomeUnknown,RecordWriteRefused2 as RecordWriteRefused,RecordWrites2 as RecordWrites,disposeRecordLayer2 as disposeRecordLayer,entityTopic2 as entityTopic,entityWriteTarget2 as entityWriteTarget,fromLiveQuery,fromTransaction,useRecordCollection,useRecordRuntime};
@@ -0,0 +1,151 @@
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
+
15
+ declare const RecordSyncFailed_base: Schema.Class<RecordSyncFailed, Schema.TaggedStruct<"RecordSyncFailed", {
16
+ readonly cause: Schema.optional<Schema.Defect>;
17
+ readonly message: Schema.String;
18
+ readonly retrying: Schema.Boolean;
19
+ }>, Cause.YieldableError>;
20
+ /**
21
+ * A Record Collection could not load or follow its records. `retrying` tells
22
+ * that its sync keeps trying, so the rows and the status stay.
23
+ */
24
+ export declare class RecordSyncFailed extends RecordSyncFailed_base {
25
+ }
26
+ /** The schema of a record value; it decodes with no service. */
27
+ export type RecordValueSchema<Value extends object> = Schema.Codec<Value, unknown>;
28
+ /** One record as CI sends it, before decoding. */
29
+ export type UndecodedRecord = Readonly<{
30
+ id: string;
31
+ revision: string | null;
32
+ value: unknown;
33
+ }>;
34
+ /** The records of one entity schema, named by FQN or id, optionally filtered. */
35
+ export type RecordTopic = Readonly<{
36
+ schema: string;
37
+ filter?: Readonly<{
38
+ field: string;
39
+ eq: string | number | boolean | null;
40
+ }>;
41
+ }>;
42
+ /**
43
+ * Where a write goes. The SDK adapter that makes the target knows what
44
+ * `key` names; the record layer only reads `key`, which is stable for one
45
+ * target.
46
+ */
47
+ export type RecordWriteTarget = Readonly<{
48
+ key: string;
49
+ }>;
50
+ export type QueryRecordCollectionOptions<Value extends object, E = never, R = never> = Readonly<{
51
+ /** The key of the rows on the app's shared QueryClient. */
52
+ queryKey: QueryKey;
53
+ schema: RecordValueSchema<Value>;
54
+ /** Reads every record of the query, as CI holds it. */
55
+ load: Effect.Effect<readonly UndecodedRecord[], E, R>;
56
+ /**
57
+ * The write target of the query's records, if they have one: a record
58
+ * write of that target then shows in the rows this collection holds.
59
+ */
60
+ target?: RecordWriteTarget;
61
+ }>;
62
+ /** The CI identity that owns a set of Record Collections: one user of one Organization in one application. */
63
+ export type RecordIdentity = Readonly<{
64
+ applicationId: string;
65
+ organizationId: string;
66
+ userId: string;
67
+ }>;
68
+ declare const RecordIdentityKey: Schema.brand<Schema.String, "RecordIdentityKey">;
69
+ export type RecordIdentityKey = typeof RecordIdentityKey.Type;
70
+ /** The TanStack clients of one server request. */
71
+ export type RequestClients = Readonly<{
72
+ /** Holds the rows of the request's Record Collections; its `queryClient` dependency is the one below. */
73
+ dbClient: DbClient;
74
+ /** Holds the fetched rows of the request's Query Record Collections. */
75
+ queryClient: QueryClient;
76
+ }>;
77
+ /**
78
+ * The QueryClient and the `DbClient({ queryClient })` of the current server
79
+ * request: the same pair in one request, a new pair in each other request.
80
+ * Call it only in a React Server Component; React `cache()` scopes it to the
81
+ * request.
82
+ */
83
+ export declare const getRequestClients: () => RequestClients;
84
+ /** What the server read for one Realtime Record Collection. */
85
+ export type RealtimeRecordRead = Readonly<{
86
+ records: readonly UndecodedRecord[];
87
+ /**
88
+ * The `position` of the read. The browser stream of the topic starts there.
89
+ * Without one, it replays from the page's age.
90
+ */
91
+ position: string | undefined;
92
+ }>;
93
+ /** One Realtime Record Collection to seed: its topic, its value schema and its read. */
94
+ export type RealtimeRecordSeedOptions<Value extends object, E = never, R = never> = Readonly<{
95
+ topic: RecordTopic;
96
+ schema: RecordValueSchema<Value>;
97
+ load: Effect.Effect<RealtimeRecordRead, E, R>;
98
+ }>;
99
+ /**
100
+ * The Record Collections that one server render seeds. Each option names a
101
+ * collection as the browser opens it, so the seed hydrates that collection.
102
+ */
103
+ export type RecordSeedSources<E, R> = Readonly<{
104
+ /**
105
+ * The CI identity of the request's session: the application, Organization
106
+ * and user that the browser's entity source reports. The seed then keys its
107
+ * Query Record Collections as that identity's browser collections do, and
108
+ * hydrates only that identity's Record Collections. Leave it out where the
109
+ * provider has no identities (Studio).
110
+ */
111
+ identity?: RecordIdentity;
112
+ query?: readonly QueryRecordCollectionOptions<object, E, R>[];
113
+ realtime?: readonly RealtimeRecordSeedOptions<object, E, R>[];
114
+ }>;
115
+ /** The loads of one `seedRecords` call. */
116
+ export type RecordSeedLoad<Sources extends RecordSeedSources<unknown, unknown>> = NonNullable<Sources["query"]>[number]["load"] | NonNullable<Sources["realtime"]>[number]["load"];
117
+ /**
118
+ * The two payloads of a server seed. `query` holds the fetched rows of the
119
+ * Query Record Collections, `db` the rows of every seeded Record Collection,
120
+ * the live query snapshots of the first render and each Realtime Record
121
+ * Collection's position in its sync metadata.
122
+ */
123
+ export type RecordSeed = Readonly<{
124
+ query: DehydratedState;
125
+ db: DehydratedDbState;
126
+ /** The CI identity the seed was made for; only its Record Collections take it. */
127
+ identity?: RecordIdentityKey;
128
+ /**
129
+ * The Seed Owner: the CI identity whose rows the seed holds, as ids. A seed
130
+ * boundary can open this identity's scope before the provider knows its
131
+ * identity. Equal to `identity` when hashed.
132
+ */
133
+ owner?: RecordIdentity;
134
+ }>;
135
+ export type SeedRecordsOptions = Readonly<{
136
+ /** How long to wait for the reads; `SeedWait` by default. */
137
+ wait?: Duration.Input;
138
+ }>;
139
+ /**
140
+ * Fetches each Query Record Collection once into the request QueryClient
141
+ * and reads each Realtime Record Collection, renders their rows on the
142
+ * request DbClient and dehydrates both clients. A Realtime Record Collection
143
+ * is in the DB payload only, with its read's position in its sync metadata.
144
+ * Each load runs with the context of this call. A collection whose read does
145
+ * not answer within the Seed Wait (`seedOptions.wait`, 8 seconds by default) is
146
+ * left out of the seed, and its browser collection loads itself. Render the
147
+ * result in `<RecordSeedBoundary>`, or pass its promise to it.
148
+ */
149
+ export declare function seedRecords<const Sources extends RecordSeedSources<unknown, unknown>>(sources: Sources, seedOptions?: SeedRecordsOptions): Effect.Effect<RecordSeed, Effect.Error<RecordSeedLoad<Sources>> | RecordSyncFailed, Effect.Services<RecordSeedLoad<Sources>>>;
150
+
151
+ export {};
@@ -0,0 +1 @@
1
+ import{RecordSyncFailed2}from"./index-3jq1t3k2.js";import{getRequestClients2,seedRecords2}from"./index-ntjesxcf.js";export{RecordSyncFailed2 as RecordSyncFailed,getRequestClients2 as getRequestClients,seedRecords2 as seedRecords};
@@ -114,31 +114,38 @@ export type RecordSeed = Readonly<{
114
114
  db: DehydratedDbState;
115
115
  /** The CI identity the seed was made for; only its Record Collections take it. */
116
116
  identity?: RecordIdentityKey;
117
+ /**
118
+ * The Seed Owner: the CI identity whose rows the seed holds, as ids. A seed
119
+ * boundary can open this identity's scope before the provider knows its
120
+ * identity. Equal to `identity` when hashed.
121
+ */
122
+ owner?: RecordIdentity;
123
+ }>;
124
+ export type SeedRecordsOptions = Readonly<{
125
+ /** How long to wait for the reads; `SeedWait` by default. */
126
+ wait?: Duration.Input;
117
127
  }>;
118
128
  /**
119
129
  * Fetches each Query Record Collection once into the request QueryClient
120
130
  * and reads each Realtime Record Collection, renders their rows on the
121
131
  * request DbClient and dehydrates both clients. A Realtime Record Collection
122
132
  * 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>`.
133
+ * Each load runs with the context of this call. A collection whose read does
134
+ * not answer within the Seed Wait (`seedOptions.wait`, 8 seconds by default) is
135
+ * left out of the seed, and its browser collection loads itself. Render the
136
+ * result in `<RecordSeedBoundary>`, or pass its promise to it.
125
137
  */
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>>>;
138
+ export declare function seedRecords<const Sources extends RecordSeedSources<unknown, unknown>>(sources: Sources, seedOptions?: SeedRecordsOptions): Effect.Effect<RecordSeed, Effect.Error<RecordSeedLoad<Sources>> | RecordSyncFailed, Effect.Services<RecordSeedLoad<Sources>>>;
127
139
  export type RecordSeedBoundaryProps = Readonly<{
128
- /** What `seedRecords` returned in the server render. */
129
- seed: RecordSeed;
140
+ /**
141
+ * What `seedRecords` returned in the server render, or its promise. The
142
+ * boundary reads a promise with React `use()`, so put it inside a
143
+ * `<Suspense>`; a promise of `null` gives no seed, and the collections load
144
+ * themselves.
145
+ */
146
+ seed: RecordSeed | Promise<RecordSeed | null>;
130
147
  children?: ReactNode;
131
148
  }>;
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
149
  export type QueryRecordCollectionOptions<Value extends object, E = never, R = never> = Readonly<{
143
150
  /** The key of the rows on the app's shared QueryClient. */
144
151
  queryKey: QueryKey;
@@ -151,5 +158,14 @@ export type QueryRecordCollectionOptions<Value extends object, E = never, R = ne
151
158
  */
152
159
  target?: RecordWriteTarget;
153
160
  }>;
161
+ /**
162
+ * Hydrates a server seed, or the seed of a promise, into the record scope of
163
+ * the SDK provider's identity, so the seeded rows are in the first HTML.
164
+ * It loads the record layer of the tree's QueryClient. While the provider
165
+ * does not know its identity yet, a seed that names its Seed Owner opens
166
+ * the owner's Provisional Scope there and gives it to its subtree; the
167
+ * provider adopts that scope when the identity arrives.
168
+ */
169
+ export declare const RecordSeedBoundary: ({ children, seed }: RecordSeedBoundaryProps) => import("react").JSX.Element;
154
170
 
155
171
  export {};
@@ -1 +1 @@
1
- import{RecordSyncFailed2,recordIdentityKey,recordQueryScope,realtimeCollectionId,recordRowSchema,RealtimeChangeSource,RealtimeSyncMeta,make}from"./index-najx4ye0.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};
1
+ import{RecordSyncFailed2}from"./index-3jq1t3k2.js";import{getRequestClients2,seedRecords2}from"./index-ntjesxcf.js";import{RecordSeedBoundary}from"./records.js";export{RecordSeedBoundary,RecordSyncFailed2 as RecordSyncFailed,getRequestClients2 as getRequestClients,seedRecords2 as seedRecords};
@@ -151,11 +151,16 @@ export type EntityIdentity = Readonly<{
151
151
  userId: string;
152
152
  organizationId: string;
153
153
  }>;
154
+ /**
155
+ * The state of an entity source. `pending`: the source does not know its
156
+ * identity yet, as in a server render or the first browser render of an app
157
+ * that learns it later; it is no sign-out.
158
+ */
154
159
  export type EntitySourceState = Readonly<{
155
160
  status: "authenticated";
156
161
  identity: EntityIdentity;
157
162
  }> | Readonly<{
158
- status: "unauthenticated" | "expired" | "forbidden";
163
+ status: "pending" | "unauthenticated" | "expired" | "forbidden";
159
164
  }>;
160
165
  /** Configured authenticated client boundary. Snapshots are stable until identity changes. */
161
166
  export interface EntitySource {
package/dist/resources.js CHANGED
@@ -1,3 +1,3 @@
1
1
  "use client";
2
- import{resourceKeys,ResourceQueryError2,unwrapResourceResult2,createResourceListQueryOptions,mapResourceAuthState2,hasResourceCapability2,clearProtectedResourceQueries,useEntityRuntime,createDelegatedEntitySource2}from"./index-hmgpja4s.js";import"./index-xmbt130r.js";import{__chunks,defineEntity2,useEntityUpdate2,useEntityCreate2,useEntityDelete2,useEntityList2,useEntityRecord2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-xy7wm8d1.js";__chunks(import.meta.url,["4e9g4kw7","hmgpja4s","xmbt130r","xy7wm8d1","r4wk5rcm","dvybt7v0","najx4ye0","vw8r73tc"],[["./resources.js",1,2,3],["./index-hmgpja4s.js",2,4],["./index-xmbt130r.js"],["./index-xy7wm8d1.js",1],["./index-r4wk5rcm.js"],["./entity-write-dvybt7v0.js",6,7,1,2,3],["./index-najx4ye0.js",4],["./index-vw8r73tc.js",6,1,2,4]],0);
2
+ import{resourceKeys,ResourceQueryError2,unwrapResourceResult2,createResourceListQueryOptions,mapResourceAuthState2,hasResourceCapability2,clearProtectedResourceQueries,useEntityRuntime,createDelegatedEntitySource2}from"./index-1r3w51e7.js";import"./index-xmbt130r.js";import{__chunks,defineEntity2,useEntityUpdate2,useEntityCreate2,useEntityDelete2,useEntityList2,useEntityRecord2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-70ta86wb.js";__chunks(import.meta.url,["rdhb7jam","1r3w51e7","xmbt130r","70ta86wb","r4wk5rcm","z1jqncqh","3jq1t3k2","v04mv78p"],[["./resources.js",1,2,3],["./index-1r3w51e7.js",2,4],["./index-xmbt130r.js"],["./index-70ta86wb.js",1],["./index-r4wk5rcm.js"],["./entity-write-z1jqncqh.js",6,7,1,2,3],["./index-3jq1t3k2.js",4],["./index-v04mv78p.js",6,1,2,4]],0);
3
3
  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};
@@ -221,17 +221,38 @@ skill for the steps. The parts:
221
221
  that identity's collections do. A realtime seed's `load` returns
222
222
  `{ records, position }`; the browser stream of the topic starts at that
223
223
  `position`, so it misses no change after the read and repeats none.
224
- - `<RecordSeedBoundary seed>` hydrates the seed in the browser, inside the SDK
225
- provider, which gives the identity's DbClient to its tree. While no user is
226
- signed in, the seed waits and hydrates at the sign-in. A seed made for
227
- another identity, or with no `identity`, never hydrates.
224
+ - `<RecordSeedBoundary seed>` hydrates the seed inside the SDK provider. `seed`
225
+ is the seed or its promise: pass the promise of `seedRecords` un-awaited and
226
+ wrap the boundary in `<Suspense>`, so the rows stream into the HTML. A
227
+ promise of `null` gives no seed.
228
+ - `seedRecords` names the Seed Owner (`RecordSeed.owner`). While the provider
229
+ does not know its identity yet (`pending`, or its first `unauthenticated`),
230
+ the boundary opens the owner's Provisional Scope, hydrates it and gives it
231
+ to its subtree, on the server and in the browser. When the provider's
232
+ identity arrives with the owner's key, it adopts that scope: the same rows,
233
+ no second read. An identity of another key drops the seeded rows and
234
+ reports `RecordIdentityMismatch`. With no identity within the Identity Wait
235
+ (10 s), the seed no longer applies and `RecordIdentityMissing` is reported;
236
+ the collections load themselves. A seed with no `owner` hydrates only into
237
+ the scope of its identity, with the same bound.
238
+ - `useRecordCollection` gives a seeded collection `ready` with its rows in the
239
+ render that hydrated it.
240
+ - `seedRecords(sources, { wait })` waits at most 8 s (the Seed Wait) for its
241
+ reads; a late collection is left out of the seed and loads in the browser.
228
242
  - A seeded collection reads nothing on its first render. A seeded Query
229
243
  Record Collection takes its seed as fresh for one minute after it hydrated,
230
244
  until its first browser update; an invalidation still reads it again.
231
245
 
232
- The `react-server` build of `./records` holds the server values. TypeScript
233
- sees `getRequestClients` and `seedRecords` in every build; a client component
234
- that imports them fails when it bundles.
246
+ Import `seedRecords` and `getRequestClients` from `./records/seed` in a
247
+ layout or a shared server module. That entry holds the server seed alone and
248
+ imports no client module, so it adds no client reference to the pages under
249
+ the layout. The `react-server` build of `./records` holds the same values,
250
+ but it also brings `RecordSeedBoundary`: a layout that imports `./records`,
251
+ even with `import()`, makes the whole record layer a client reference of each
252
+ page under it. Keep `./records/seed` in server code; a client component that
253
+ imports it ships the seed code to the browser. TypeScript sees
254
+ `getRequestClients` and `seedRecords` in every build of `./records`; a
255
+ client component that imports them from `./records` fails when it bundles.
235
256
 
236
257
  ### Client seed from plain data
237
258
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@collective-intelligence/external-apps-client-sdk-react",
3
- "version": "0.13.5",
3
+ "version": "0.13.7",
4
4
  "description": "React bindings for Collective Intelligence external applications.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -49,6 +49,12 @@
49
49
  "types": "./dist/records.d.ts",
50
50
  "import": "./dist/records.js",
51
51
  "default": "./dist/records.js"
52
+ },
53
+ "./records/seed": {
54
+ "ci-source": "./src/records.seed.ts",
55
+ "types": "./dist/records.seed.d.ts",
56
+ "import": "./dist/records.seed.js",
57
+ "default": "./dist/records.seed.js"
52
58
  }
53
59
  },
54
60
  "scripts": {
@@ -65,12 +71,12 @@
65
71
  "type-check": "bun check --no-script -p tsconfig.json"
66
72
  },
67
73
  "dependencies": {
68
- "@collective-intelligence/effect-xstate": "0.13.5",
69
- "@collective-intelligence/external-apps-client-sdk": "0.13.5",
74
+ "@collective-intelligence/effect-xstate": "0.13.7",
75
+ "@collective-intelligence/external-apps-client-sdk": "0.13.7",
70
76
  "nuqs": "2.10.1"
71
77
  },
72
78
  "peerDependencies": {
73
- "@collective-intelligence/ui-react": "0.13.5",
79
+ "@collective-intelligence/ui-react": "0.13.7",
74
80
  "@tanstack/db": "1.0.0-rc.1.5",
75
81
  "@tanstack/offline-transactions": "1.2.1",
76
82
  "@tanstack/query-core": "^5.101.4",
@@ -86,7 +92,7 @@
86
92
  "access": "public"
87
93
  },
88
94
  "devDependencies": {
89
- "@collective-intelligence/ui-react": "0.13.5",
95
+ "@collective-intelligence/ui-react": "0.13.7",
90
96
  "@effect/eslint-plugin": "0.3.2",
91
97
  "@oxlint/plugins": "1.94.0",
92
98
  "@punks/lints": "0.2.0",
@@ -119,5 +125,5 @@
119
125
  "vitest": "4.1.10",
120
126
  "xstate": "5.33.3"
121
127
  },
122
- "gitHead": "8cab739abddbf79390a283844d159d40179eb323"
128
+ "gitHead": "50215ed0efe7c63414867375f2735203fc88e76c"
123
129
  }
@@ -20,9 +20,9 @@ server rendering off. Follow these steps in its place.
20
20
  (`{ schema, filter? }`) and `schema`. The browser wraps the topic with
21
21
  `entityTopic(contract, topic)`. Done when the server and the browser build
22
22
  each collection from the same object.
23
- 2. **Seed in the server component.** Import `seedRecords` from `./records`
24
- (the `react-server` build) and run it once per request with the
25
- session's identity:
23
+ 2. **Seed in the server component.** Import `seedRecords` from
24
+ `./records/seed`, the server seed alone, and run it once per request with
25
+ the session's identity:
26
26
  `seedRecords({ identity, query: [leadsQuery], realtime: [{ topic, schema, load }] })`.
27
27
  `identity` is `{ applicationId, organizationId, userId }` of the request's
28
28
  session, the values the browser's entity source reports; without it the
@@ -37,15 +37,20 @@ server rendering off. Follow these steps in its place.
37
37
  Done when no cached function returns a seed.
38
38
  4. **Hydrate in the browser.** Render `<RecordSeedBoundary seed={seed}>`
39
39
  inside the SDK provider, around the client components that read the
40
- collections. They open the collections through `useRecordRuntime()` and
41
- `RecordCollections`, and read rows with `useLiveQuery`. While no user is
42
- signed in, the seed waits and hydrates at the sign-in; give the entity
43
- source the session at its first render to show the rows in the first
44
- HTML. Done when the client component renders rows with no loading state
45
- on first load.
40
+ collections; pass the promise of `seedRecords` un-awaited and wrap the
41
+ boundary in `<Suspense>`. The client components open the collections with
42
+ `useRecordCollection` (a seeded one is `ready` in the same render) and read
43
+ rows with `useLiveQuery`. While the entity source does not know its
44
+ identity yet (`pending`), the seed opens its Seed Owner's scope, so the
45
+ rows are in the first HTML; the provider adopts that scope when the
46
+ identity arrives. Done when the client component renders rows with no
47
+ loading state on first load.
46
48
  5. **Keep the server values on the server.** Import `getRequestClients` and
47
- `seedRecords` only in server components; a client component that imports
48
- them fails when it bundles. Done when the build passes.
49
+ `seedRecords` from `./records/seed`, and only in server code. A layout or
50
+ a shared server module that imports them from `./records` (even with
51
+ `import()`) makes the whole record layer a client reference of each page
52
+ under it. Done when the build passes and no server module imports the
53
+ seed from `./records`.
49
54
  6. **Verify.** Fetch the page HTML and find the seeded rows in it. In the
50
55
  browser, check that the seeded collections make no list read after load,
51
56
  and that the realtime stream opens with a `from` for each seeded topic.
@@ -1,2 +0,0 @@
1
- "use client";
2
- import{RecordWriteConflict2,RecordWriteOutcomeUnknown2,RecordSyncFailed2,RecordId2,RecordRevision,IdempotencyKey2,targetCollections,RecordWrites2,RecordCollections2}from"./index-najx4ye0.js";import{entityWriteTarget2,awaitEntityAnswer,recordLayerOf}from"./index-vw8r73tc.js";import{entityScopeError}from"./index-hmgpja4s.js";import"./index-xmbt130r.js";import{newRecordId}from"./index-xy7wm8d1.js";import*as Cause from"effect/Cause";import*as Effect from"effect/Effect";import*as Exit from"effect/Exit";import{constVoid}from"effect/Function";import*as Schema2 from"effect/Schema";var runEffect=async(runtime,effect,signal)=>await runtime.runPromise(effect,signal===undefined?undefined:{signal});import{CiError,CiErrorCode,CiTransportError}from"@collective-intelligence/external-apps-client-sdk/effect";import*as Schema from"effect/Schema";var isCiErrorCode=Schema.is(CiErrorCode);var writeFailure=(error)=>error.code==="transport_error"?new CiTransportError({cause:error}):new CiError({code:isCiErrorCode(error.code)?error.code:"invalid_request",details:error.outcome===undefined?{...error.details,resourceCode:error.code}:{...error.details,outcome:error.outcome,resourceCode:error.code},message:error.message,retryable:error.retryable});var entityValue=Schema2.Record(Schema2.String,Schema2.Unknown);var holdingCollection=(dbClient,target,id)=>{const holding=targetCollections(dbClient,target).find((entry)=>entry.collection.get(id)!==undefined);return holding===undefined?undefined:{collection:holding.collection,kind:holding.kind}};var blindRevisionOf=(contract,write)=>write.operation!=="create"&&contract.capabilities.get!==true?write.input.expectedRevision:undefined;var writeHolding=(found,id,blindRevision)=>{if(blindRevision===undefined||found?.kind==="realtime"){return found}const row=found?.collection.get(id);return row!==undefined&&(row.$hasPendingWrites||row.revision===blindRevision)?found:undefined};var failed=(error)=>({correlationId:"record-layer",error,ok:false});var failureOf=(error)=>{if(Schema2.is(RecordWriteConflict2)(error)){return failed({code:"conflict",message:error.message,outcome:"rejected",retryable:false})}if(Schema2.is(RecordWriteOutcomeUnknown2)(error)){return failed({code:"transport_error",message:error.message,outcome:"uncertain",retryable:true})}return failed({code:"invalid_request",message:error.message,outcome:"rejected",retryable:false})};var unreadable=(id)=>failed({code:"not_found",message:`The record ${id} is not readable now`,outcome:"not_dispatched",retryable:true});var staleRevision=(id)=>failed({code:"conflict",message:`The record ${id} changed since its edit began`,outcome:"not_dispatched",retryable:false});var readRecord=(client,id)=>Effect.tryPromise({catch:(cause)=>new RecordSyncFailed2({cause,message:`The read of the record ${id} did not arrive`,retrying:true}),try:(signal)=>client.get({id},{signal})}).pipe(Effect.flatMap((result)=>{if(result.ok){return Effect.succeed([{id:result.value.id,revision:result.value.revision,value:result.value.value}])}return result.error.code==="not_found"||result.error.code==="forbidden"?Effect.succeed([]):Effect.fail(new RecordSyncFailed2({cause:result.error,message:result.error.message,retrying:result.error.retryable}))}));var blindRows=(options,revision)=>{const known=options.cached();return Effect.succeed([{id:options.id,revision,value:known?.revision===revision?known.value:{}}])};var unreadableLoad=(id)=>Effect.fail(new RecordSyncFailed2({cause:undefined,message:`The record ${id} cannot be read by id`,retrying:false}));var recordRows=(options)=>Effect.flatMap(Effect.service(RecordCollections2),(collections)=>{let loads=0;const blind=options.blindRevision;return collections.query({load:Effect.suspend(()=>{loads+=1;if(blind!==undefined){return loads>1?unreadableLoad(options.id):blindRows(options,blind)}if(loads>1){return readRecord(options.client,options.id)}if(options.created){return Effect.succeed([])}const known=options.cached();return known===undefined?readRecord(options.client,options.id):Effect.succeed([{id:known.id,revision:known.revision,value:known.value}])}),queryKey:blind===undefined?[...options.resourceKey,"record-rows",options.id]:[...options.resourceKey,"record-rows",options.id,blind],schema:entityValue,target:options.target})});var reload=(collection)=>Effect.ignore(Effect.tryPromise(async()=>{const utils=collection.utils;await utils.refetch()}));var recordWrite=Effect.fn("EntityHooks.write")(function*entityWrite(options){const{client,contract,resourceKey,write}=options;const target=entityWriteTarget2(contract);const id=write.operation==="create"?write.input.id??newRecordId():write.input.id;yield*Effect.annotateCurrentSpan({"entity.contract":contract.id,"record.id":id,"write.kind":write.operation});const blindRevision=blindRevisionOf(contract,write);const holding=write.operation==="create"?undefined:writeHolding(holdingCollection(options.dbClient,target,id),id,blindRevision);const collection=holding?.collection??(yield*recordRows({blindRevision,cached:()=>options.cached(id),client,created:write.operation==="create",id,resourceKey,target}));yield*write.operation==="create"?Effect.sync(()=>{collection.preload().catch(constVoid)}):Effect.ignore(Effect.tryPromise(()=>collection.preload()));const writes=yield*RecordWrites2;const base={collection,id:RecordId2.make(id),idempotencyKey:IdempotencyKey2.make(write.input.idempotencyKey),target};if(write.operation==="create"){const value=write.input.value;yield*writes.create({...base,value});return}const edited=(current)=>current!==undefined&&!current.$hasPendingWrites&&current.revision!==write.input.expectedRevision;if(!options.resend){if(blindRevision===undefined&&holding?.kind!=="realtime"&&edited(collection.get(id))){yield*reload(collection)}const row=collection.get(id);if(row===undefined){return unreadable(id)}if(edited(row)){return staleRevision(id)}}const checked={...base,expectedRevision:collection.get(id)?.revision===null?null:RecordRevision.make(write.input.expectedRevision)};if(write.operation==="update"){const change=write.input.value;yield*writes.update({...checked,change});return}yield*writes.delete(checked)});var openRecordLayer=(queryClient)=>{recordLayerOf(queryClient).connect()};var runEntityWrite=async(options)=>{const{identity,write}=options;if(identity===undefined){throw entityScopeError()}const layer=recordLayerOf(options.queryClient);layer.connect();const scope=layer.records(identity);const answer=awaitEntityAnswer(write.input.idempotencyKey);const departed=()=>{const error=entityScopeError(answer.take().dispatched?"uncertain":"not_dispatched");return{correlationId:error.correlationId,error:error.resourceError,ok:false}};let exit2;try{exit2=await runEffect(scope.runtime,Effect.exit(recordWrite({cached:options.cached,client:options.client,contract:options.contract,dbClient:scope.dbClient,resend:options.resend,resourceKey:options.resourceKey,write})))}catch{return departed()}if(Exit.isFailure(exit2)&&(Cause.hasInterruptsOnly(exit2.cause)||!options.current())){return departed()}const whole=answer.take().answer;if(Exit.isSuccess(exit2)){return exit2.value??whole??failed({code:"internal",message:"CI gave no answer to the write",outcome:"uncertain",retryable:false})}const failure=Cause.findErrorOption(exit2.cause);if(failure._tag==="None"){throw Cause.squash(exit2.cause)}return whole!==undefined&&!whole.ok?whole:failureOf(failure.value)};export{openRecordLayer,runEntityWrite,writeFailure};
@@ -1,2 +0,0 @@
1
- import{realtimeFeedOf,RecordRealtimeContext}from"./index-xmbt130r.js";import{outboxKeyText,dropOutboxAfterSignOut}from"./index-r4wk5rcm.js";import{createEntityHttpTransport,createResourceClient}from"@collective-intelligence/external-apps-client-sdk";import{DbProvider}from"@tanstack/react-db";import{createContext,useMemo}from"react";import{jsx}from"react/jsx-runtime";var RecordScopeContext=createContext(undefined);var RecordScopeProvider=({children,dbClient,identity})=>{const scope=useMemo(()=>({dbClient,identity}),[dbClient,identity]);return jsx(RecordScopeContext.Provider,{value:scope,children:jsx(DbProvider,{client:dbClient,children})})};import{useQueryClient}from"@tanstack/react-query";import{createContext as createContext2,useContext,useLayoutEffect,useMemo as useMemo2,useSyncExternalStore as useSyncExternalStore2}from"react";import{queryOptions}from"@tanstack/react-query";var rootKey=["ci-resources"];var resourceKeys={all:rootKey,list:(organizationId,resourceId,version,query)=>[...resourceKeys.lists(organizationId,resourceId,version),query],lists:(organizationId,resourceId,version)=>[...resourceKeys.resource(organizationId,resourceId,version),"lists"],organization:(organizationId)=>[...rootKey,"organizations",organizationId],record:(organizationId,resourceId,version,recordId,includeDeleted=false)=>[...resourceKeys.records(organizationId,resourceId,version),recordId,includeDeleted],records:(organizationId,resourceId,version)=>[...resourceKeys.resource(organizationId,resourceId,version),"records"],resource:(organizationId,resourceId,version)=>[...resourceKeys.organization(organizationId),"resources",resourceId,"versions",version]};class ResourceQueryError2 extends Error{correlationId;resourceError;constructor(correlationId,error){super(error.message);this.name="ResourceQueryError";this.correlationId=correlationId;this.resourceError=error}}var unwrapResourceResult2=(result)=>{if(!result.ok){throw new ResourceQueryError2(result.correlationId,result.error)}return result.value};var createResourceListQueryOptions=(options)=>queryOptions({queryFn:async({signal})=>unwrapResourceResult2(await options.client.list(options.query,{signal})),queryKey:resourceKeys.list(options.organizationId,options.client.definition.id,options.client.definition.version,options.query)});var mapResourceAuthState2=(source)=>{if("ok"in source){if(source.ok){return{status:"authenticated"}}if(source.error.code==="forbidden"){return{status:"forbidden"}}if(source.error.code==="unauthenticated"){return{status:"unauthenticated"}}return{status:"authenticated"}}if(source.status==="authenticated"){return{status:"authenticated"}}if(source.status==="expired"){return{status:"expired"}}if(source.status==="error"&&source.error.code==="reauthorization_required"){return{status:"reauthentication_required"}}return{status:"unauthenticated"}};var hasResourceCapability2=(capabilities,capability)=>capabilities[capability]===true;var clearProtectedResourceQueries=async(queryClient,organizationId)=>{const queryKey=organizationId===undefined?resourceKeys.all:resourceKeys.organization(organizationId);await queryClient.cancelQueries({queryKey});queryClient.removeQueries({queryKey})};import{useSyncExternalStore}from"react";var recordIdentityOf=(state)=>state.status==="authenticated"?{applicationId:state.identity.applicationId,organizationId:state.identity.organizationId,userId:state.identity.userId}:undefined;var outboxKeyOfIdentity=(identity)=>outboxKeyText(identity.organizationId,identity.userId);var reportMismatch=(message)=>{globalThis.console.error(`[ci-records] RecordIdentityMismatch: ${message}`)};var loadedModule;var moduleListeners=new Set;var signedInKeys=new Map;var countSignedIn=(key,change)=>{const count=(signedInKeys.get(key)??0)+change;if(count>0){signedInKeys.set(key,count)}else{signedInKeys.delete(key)}};var signedInAgain=(key)=>loadedModule===undefined?signedInKeys.has(key):loadedModule.holds(key);var makeIdentityCell=()=>{let source;const attached=new Map;let session;let signedIn;const contracts=new Set;const listeners=new Set;const bindListeners=new Set;const signOutHandlers=new Set;let outboxStorage;let counted=false;const count=(on)=>{if(signedIn===undefined||counted===on){return}counted=on;countSignedIn(outboxKeyOfIdentity(signedIn),on?1:-1)};const signIn=(identity)=>{count(false);signedIn=identity;count(attached.size>0)};const signOut=(identity)=>{const key=outboxKeyOfIdentity(identity);const handlers=[...signOutHandlers];dropOutboxAfterSignOut(key,{closing:async()=>{await Promise.all(handlers.map(async(handler)=>await handler()))},signedInAgain:()=>signedInAgain(key),storage:outboxStorage})};const follow=(next,state)=>{if(next!==source){return}session={source:next,state};const previous=signedIn;signIn(recordIdentityOf(state));for(const listener of listeners){listener()}if(state.status==="unauthenticated"&&previous!==undefined){signOut(previous)}};return{attach:(next)=>{attached.set(next,(attached.get(next)??0)+1);count(true);if(attached.size>1&&source!==next){reportMismatch("Two entity sources share one QueryClient; the record layer follows the first. Give each provider its own QueryClient, or one source.")}if(attached.size===1){source=next}let released=false;return()=>{if(released){return}released=true;const holders=(attached.get(next)??1)-1;if(holders>0){attached.set(next,holders);return}attached.delete(next);count(attached.size>0);const remaining=attached.keys().next().value;if(source===next&&remaining!==undefined){source=remaining;follow(remaining,remaining.getSnapshot())}}},beforeSignOut:(handler)=>{signOutHandlers.add(handler);return()=>{signOutHandlers.delete(handler)}},bound:(next)=>{source??=next;return{bind:(contract)=>{const known=contract;if(!contracts.has(known)){contracts.add(known);for(const listener of bindListeners){listener(known)}}return next.bind(contract)},getSnapshot:()=>next.getSnapshot(),subscribe:(notify)=>next.subscribe(notify)}},contracts:(listener)=>{for(const contract of contracts){listener(contract)}bindListeners.add(listener);return()=>{bindListeners.delete(listener)}},follow,keepOutboxIn:(storage)=>{outboxStorage=storage;return()=>{if(outboxStorage===storage){outboxStorage=undefined}}},nestedSource:(next)=>{if(source!==undefined&&source!==next){reportMismatch("A provider nested in another one on the same QueryClient has another entity source; the record layer follows the outer one. Give the nested provider its own QueryClient.")}},session:()=>session,source:()=>source,subscribe:(listener)=>{listeners.add(listener);return()=>{listeners.delete(listener)}}}};var cells=new WeakMap;var identityCellOf=(queryClient)=>{const known=cells.get(queryClient);if(known!==undefined){return known}const made=makeIdentityCell();cells.set(queryClient,made);return made};var subscribeModule=(listener)=>{moduleListeners.add(listener);return()=>{moduleListeners.delete(listener)}};var currentModule=()=>loadedModule;var provideRecordLayerModule=(module)=>{if(loadedModule!==undefined){return}loadedModule=module;for(const listener of moduleListeners){listener()}};var useRecordLayerModule=()=>useSyncExternalStore(subscribeModule,currentModule,currentModule);import{jsx as jsx2}from"react/jsx-runtime";var entityScopeError=(outcome="not_dispatched")=>new ResourceQueryError2("client-scope",{code:"unauthenticated",message:"The authenticated entity source has changed",outcome,retryable:false});var identityKey=(state)=>state.status==="authenticated"?[state.identity.sourceId,state.identity.applicationId,state.identity.userId,state.identity.organizationId]:[state.status];var EntityContext=createContext2(null);var FollowedCellContext=createContext2(undefined);var queryScopes=new WeakMap;var retainQueries=(queryClient,key)=>{const scopes=queryScopes.get(queryClient)??new Map;queryScopes.set(queryClient,scopes);const identity=JSON.stringify(key);scopes.set(identity,(scopes.get(identity)??0)+1);return()=>{const users=scopes.get(identity)??0;if(users>1){scopes.set(identity,users-1);return false}scopes.delete(identity);if(scopes.size===0){queryScopes.delete(queryClient)}return true}};var runtimes=0;var createRuntime=(source,state,recordScoped)=>{let active=true;let onWriteFailed;runtimes+=1;const formScope=String(runtimes);return{activate:()=>{active=true},current:()=>active&&source.getSnapshot()===state&&state.status==="authenticated",deactivate:()=>{active=false},formScope,key:identityKey(state),recordScoped,reportWriteFailures:(listener)=>{onWriteFailed=listener},source,state,writeFailed:(event)=>{onWriteFailed?.(event)}}};var noUnsubscribe=()=>{};var noLayer=()=>noUnsubscribe;var noVersion=()=>0;var useRecordScope=(layer,state)=>{useSyncExternalStore2(layer?.subscribe??noLayer,layer?.version??noVersion,layer?.version??noVersion);const identity=recordIdentityOf(state);return layer===undefined||identity===undefined?undefined:layer.records(identity)};var EntityRuntimeProvider=({source,onWriteFailed,children})=>{const queryClient=useQueryClient();const state=useSyncExternalStore2(source.subscribe,source.getSnapshot,source.getSnapshot);const cell=identityCellOf(queryClient);const nested=useContext(FollowedCellContext)===cell;const layer=useRecordLayerModule()?.layerOf(queryClient);const followed=cell.source();const recordScoped=!(nested&&followed!==undefined&&followed!==source);const scope=useRecordScope(layer,state);const records=recordScoped?scope:undefined;const bound=useMemo2(()=>cell.bound(source),[cell,source]);const runtime=useMemo2(()=>createRuntime(bound,state,recordScoped),[bound,state,recordScoped]);useLayoutEffect(()=>nested?cell.nestedSource(source):cell.attach(source),[cell,nested,source]);useLayoutEffect(()=>{if(!nested){cell.follow(source,state)}layer?.connect()},[cell,layer,nested,source,state]);useLayoutEffect(()=>{runtime.reportWriteFailures(onWriteFailed)},[runtime,onWriteFailed]);useLayoutEffect(()=>{runtime.activate();const releaseQueries=retainQueries(queryClient,runtime.key);return()=>{runtime.deactivate();if(!releaseQueries()){return}queryClient.cancelQueries({queryKey:["ci-entities",...runtime.key]});queryClient.removeQueries({queryKey:["ci-entities",...runtime.key]})}},[queryClient,runtime]);return jsx2(EntityContext.Provider,{value:runtime,children:jsx2(FollowedCellContext.Provider,{value:cell,children:jsx2(RecordRealtimeContext.Provider,{value:realtimeFeedOf(queryClient).attach,children:jsx2(RecordScopeProvider,{dbClient:records?.dbClient,identity:records?.key,children})})})})};var useEntityRuntime=()=>{const context=useContext(EntityContext);if(context===null){throw new Error("Configure an entity source on CollectiveIntelligenceProvider")}return context};var defaultPathFor=(contract)=>`/api/resources/${contract.id}`;var createDelegatedEntitySource2=(options)=>{const fetch=options.fetch??globalThis.fetch;const pathFor=options.pathFor??defaultPathFor;const sourceId=options.sourceId??`${options.origin}/api/resources`;let cached;const snapshot=()=>{const identity=options.getIdentity();const status=options.getStatus();const next=status==="authenticated"&&identity!==null?{identity:{applicationId:options.applicationId,organizationId:identity.organizationId,sourceId,userId:identity.userId},status:"authenticated"}:{status:status==="expired"?"expired":"unauthenticated"};if(cached!==undefined&&identityKey(cached).join("\x00")===identityKey(next).join("\x00")){return cached}cached=next;return next};return{bind:(contract)=>createResourceClient({definition:contract,protocol:"entity",transport:createEntityHttpTransport({authentication:{credentials:"same-origin",mode:"server_delegated"},destination:{endpoint:new URL(pathFor(contract),options.origin).href,kind:"gateway"},fetch})}),getSnapshot:snapshot,subscribe:options.subscribe}};
2
- export{RecordScopeContext,resourceKeys,ResourceQueryError2,unwrapResourceResult2,createResourceListQueryOptions,mapResourceAuthState2,hasResourceCapability2,clearProtectedResourceQueries,recordIdentityOf,identityCellOf,provideRecordLayerModule,entityScopeError,EntityRuntimeProvider,useEntityRuntime,createDelegatedEntitySource2};