import type { Constructable, PhysicalStore, StoreToken, WithOptionalId } from '@furystack/core' import type { ServiceContext, Token } from '@furystack/inject' import { defineService } from '@furystack/inject' import type { DataSetSettings } from './data-set-setting.js' import { DataSet } from './data-set.js' /** * Resolves a {@link StoreToken} to a {@link PhysicalStore} whose * `TWritableData` generic matches the owning data set. `StoreToken` defaults * `TWritableData` to `WithOptionalId`, while a {@link DataSet} may narrow it * (e.g. to strip system-owned fields). The write surface of `PhysicalStore` * is contravariant in `TWritableData` — a store that accepts * `WithOptionalId` also accepts any narrower shape — but TypeScript * cannot express that with the default generic, so the cast is localized * here with this explanation rather than scattered at call sites. */ const resolvePhysicalStore = ( ctx: ServiceContext<'singleton'>, store: StoreToken, ): PhysicalStore => ctx.inject(store) as unknown as PhysicalStore /** * A DI token that resolves to a {@link DataSet} and carries its model and * primary key metadata (mirrored from the backing {@link StoreToken}). * * Consumers can `injector.get(token)` to obtain the dataset, or read the * `model` / `primaryKey` fields to drive reflection-style tooling such as * entity sync and OpenAPI generation. */ export type DataSetToken> = Token< DataSet, 'singleton' > & { readonly model: Constructable readonly primaryKey: TPrimaryKey } /** * Settings accepted by {@link defineDataSet}. A subset of * {@link DataSetSettings}: the physical store is supplied by the store token * and must not be passed here. */ export type DefineDataSetSettings< T, TPrimaryKey extends keyof T, TWritableData = WithOptionalId, > = Omit, 'physicalStore'> /** * Options accepted by {@link defineDataSet}. * * `settings` is wrapped in `NoInfer` so the `store` token alone fixes the * generic parameters. Without it, an inline callback inside `settings` * (e.g. a `modifyOnAdd` arrow) triggers bidirectional inference where * TypeScript widens `TPrimaryKey` back to `keyof T` to satisfy the * callback's contextual typing. */ export type DefineDataSetOptions> = { /** * Debug-only identifier. Token identity is established by the returned * {@link DataSetToken} object reference, not this string. */ name: string /** Backing store; its `model` and `primaryKey` propagate to the returned token. */ store: StoreToken settings?: NoInfer> } /** * Defines a singleton {@link DataSet} token backed by a {@link StoreToken}. * The token mirrors the store's `model` and `primaryKey` so reflection * tools (entity sync, OpenAPI generators, test harnesses) can discover the * dataset's shape from the token alone. Disposal of the owning injector * tears down the dataset's event subscriptions. * * @example * ```ts * const UserStore = defineStore({ * name: 'my-app/UserStore', * model: User, * primaryKey: 'username', * factory: () => new InMemoryStore({ model: User, primaryKey: 'username' }), * }) * * export const UserDataSet = defineDataSet({ * name: 'my-app/UserDataSet', * store: UserStore, * settings: { * authorizeAdd: async ({ injector, entity }) => ({ isAllowed: true }), * }, * }) * * const ds = injector.get(UserDataSet) * await ds.add(injector, { username: 'alice', roles: [] }) * ``` */ export const defineDataSet = >( options: DefineDataSetOptions, ): DataSetToken => { const token = defineService({ name: options.name, lifetime: 'singleton', factory: (ctx: ServiceContext<'singleton'>) => { const physicalStore = resolvePhysicalStore(ctx, options.store) const dataSet = new DataSet({ ...options.settings, physicalStore, }) // Disposal is delegated to the injector via `onDispose`; the dataset // outlives this factory invocation and is torn down on scope teardown. // eslint-disable-next-line furystack/prefer-using-wrapper ctx.onDispose(() => dataSet[Symbol.dispose]()) return dataSet }, }) const result: DataSetToken = Object.assign(token, { model: options.store.model, primaryKey: options.store.primaryKey, }) return result }